From bf24208898947138d0e232da63618db5b7de5d56 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 27 Sep 2019 21:10:01 +0530 Subject: [PATCH 001/289] Initial commit --- .gitattributes | 2 ++ README.md | 2 ++ 2 files changed, 4 insertions(+) create mode 100644 .gitattributes create mode 100644 README.md diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/README.md b/README.md new file mode 100644 index 0000000..d2a77ba --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# Standard_Operations + Standard operations required for FLO Crypto, Blockchain API, Supernode WS, IndexedDB From dd402cd4543f1033b7c901538336f4d779929823 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 27 Sep 2019 21:34:16 +0530 Subject: [PATCH 002/289] Adding files --- .gitattributes | 8 +- index.html | 1126 +++ supernodeWSS | Bin 0 -> 176456 bytes util/mongoose.c | 16548 +++++++++++++++++++++++++++++++++++++++++++++ util/mongoose.h | 6683 ++++++++++++++++++ util/websocket.c | 170 + 6 files changed, 24533 insertions(+), 2 deletions(-) create mode 100644 index.html create mode 100644 supernodeWSS create mode 100644 util/mongoose.c create mode 100644 util/mongoose.h create mode 100644 util/websocket.c diff --git a/.gitattributes b/.gitattributes index dfe0770..ca039ce 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,6 @@ -# Auto detect text files and perform LF normalization -* text=auto +*.gitattributes linguist-vendored +util/mongoose.c linguist-vendored +util/mongoose.h linguist-vendored + +.gitattributes export-ignore +util/* export-ignore \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..1112ff3 --- /dev/null +++ b/index.html @@ -0,0 +1,1126 @@ + + + + + FLO Operators + + + + + + use console + + + + + + + + + + \ No newline at end of file diff --git a/supernodeWSS b/supernodeWSS new file mode 100644 index 0000000000000000000000000000000000000000..1b2ed59e35466dd31480cdae1fbf94f5a4e346a5 GIT binary patch literal 176456 zcmdSC3w&HvwLdGfE5Pq)qz{_3{!P1y)s}i|L=G0z0aIE&9uGu z`v3fXzd+}lz4qE`uf6u#Yp?x0_eQS1yeb$Bn7>hhj|3#ts32h-G4$OkgAxb_rUb^~ z_xQkv0tWy(8vnvN*8ePO(&kyC@kZgvbW=20|MNJFXP$;bKC5-yNRROOilBK00`-E% zbmX;hhKg^TaiYM@vwNHb1G5iNPm_+=Ojo!{r7K*e(z#E~SV2Ec`B*moyG|wB<2eIy z{4-DD@~`<1(Rq9y|A8Xtf6h2a&;sUZ(p`geaXAEB;OX(EZ0v-I*}z0Z94ZDg+NJ z2T5or=!^unh-1Q33zi3i(c}K&P_;{<#(4CqZcSi1Yuw0KiE6A6)@Hy8=Jo zr~qgC9Etv<3hh^(Em#X{I6HYx4r`Y`4#ZzRmk_C3i#iv0RL2l zeC-PO=?eHisld;T73dsV0lu&T{HO|WcDp0ByNwn2+)@Gm)C%;&73|3)73h4c0-doH z@QD!`wtK<76V%A2SF|5ye3->iWD zR)u^Ys(^n-1^5RQ==`Dreyjp~W(D}u70PvK1^lHI_&L1-{JIM8(G~JNzCykqub}^1 zE8zdWLcYBf@b3ZqM5OWmbpbGve*UNe|Jy6T>7I>5=RV*c8aO(TZC1G(zqAVc5FWUu z93Fr_H<#|)`GMt2=iV_t8d$Jkacud*!1Cy_xvh5x7DksYSuDTH1It^NEm{&?z^Em2 z?`-9B+1!Q80<&fGJvW7A*@bS~5R6Ye{tJ z91p5snh2q_g!wI4y6g^MEsxHbd&jJ~3-6et4U zrvT@#oIiK*{J?_S=11qs@AAN0l>?G5mVB4Y3oKuB+x$CQqjxWdjF1Z-vu4d-wrt7L zSzu;PbkWi!fm;^=aqdEvnT$Y2(WSB0RxkqEl<(5kXaEeI6Iii)i7U-{OJfjwYmB)s zpFjVOrRSfEGR|Egu;oIDk`ZwRmdznAEOTrz1maS?Q*n%ZTIbJSwqy!w60$OD z*4*gbt@CHyN=C`a{3R!8Y@7TSNK>CHlj;eZS%km3O8r&-1!g$ z_*yw<)`CUIaM5SxvoI@ejV(YymqZt{)ORjjfxKA?q#<3UbKrI<`K9JkQBa$A&RMi1 zuwsFhC^T*1;sAe_lXcemO5jC7<%+AXy!5hJ=bZUr_w54r?d(!?>Ft~|&kM}D^17y3 z5YqhHsD{g~Yr1Ul(k1h+n{z9aX4b6R?p(S=voTAdj);i%TD8Z2Bf-kCM(vTNJic;> zv`3evt}Y9WoU(*d&f5VxZ4jeyn3#YWM;^Xt(ZL+4{RQ@gu%jeg9e7WNAN=B1FpL`= z7zKOF`0)}yDsYGn$BtPvmO0fS%s(?OH+Cy4T5f@OB^kEDi7U!SB)VE+72M8otg4 ze_X@6eeeMd@A1L28s6)J|3$<5eDL=*JmrJ`Qp+dngAWcW`8YoK#32PQ_~2)1c+m%+ zs^Ni1c|Z0G4X^RRui2pJ*ZSa3YIvOwelrL1_^bE9Z(Fb64L#eDmdLR5hen%?{d+39|so_(6aD#98;0C|h2j8LT%=WS^;2ftRs>wR#8-{6Dapz){p;5TV_*ax4l;mtnyA`PGE zgWsj$3w`jZKIDV{ zLc`NO_^&lQ>w~|p;f@cU)9|7X{wEC&SmpKpfri)m;K8iY+d3coNDXiB!H?1KMjw2l zhKGIdQ#9Q2!9SwmGkx&OG<>!Xew~K5`rtQe_(~sqk%o8r;0C|T2ftI}cl+Q*K0Q8o ztH$s1!J`_U^1(l^;b|W{q2U=H{80^eeDEF(FZkd;)9}ER<@Nq^4X^RRf2-kjKKSo7 zyxs@jrQwY}cu~Wr_}~Y=q4dh~!4KB(W*_`S4WI3UpRC~veelaPe5DV5g@(8L;PW)R z%LiYm;p=?xl^WjTgWsd!y*~K;8lLjOyEJ^r2mgVFXMFGAAF;R7k%&- zHN57ka(yuLYklxnG=9Ag{;GyI_~378_!J-fZ4D3m;JY-u*#|Fb_)H&s^qWe57W&{d z8s6%IAEn{#KKQX3-syv%rs3;+@Ut{L<%9q2eZ^1O2j8vXSs#4#-xYq1Z{Ev<>wR$J z2RHcOztsLlqYvKoUyA;e3h=NG{=qv6-}1pTe^c;gAG}*Hl+X6TJ9K#$`rx*PxBB2o z4PWVle^JBReeks!-syusq~TpY_}4Xjoe%zqhIjkm-`4ORAN;!--s^*ZU&H%+@E>V- z$_H=M^*-c-_h@+fz>Za1VZ`2R_~d@AANp@W9u3;75Ak-5&T+9(a!j zUgv@Ldf;5+H-CK|_%Q~EXUYRV)&n2%z>o95(;oPTJn)PMe!K^s^}r{1;Eo4g?|~OQ z@Dn`nq6e-tUPpecr2i8=_%$B*NgjBu2R_LIuk*l9_Q2~s@KZeS1`oW!18?-eCwt&i zJn&OJ@URDdng?!q;9To6f6X5F83u^wOb`4_4}7)Vco*p|jEh z|F8$%?t!1{fp>b~=Xu~=9{Bkl_&N{#0uQ{~1E1=F_juqJdf>et_(dLgp9g-i2cGi4 zr+MH*9{5K*@U#bhi3gtXz{4JR)&rmJfjb`fr5<>}1Ha4zFM8ly!*>64|3Vuaae;wA zjR$_Y2VU!eU*Un*dEk}@Uhjcl>47(R;8%IzjUM<%J@6?W_|+bG*aL6!z%38_V;*?3 z2mWyne5ME9?19hrz_0PZ7kc2=df=@d_$NH@l^!_Pn9X0i2d;LsshCa={Cb0oXO{4Eon;5T{Ty&m|@9(bPzev1d5^1x?#;6onxY!BRu@2Ig7)$1pn z7_d50(W>FJ72j0zd|>#zAD?()V0hA#_zg`6JVY(!_b_sumVK#$YtAv*^Ocx|KTf(<9 zOxGjVEa6)jrpuQLOZbxv(*?;jO88oa>3ZbqC43dbbUAXh626pSx*EBFgfC>6E=I2K z4*({e!!TWoTvo!TGEA2umzMB}4AYg!r6ha|!*n5Xy%Ii*VY&{vZV4aAFkOaRmxQYr zrmK)^m+<>1AWRn_*DB$i4AV8p&6e=n4AUjZHB0zShUp6A!V>-s!*l_1jS_x^VRrqw zdI`V4FuVL*t%Nr+%&tBckZ?c4?Ba8U4_N*mGhEMbR>F@n%q~5bmhd+jX6KztN%*S_ zvkTAlO883*v+K@vOZW>6v&+tPN%%g7*;VJ-CHxtN*+u7CCA^GbcFnoj626^bcFDPB z3E#>vyW(6}!k=WAU2v{Z!q+m)t~XaN;j0*Cmz%4V@TCm1tIY)@d?CXeD&z{grT!Ua zmz&E<_*913)#lO?K9ON|vAL9lk71ZyYpz$qhcV19HP&Z@ z68&c}gdGI>nve=HanKH>+Uu`4tIwPYoyJp_hYtYq~U@wBEEE&C7AqtR8|2OM@42j4uL zU2tY-!WyA}^YiQ_N@1kGk?E4>QSL3){sny4yU_*{=8p|EKt55VqcwD>~Ty+95vQ_cy#YEmcP&~kk{EQd5YSodzh-WYH=C>9YhJ8rdvSS6y zZebCMgJE{V5H@Ar0&uNwWkm{B^4u!K zlJTS!1k|yw8W(!{5WZRKI2_&5?(~>AeU=vQR&aoAP=YGk=Er7;T!Ksn0tLlib&Pp~jixN)0x{q8z#DZE?hDrgCfV$gC z9P!GrCn8I#8;Opq0w*ACqh5uHAuG5s^mMQj6pnaIqbeO7&^kD@_jD!3r+~yfAz?HV zBt$d!hlCX9bl95{NTOx8HTRYHo0ov&+DaV9BRfVR_lqK1L-#+1ddox2{bfsU4om|y zo*mVZie*QP50o@I42{m9DWvU|E#(z=rMKeJBURj%@`@|r>{)RhR94&wsI0gXj`38S z(v%G;s4y6O6`I=rx8Y&cD2{mdXob0Fz3rJSu9KN++p_8c#^byXLS6|?W5b<3PYhaV^OQ^ zZGXkvFd{*{0F!EO#>-z*&S-l;SYty3#j!8hJ3DLJ+jau`MTPxWSZl%FnR2Q|#(oFb z-&EK;2eJncyXl=h$;R8Zk5aZv8-zh;3_66)NCAuvN9Q4hW5GVSu{nsYGxAq3KODVW z$5y$qzmV9SV0Jj#pkqh5vEP^2ciP+D84h*4%{my}l@E52tIZTqTRIRuQWT9nz~qgV zowhe3Hf^IR?m8{9-QVj~FR6noLE|59a{^J;sMzplQ0JCi-Hh1$LDpdPWq9Eq;)^u4 zxBa!$2d&=GjTn3VVieo5pW+zOUb_&#DEsJ199J-dvs36_IuQuqDb5p~tk^)J`t_qu z3{34{`c>e*`Zox|4~iWqW;6HeD(2fky3G3GoqVEH3KC3%dVBs(Jk5VsV z?;Xs=`{Na7g8EWlfEAt~j_9v?HCU7yLsM zScXCXogExNP3=~aUGPgRUeh}$Ua}<%%yq=HJ63|hzB)yBohms&8|o#`LFZTqB#~q> z`fppXV1YgK?%MBIH|V?Osyb9VD!T z5V&`pNet;T>E^(NsIOCxl==#-$%3Oq^+5>Q9Z^Ih?hwYISXX2Gh7xz9J@%;5MtY@) zcBC)A0B^L9Lsp^<&{&^kzl?%9Kf)jl{%|d#Gjxn~9jNZKvtv23X#X~U(YhoQF9g?M zszof5bkG}8ai>u+lW(+=O|U*K$SKwhl0BCFu4Qj_PR3BjWi0^~J5r&J+d(xUDtVC< zWz`r_#{5T7rgM%^`UyX%`XA$2zUm18DRjH~?}r1FIAR>Jq+Va{XYIk}F`q%_BGj-b z6Zk03vp#&Tw2^4FbKhTvhjjy8y@Rr}?DY*4qy5xOd8}1!K~XilwRE3}NbC-fn~Qz1yz-UI~QJMx&=# zVr3w5?H>+0DUgKT9IzntmsB1eN+i3}3Y`iyi#U8q?F`i(@$mX!U}xx-jXOg#2X=-I zjbs3Xx*>Znb8r30!yIEX39GjMdyhYUD%;!3@4L+nzG9+fhm95&WYa^l8v;lYw2t3P zx*)vFLcDE9;O-i9wBzD;7J>)`SJkjTO$GDtmw>^cNhZ-Kzbi-cF(VNMinyKQJ0N#d zQ1#EB2?i45>7Zob=LXZsW(-gYap&?ysXL*C;!5s{JCS5Fe5;VP5gz7@^# zKcORk4GRU+QLG+#Z-V^-&B*j1T*6(+&eK4^MHzU1j9c*O$?-u`>`^mP0<(2b|Ml+{hKfPu8b)PUUC~#3NQb{us3w15ct|2%vbKDF& zdv<2V3C`IWDMvaH2&QKQ3p0|vD<8f6wdn(!$3%jEo?$yP&d$y_p@3h7hAv|?QG=P} zy6c}AbOxRuHzWAY3>z5E2^svjXf=vrc1E)Mx2^RjO&{12njYL{1E(Og5C5{LxLr!+T-!^b(UBUi*|?naRcy zlP4b9b;sVAJl8P!4*qLfrN(V>#INkvjA!~Y&m4Lm;SFHDM-DJI`~@r@Jq#-vmtnS6E31y)h|b5{8zi{=b$ucI5MnK@6y1sPk z`)GxmN0*e*qqI_HvbXwgpZ@&7^9Q+_=&_9+H9T?7*Y5;xwXPa^v{kn$ayD+tA82#N zx{B!GOboJ;-Hf+4JX(=6F`wk@yTAP1M=NmVk=pE!{uE7aWX`lnB4@47KDVI~XP#Q! zyy|NWBXef#%loH1@^%HTJPOy*_?NAfxDq2UBS@~QKh!z85?7uEF*UvQ^^v(kjf-MX zUVnJ#w{KP8%+p?r_k43gCC)@=6=(CWe`1s7%+9=puufwNaHt_s`(gi#3rpK~(b+NSiumwCe@xkwbH}=5jt4R;Nzl*3p7a40oK4!^Wz+`m-hP^%F+Y}@r0w5duQY85AkFW;f8rQzMz>$B`DMKeE6s>gkVY`=0JNNSBg)I?7%1z1Hv(PeG0=%qPT)&HG@o3I1J8INb%Ag-nLW3D_9|r}0xyb-P8Q!rDlg(3zNG0Rw zlYomAV7vgNq(Vxu^PDEKfzxQDT9AnZNF>pW@ex2fV0&CwDS)J^`Fz4!y@L~$n1$gK z3ua+j@$gPJIGEH-Bnh<=XeMCN%y1>9qcL4W!Stf#^;wDO^$0g0oI)5A5YrnGo`NuD z_^359otD5F(f#HfqfyKi>WFZS9eL0VjFYKDm4xm2;Y8%Y4@cHbjCA4Ge%?w(y4`yH z56luL$7A;3{()3=FkSu7-S>Sm7RA!Efi!zexVQ;E+15NiM z74W+zMjpnmPQ@uv*50R0s&(E}4-Pavj8wqCe_~`EeswC&pfc4(Ce?%9R9yp2>yQfg z4^L$29@eRhrc|3$UEWmp4>Uc9RC`E6&Cd=xzr+TV{g=i8n!|@os{N7%cUG}nb4{xK zk_KntnCc9ZYQLm0R;PLw8%v~I`y~y|&oQq7lWMTQY05EJ(Dr$?pk!5dTWLrO>uF1Ik@ll*x? zrG5f$Og)nB&_d9tASqZ(GgTjddR5Y1yfLX3*(3Sam$=4-W`dRlNx|P%rh1k?PpYI( z;*CkQyi`&xFWL&47bFF98Kx3>_o<|PV1h}tuvAiQW@s>IV~`ZgZDUdq_OmMKvtWWr zwWL&1ZEILi8X6=8bKOiTl1{0lDKNpLT1+abHaH$Jfw@PSRK&bVCEWxjm~5r`Q6v#_MkPhV$S~Pi=b&yI8 zboeXxD=N~S0ZEg}kfOr&EL4;nH5FsL4pOOs4sY&ZMMau6AX`agi=x7&EmV|9H5FsW z4pOOsF7gq%NGk^)Sg{@quDCue{#-xoTU1{(ju#HrCBJO#y)vsq`r-XrX;VWxu5><^=>ck;=1* z3R>v1LS?_DyI1?N-_qTyec5m6?$y5Rw{-VvUq+N}$tM)60%vC=-$9G?)Q^1qyppjk z`GjIhkaQ&9LCaAkH5Rty6N>#n(vf@zEj*RfnAMU`C`JQGNAexC#8gsaOG`eXSPCQ^ z$?4Z(Qb~;gEs06Y1Coy9@$W-SViS;bBzJ!wViH4uq$BzI`w)|~ek2ta&FAayLrl`- zkyKnXpRd0UF-bc|(vf`qeTYdKH+eHM(xQ=cBwv3YVv=Tzq$BzI`w)|~T_hdJ z*WZVjq`@NTNWT6)#I(2ex(_k!t-bC;OnYmu`w-LK+UuTTGBaeg@Z~r|EmLHiESDFV zUB^UXDbUgte8C%Clkh~>Bw8LUj~?fZ9+zlYR~}vKjmAlbhb0=5aWdQN&dA;I0ynBZ zj9G^OoJCCK!P&#?9-K8y_`#LM93bZXB93?a(QQA+9OLRuoQ}N7-7!-HR`I{Lf2Huo zE6+=+a2@mKYofW156tkJoiW%{WzGlKE!z;ud4IE`COkgTvTfkaQSJhOj>jf?vuIG~ zE*g+B64xoEHHa=Ic>=n70oO;dLBd zvwGHk5~L_G$!4r007K0vU-mYpu|Fh-O@OMH)KLwHibslJ6gHl^WNKvFT^Vy;V9a2o zNO^#h(;$k?CcW&G0uyR!L~Yz0XW2XTV#On<6*B{^gofGbSlT;9jD4?zksYL+zW~$s zqe5Rvg`Q4>;WTEct@y^#iR-#XW7hrMG&Z^qWJlQpzrw~V4rz9DURPbfRxoY@8?)m1 z&5?XNHZbOyv|mlr%GSH9Fb|qP4zbwywP)<<6$hnhQf|`<29a=w&&JFRN7uo?NhB=&aRz9=>9;ko^?O>+1Vw2f;%!Qs`%9 zE_6PiRP(Z3cI}(pC6m=Vn!zgO-ZLzM{Zv{WYlq~KOyPkYkbQXgq;1956E(bIu9fU4 z2=<`!3rr)T-7|t^N(xOAEu|lYX;&+`RuY(Pk8-+a0!bK1ha?;nLfim`2+sbOx9;^v9B32{a)UrJLbPtP6uW=f*6DvYjGP$Nw26rNZJv8g& zO|E9?6KZIwYy&vXHi|Hr1i$k0>`lu;aV($n=mExS~O$Po;oDCm}- zArG^^GByTllG#8E#|cRhXYORFn6JQZuEk*icS+L2xGt?CIIE1uu)A={bt}7x+xQ(3 z3Kl;Du?aZn_=RLJ(0?WtORVI1hkTl6AEzCLhjZ=oQu>Tq%;TO~mT=<=rn#PJ&QfW9 z(<*5kJe=d*G+~xFEy$CJ+^CShuaI9P@?VvBK{#N&n+AGng+4Q2$(aFWDMd@Ep1^Pr z`h2_8s<2dp?fPlR2ayNjfhEdwvG~p4Vc3q27!*19o)zSdbS@V^3r&KMhXT`uluc4YbT+wpAB8oQAo zZc^r^<%8et;-=*r2Ns0RtbPaY%MU{I=_$}C(wZLcqp|^6lx-HvWJ9%hTqJh7B)=$96j4CegrG0U>E0yj zNDYz!31!KtffI;VHus&{zMz?{hbC$qF;c&FY0y+X>Fhb@XsY4rtK~l_? znr?pMK1{DxX12au}Kcy&LRfohB?IP??!3te&1eTGO(}X0_g|B@UU8QW{2*heZswh$| zaBDsH_U~{jrqMOHI=_$pkMdiO3p4he-zQKBmSsb82Q2$nmi>-cc>CrdyX9GkGb>Uz z2A`%49b7B8Pw|Dj=7-{K&jzAn#3RjD_X|ExEe$$bmDsVT3H=0{Hn%-ArH}^F6p`Et z3`x!d#fU^iFuhqC9Z=xDi!Eh4;XBMle3NBHKhlYV?Y~;~3sM<2&zFl=TU1=wzvSVb zqtKbTqOFyZj+g}Y80sZScwAd0!H)hi$)H>}XK=vObbutmMV_(UH!!lBC8!5(OS zJdYo64^;;G;VgSe%&;kiUAz*9_Ss#$cC|ey>L_XnqBeHEXnoFq0t6|IqGSW@fmTUq z2qzw*Az)^8IIz8d7xa=VprZI6CPem=)IjECY zZqsOne6C~_r~*KGXeDwE7agJ9G;}o%cYy?$MR&>ywdI&Pbbzh|8wx8;_~=_+gSS3F zS>0?)B?xf}NP}k^#1KQfWoPXC#H}c3alM#Y5~F33cI>$B8=%_uKpTqz-fjR4DCxgJ za>h!@2yX8cB5ncs-MB)Z2fM+oq;sW|Qd(LS*t4LL%rBi>KaU}aUYKgkAFpdcB$82Q zHCZ1k`b0zaqO#0uf~aS;EfL(c?4&!i@? zg9k&;xX(iP*;Kfj5Qt#Zhf^$m`VkB)kXJgDwi>Wp`Uc{{f+2!!$gt}@# zfiK5UBT94_WWNXJIfO*%EKtGWK3Ne&;4kJ!}fxohF*^sN!o+muzHw$4syI(D1vp zpmJ4X0|A)-Nzs!`o`-q!Ort$}Gl39sFWK)iU?U1YEu zqlH=pve{UmG~J2Ac;y6M>;qxS1t(mCsVIS2_Ek09vxn`J*nfjqp?hYigOht@uv23z z6yg7MUR#82ep;esi$?@onE41I5O_rqh@h^F7tg-yHWWDNo*!I27v~2@SEi8UM@PA)9=$hAwL|#F+0%QA6ZqWQ55(=n&EqVwRum@)B9GtKC6^$uQejwO;hjQ+4hQY(+OHS+i;UlLJ= z67J6>5y@mDvri~45{jophvIP1c>#j4J5C2mLVm5pdR|3=rOu1ZEg1JeV(#dtQATy8 z^Gg^q3_2H5rW`Vu3(Mfg=?OSEZ9G||2M{v=cOb`to}HyH4GJUNtYA!_rfK`5Uan5s~x>)KCtuaN!U}A}SAXr5w>>=;=c{;Y}WKTnQ0a z@oZ>hM14z|gXAb2*v9w_RUav$-b)u?#M^eCwdxT3PQAAV%cHp5B!31%vjw(5!*0kQ z4Om!UmuuJs+T~G09!~o-K(r7>EQ8$At|+g8$TA`UGot~4--{~Zg-LXsAxk+Dmf;vs zd~G1y0)*taQHaj!;%B)k2v@a$S#c3(dfB%b&C)=J8;lN{#TXQn)NuXYpz{S+1IXtT z@ChC{v%ovqWGxj<2J`Pc(UsBp0b|g49Bc@an2wjx0MZOP4+5$@JszM6#Ez9@XjDDd6F0FGs-h3$yxw`f8=jIpu!m7}0%sbpuW?UqU0!S1JP^f^99D;jg!Bp08FY3$ z#);8w@wRP&ko{9|BzS7!EtfQ5PU_%z*mofLcv~tElNowAssZce`6;9jQgfgHYPK3& zy7{3YjU9|^W3A<{Qn~MiMYQ8quGy8bimW3ZHaizl0|W;{g>5j=VxIGNlM!qzxTh6R z&d;nP)4%xczPOsccdj(CxrGtf`T-;Y>5+>>8`siZJ9;h{u4qRcGS=s?6qsjB#Ije~ zDO_VJlaOdM*x<0)QKxCpc-1Uj!Aq>tG#Q$q%uR~+yabR;N37QhVXi8Gr^6v!N_Y3}5vAVJqA zzhF&9ne@aW7|GXz0CEK+n0A+D|MRp@5$099}@W508C(FsaB$2P<4VGGx=a%gXr&8&D$%=roy0hr;-C(-oqa zK8^cJL~L0Qb<}D%{Q;R}?ft-0Be6PE47^kx3-3kein>ApU|CnI3d7~E!qt!}EXtP7 zeFwTDT9uROuu`$8P{SCcu&ahX(s-*SqqhN^`h4t^Jgzhp`D+(^oh%11Z%8qc3f*@O zs+349E9+-62r*Z-G%XHca#tl>*g8vHtB55n2)90(io+Y{lYJn7MY%Xf5(7qGcBPTgO7- zlIOkh@nGON%p?SyM}HvqmSHD|Sy<hDt3blS&E zHGKd_73n{%l7weZSJ#k13f6Q?s0yJz8d@(+Y~zWI#U*WTgG_!5Uf#kBY{F2YWh;7O zXZkhMo3FIryAt=tu^pn`Ujc%u_v{Z*@9|BnXcU05R?@wYTt?5u@2KdR_#Lh94i%Kv z8lfCawM8hif;_s_+>dh+y5OU>4B?_q`xeq zwdfq3U^W&@RZ=co%bQSDukBKIM$Y#&X*sXLiwM|$Z@P`vs-^n`z)HIJq1BZ%yq@~Q z3jwo!FBkb?i%obXZWa7FHsB20Rh7SyIRj{|#7_j5t)Drtyefa0hK2z>l&vb_@Fqe8 z!YdW4UEPocyg!LUmH*@bgk6{99GKuPAeQZs{M6T78)6h(1kgN1kqlexY4iyA6b19d zO;#=j8x-ml)y6FgrIoP8y_H%k$fQ7xYB*dUMiU!!-bOzpGR*OQU6rTk(jTYT#!>8+Tf7&aE^(e1m756(l~JhI%xMW(Ryr2AFwOOQwAUvf zw327ufc!G(l~{?H@*7w_AsIw6gW>TUs}dn0*Y0H0?yn4TM{dn^a+BGo z)S*p{PgH+y{Rvp#sY932i8pj!^`KEp6=A1_Knto2=Mw5j+HS5#LO3P zn4-b#1ZUf;=U#8@R>!V?I%?uJfSGF>5>0^r+!}ael$AV=npHCm;qjiB z@rb!z$LvK}r~!pM_f!@rY_&fGujOX9pxdLMfiQ2}z&jcul5uNbY=hAS_P%?mPq-p` ztI&#xk!jsp9?jT+Arnhpk4nGi%LboyUBn!o4ny{X4(IgX|GTZYp1qd7KQ<9Q31?Nz zMv%*qj4lRru;|la@om{E5KkpUywYV+!bH<{PVtE*s@+n;Sn-}8kRmcUEwWqZuP#8h z%B~5rM!o_)i7S2NDsY*e$27T|07ynUH_W5`K+(RqgA+Py;%#dJt1w(_>P)n(!A^T= z0&33jTex5bTzBG(K^MAuxwO5LO=BE5>m-ezf0^Zcrfb$?q zFO7h6NTD@fV)>!xgW-BmQYugP!R`|8QMyo0OEuRy?e&2God=jcwu|OgJjE7qXxU&! z4B-Z4(tvSa3dCW&Z0xjZhUaV3tOBlmRG48E>;{^=4u+?Yi9C&4J*$#7px#OzaW_Wz zdL*@H;h+Rr;GrvO7>?Bs$LfYLJD?2kE(nahkz3&Cxsp+tN3jqDz!g-S{fERudG7xr zl9ood#ej^Z%eWf8bWg5kn~oI2tv=2TW4zVl>r}NN(aSc-Fx5}xa1G%#&|5+m48qI9 zOCJumDG?3z(=mp5|Au6Z>&L()xIPr~1VgL_pu#a!dpKO=l^XeIh0JN0p#!c?!XPBu zw#%GrQqH#xS;<)8di?CTzR4cA5}Q7g=Ut}Ks*ynh?GMIX@nUuCO3bwmWb3#vo5f|+ zWAWUM8>snoaPjn@^Vu&!Sy|&LyO~G3u;C8Sr@(`PF0h-ca)&6JKg8yGJ0(69n}YQihNM9^AO||FIL5Fb*bM_Mjc60NZPBF;rpitvD+`S z=BrAUz5Q@dDa$rR)A`a{(r@Xb6ZGKwsExVj1r1}9q}(_MDV=wnmyN@OjbL<=3}8w~ z=XsI-1Zm)_M=@S4rzG*cF0Ul=dTZ&8?55_jiD3@OtSs@az#Y^6flqwgg~2WS;>q|u zJv!03K{^DvBoL0to*NRQ)gXu29hL(|lmn=7#!?)M{N2XX47Kg^sVNMr&-d#?5^&ZB z?_FC5yoS-<_HYAdvinpGPt9eTuUPy|34aK6gXYmp6F_q925g&GLc2>){R*fI;-E0{ zBvz_~rC$M+-aVcbw~wDeLWTme;zKYFR7;T1hKP|eVFQr(ZMWi<`~I77(HE+E#xyg2 zITD^0Y|@84)Zin5P{OK5aX=)}H(l*xPEMP4iE*4h{BI&OM3>9|YY!Otn`KDHOw;t= zs`4JX*yR0HxTVOOTg|hfXTnuVg&fpJ=$QRJYa%djRohG&?CiRQ3+hAo-+Mc1gnnkc}N^(;j} z#b~9L8a)mw2Qb_fZnl;VsY(e8Ul2m!P!X<8Ks(VV z`k+~#L1f9%WJS2z>N6XIkzL4&^#K*~j@)O0E66Mct%7!ODh-#Q_CKjq{XeFf@yZX^ ziK-tfH=lxrj6)7ZOHk^$U50wQV8|bM%*}=p+r{-q3L8n9E$5Y^N;*bJt6~W499nR` z8_+X{lhjNEIHn~fgAQtU9en|N>3YX7?f&63NwSksSIfgob7PiLJVtm z`H5h!BXu|GOoXCl0%}Z4b?uO&)MU_^1L7=^&txq8Ldj&9OF7#*VKv&}XRm~6daDAr za_Zyt$Q4MD9=J2zbTlMfRyDKX4RoXXO2ZW=9n?}g=Inb|MGxb2K6pO?sd{t+b0@2M zv<=N2jxuYqESzd=p*7!A-Mh+N(ueC@$@~O24uY-Dyaj1@OKRE{^g6on{{+QF`=k@t ziHgCY$w-fEp#~pfuR&MZ=~7Jz1GUaT>_=P@;ajMKU+DnB-tsAozuHoDpklf)Avhcx z8jhugV|~N1UQPJPUBFb`Sf?VnCZhz{lW49dUzk5o?6p7^?9Q6NDwm%)3E)~yX4P&a z?{;y7c9)>~6;SEgP&oY@ly*Vi5G;nUGhuKPUb*tmi0VIoeq zAqGw)%$i~v@I0YR;1(_~07M+2PV@<3AVA4w%Ti3WydKk7 z&c#Vo=RffwWHUG+fmThJ&z@4a)clbvWfkVCO%%;v*i|rT{_P}CYW`o`$)OAyLiAKc z*|d5|M`@O|`gY_YIF|NQS}4cppF=F;ES1DUZ7Z9%dP^Ys#WQwx}|EtVI(tMzF9`g{&ay=3rcr$ ziP;p?wQ*2jHB&oXWp|--7e2~ubPci1*ygew%F8An--ycLF)-(0o<}D+J+1rz&W8$t z=$R@Pqd>wP6$ncNrEcRR+o3?_t9E4zA9L4~IsvtPO{RRXy4Qb$lHnK6F>d2r8SzCw z$s9{=>o=9A(40?h|=v##M*ry3tFap|W6kJ6O9_!0kv6dsDgF zwYc`)Je`3U2LS1Xreu9MK{Si+@)v7EJzXvX)zz1|wpGa^GTE zrBX#tk~ zJ{#o;2UECA-P|D0GV?R$Co;=XEyE5*EC2V87N%u(zNpWECvIeiL7Vh`qf!0XtF!MEk^=Lw525oXpgcNTQeMp=ZWTVZ4V z6KkR@Xzmf|VpWbxKT&M^mDO*`bmv$!broltav7$u6@R}fHl|-GbH500&s3ZzHFUax zqxlVW$hP;vjx4#ypOx&Wg~ZBz-RgTO4Z(rr8xW6DHsY12hOTstYn9-hYDC2FQ^Xv8 zs$PEU?w3h%HqT$)9L&VJ7r_Mk+=bgjb8CU9R2}+x|Oks~-HghPDq$y=|*< zqpJ7k`u%&{TvzXCq~6$~y_Wry2*4I~@EhvE4mJX?01?X#P=Of7VP&(>%g+!YD~Z zQJIFHDrt_lY3n}xTnG8f;7Uq~5=voBb6z9#l7xXFY9f?H6xbbCsdTQIVCyWKoTN}q zE+H0(bHo!(go~{f;=S1AD9T}u!W%K!q*xCehbF>};6?IDUWM*Sy=rg8?%=9J9#ae> zq;rugrHij;>OgdU|1IdK;1F+WFb?roFtS1`J31j5h&!CX09T~%yohm_Uo&jPD*HuN zUHf&#?@aSM$>ovGl`e&t+SwVAx)OeQ`}xniT}?KJL1cY&EV3_R?FYUQ`|X7Jq~+=z z;d)W`%tJ`+7QJaq`tKFBb=eD>09+RE* zNU7)8Fl(~|YdDybZNfT^%vcR!`DPo}a0;b0oQEb;5A>qRJeFOp;Y4SQNB|Cl5OLRl zZuh1?$xS~x)WO=oG%+M_+%T0>?GS{w2grc}iMGMjMrb!Q5X!q06O0J`S%v06QE<)E zC-I0E>+ii5OG@%xBrGV&!V(sgWMRqC3rjo3(tA$vE8a*K#i8bc^me>GrXShiBR9W# z(_Fuji1f+lzWtVXBI?SW;|$ZcvSXY4Dk$4oxm{#PPRGQ?^qq#HVkPAaJaBk8e;wko zJgT!HrA}>}7R7Y~+s?pEV4OEkT0vCER;x6b#S8Q>nWdL`V%SML5eNLST9%%=F?N8I z9F8#0ghYmvC!o5pOMgk#q94bTId=aKlv()xNyaSPi@}?ig_aDj4B%wT;3>u|JdL3q zJowYpEfIcE)UEJ{q86ek!p%g}WjlssC~UmRmO-2T@;po;UmiKaNc7<-{OF|&cN`dDlfSw60`bxkhzV)EL9 z1BlugGPiq))KERR*((j!;LU$YT!n$RtL&HKZ(u+mFy&#yFpNq;RF9r)M3ulOkj&|! zP#mKf@X@G2k_usT?1G}Gpvhs}P2Mon8gznCK?X{bIU-bik_qc|!%=qKD8F|kyi(?! zTZ+2xD2cD0wZU&W*<{+6ti2t@WN{Mw*b|ljIGJ8b+laIdw}HrQTby$radG^$--{(c zP9QHQN*dH$OHqxnr=m0}YZ-bY7wH-zuPCtFhMIL7sx&;Q2eYmV6^k-;OJAaC6KG?? zwX}4o^nD6*rB~o{+ZHeP>Z((X+A_nqV!6yIItPlJ-B5>|)vkwcFk7|t2Q|QItCgaa z_Jk9RRI(yz>d&*tp|41VoN$ZNz2?Hy28tGK1%lgMzO4qwFJlM9BfEonTr2Wf+bbF<_CYg-%QG1P#0K+E0b}z<7MnLRK4P*Pw#0>}C}^#o(8#ZpZ`oFxeG16X ziSGzQujN37Oj1((jYKNeXQa3>tK=DIR~mEF$Qr(fV{a74_BoEBof}{z zq}$@YPRN?O=-@=gCOT1M2lGAFxr6y`gp)wmjVRb|pZhoc4s?j-Ffn{w3=;yfIS1Vz zVs2Z;GRpbcyAN|XQWly=8JZwtX!h50Q7U=f=nt8m?bXi;I@caEiJ2!kZ)^i6+(3Z+ zt@YePinr+TkUW9m)UR9Gc8(Q{h3o;J?sw5Tef9F#DwBD3tn9VHAJAPS@2xeYlB zWApO^^MLqo4GYcSPOHyPjc@`R8qJEa4esV?XqxYaLy)g@*y5oq5Pp^cV zfyQ%-rR_lV19#Ut88m9Tin^CUi*i}rgP7Tl!8*}Ir_22doX4baQHVn!PgMv~|IB}b zx`(PEw&r%1nCxsfn&PfUq7zl?B}eMwjIEqu*mTt*8=RTt=_H?8qf&-o$hZwdUHGT; zk5{3o?F8zSkm2u9DJ(WjsqYZO*41*$6bil?(^g8XvO!^l_4S%NT*ZUw^ICe(`Fz!i zq8|lc=mo`o>$SC7f)EXnZvdsdK7oJ<1HFo^BOgH|QFTXv9<^lQEJ&nml2?}TQ?;l` zBeVG*9AKAZs)n~W-z z`Rjq-fC*)j%9m89lYH4FnQS)fI_;JbZl$MeVcqCmV0dl11$9LrjvC-Iha%~}OB+?5 z{9UMo0u-oZ0%>-Q2|RnDDB87hH#|Rc2rr(!$Bn3WXaY~ERYea6cmt(}h%Cg3h!X%p z=*uu6P<4z3ThP<$v|pz}9VNqvLlxRhD5YkbSiVip)4+pkHQ3Bpd=9|;&5K9PVn?7V zGREYmz!Xh>Ss#q%Cl}=2(Z5Ai_UT6&)%pi~YoK4FXoP3Wp)^o4r~mNUtLAKVPq$St zG0kv8gxgFDN&`N7v{A(1N~u3ICw(2N-IAhjlA=Yv=>_J7b!k+ThwFHj3;Cfn-v{$7 zQfN&aZ`w^L!;?K<*JCdiIu4;AZ3^9QvV}`)*b&#y7*m=)QGSoA7{RgVTe)e!v z*d{neC@dyYNldKZJhudEVzMHHh%u{HAR{3U?Avvw?nw6iwXe_b$k{%pqz;$=$|Wi^j~E0c8dB7rs&CAG{#y z%x^iv-|IhCmAd0FQ|cQ&Ev44`>WZq-twAeRHFrN+vBy7WCjIq_#&nm);hF{+l)(ji zkjq^f7HF8Lc&c^-jUu)4lQpF;1%R#@OpN%7Nm3a;Vi*ViVK};!lcn&&?p**sDA{}o z8o9M`pm>1jCALbxY9%gCBkG}nw~xW+Q?i##R^J7|f!JTY$;Iihxc1>aa3#3*xHMiJ zE>923aWK5%lP#+_dF{YW#JA)1*bb{SVBf+j%?Hqtr?%sFPi=)Ie zu?`D>!H(TP;NM`!XoMjS9094p8?A`QUEP(HT-ypDwvFt5$NHXKv|q5-)&gL6jK^;o zo>~s|;MED1<93_;oaA_Oq9W+H?I!vz1s&YSQe#4x6CV zKMBn?C@Q|WKL0V?&P7yASc8}TMT+)0F745ZHjmcLcPU*4N~)50Q&e63v$T z8lJ)}!=uQ-gURm|xrTjJvDi4nLPwJR^E=|qxm{l99uwbmYb z_w9lA53q*@iW9gtfz4rd$83<^3(lgHgEldFz#dX>l4c>(h!IJy#Dc<8q`}t8#*MB< zLLIGmC@;#nVm6yh0|3q|=vlnBD88QHz$zReFwLJfaAqm!F|Now@#N1)xD;K{z@AW` z`rz{oLYMabaPeSOkn@C6MY(Uo=nZy^BNzAsy4Or#e>Y5luo!v(`z}23mH5)h_rVvu zCZ!?Xq1qlzYm7`2-`S5s9K3a?|ZWRw~qu-X~f5r-p3N z7LmH8q`0MFB$5_HomfkOn^-%UfsRt0`BYA5<{gQbH2%iagtWvaC7BrX4>Ml9$?uu4 z|Ho(@--q}V8X~5f4slk05`3V?9UZI6XT`Z0shxGa5k>`7lQjVqpDwlNae!dd`#eb|vXS}~A-h2<(Ce>uaj z$>NbGqPt$+&rrYxgOPNVEF|3Pd>dgKx8S&YyfJ$Ut`m_bW#Y)*tmfWc5~lH)!A%fB zXw3sqXbff$EREbhdNVtwP{%TAe%q757zP!a%&6lf2#=91OvqFi3AtnbFY1(2B(gl? z7G^BNds8f70K4f_CKL2QB{a)D=y3=GPO4%nyhtb??fAo*qm5dMBp^)b_}x1Gn~3)& zPpjl-Xr4JLb0wjZ9x8FMJD7JAAIU41)9W9wMEE#}%n3;CVO>`oxC>DYthhnvM`*YV zux9O`rvjnWOE11*3c0vMt2+UeL;Dn0EWM@fA|YXn+}5~D;tNSM)wB3jid zl4!~w>?UlBzisr-^t26XxE*t#E7?61bQd*_?mX))>#E*WH=+Sy4>r&GOPk;+KqbxL z8!+g=c+v-63FYhpjk3YRhrMis?Y3=bXsDEyA$(fH#|nmZSoVbHjJ*V0k!HPLjD{)~ z)Nw41gh?tqX2QYd9$5{6Eq9z!ug58D9^|QPt}J>YC*}109`RHIe4-kXYqjY$Q<50gErkR>cthRn+@-~$INjhkWxZ+-F+ zEDbZVsC>Dnj<*fMWxv{f4ZCE}k;5ThkI4r-)}jjWzL1>t~OC_UfnfTEI)`FvtH)m)6gWerENP)&u=JhJez) z56W46iA!{-(nQ)(m-yEqrQ%&@kAo-_O`fwS0zS)taoQn}hi?qF)XjQe4ewJU zop(K}I0{4$Hmr4=E0j%1dIgoWuOO54LA}1*IK@Gy6m@di!sfG8yy&OBpA2HsW$74{ z04*r-37YsAE~YRoMoXUs>t=m1t*yE|FKcG^GLki&- zt#5fP;3h#6eN!wp*l~|mEBQKsq`Fz{X|W~Bn?Al?kYfi5kkz@xfX?p&nc>`ZS`y6s z!hIK-y?wiyukLjV(`TrMK8J}*w=5UNLLQN`B@j>K6zV7-sA8#mxi@sIQ9pj*Xe1rI zJh7Ios`Q-;X=EBVv>~04FeX2oM%#@tL=BsFeJdY@T~EP?cUno72cJJZ;w_wdr80i^ zeX%8?{VSxY@MAh;`x313BwNzu$$qSpEn_m-c;+Sg6&-sWVwFy#5<;Ip65S*wxoFD* zRG%c@z#dRqFhEilpT^hI$f&0G*B>$Fy?o+8qgTUjdf+j>Q* ze9!A&KIT@Wx#fnp$i}+h+;rMaYw!);mB{#NTMf-sr@T>K&Xepk)}ND0K$pg0)UViKn^{5K4G@Dg8Q0zjaL@dI9h3Q9AXQ zq9*F;9C{7MP){TxPgrxIigaS#0(=g~S6QX5c`=f%-UFuQM%Vtjoo zOCG%%B=}~;eX%#iEjq!McbLZIdz#@JaKW!IAyd!tg91nA(1@7 zVym*dI2KVvCAp8T>`6Ua#mkB`?Kw&&&1Kw`N__qGpy8^(kyn*XD}g-+Y48tea1#!P zg#{I$gz!q6f%}TD5Mm71G5jy3Fw_lSelTIYFIVp<5Yo%ZhsQB0lF?78nvklLGo(7x zpmK*+N7s=M;(WUB2S-MZ_W z+%1`PqYkI#2)2d7Xh{OaP7|=OqILGlGW{VPJrz2MYj>S88N}fO#(8y3LIgA zN%=Qt#+HK0NSPciX~rWH`X*AOXC9U!O{m06RtXMaxitlyJXKI#@_umioIPL%MvwQy)}&VIdwE!^{@9BT zjGYP?JWm|&T{VHx>-21m$>+dWjbK#eZyzBw&hjI56;q!-QtE?aE>TvbpXey=!`>A{ z%8Pism{;qIYvYPAjMkDtYvJi@Oi!isrA4_fL4=&eTZaZYMovuIY!u?{$5S64!93kxh zs1(gLDhj>>wq7v5K)-y7BY9r>Jyqa0)|qBSQh|P4L|W6r;L6TyNcZ8P1~K3CvFm?Z_Rf=6#0xS7L1M z_D7$)Oxhxvv5Y!cx6&Fiii06=KoJa~>~%1`tP9|Z>%urvb`#KS;xaebfegn}84P#| z%TIAW!KN*O%wRx>9)6@x+`gc`4V=fN+ei~f)8q4xxC7MBtg@c=f?*?--6ibSv0&E2EF5Tic8!pXVZ#Zwc;SwqqwEV$K zS+A&Yb$?}@!i5(lbF~!OLQUG_H${3JY681K_d^*35WQ8k7tO_FHIZi`r{tbd3O$4j ze8rskuHtCUw~ffyG9ge!BVHV}iVjN#nU3O6y*{eT_m(0F$qzbzfP&bPo88<@juPSK zcyaD3?(E|Gv>Py2wMr-C<~COUXhwpendNeSidR&DX8KXXP}7j?K{OSOZsqSHy^IiG zL%;$@?0PCkRB{(TA$i`tno_GejCG!%(}lpEF&)*SqBy-S+6&givWa>d-F2H%qp^oT zhaL|)ZI=imaAP7_Ce7cAm~6RKL?glcX{v^LuVXz%(G!c-F9w31)H&)M#tGjU=OSKCFE2#~u{RaR6eAm?D?7Jzh9$+P!@CRE3nPdmKh{N(-wNoS z%Gg%m_h)ox@a44JGVaUj}pC3@$8X zfR={d@kFE&PRw~H`1UNA;!b<{x|oB`Uw2}r`m3t4sXtQxRiO?XSY#zgBDq?sBTZq( z*AL+#OKJ+h{&}jZ$I#{S)LRBnIT@xf1x7{c6rj77QEpwPACbDustouDL@xo70CXzl z;_`k2m!hdYLGxE1I8}ruxcGZY|C=RE`=7|}|KslcP_2p(5u^o` zqC|_dm}sxwYOA4Gs3KDNQ2|jZB&8^AQ__pMdwsJJiAEN7s|(r%)aVijg_N|^CL$|A z&<)5!#ELhjLO_HFEcrZN=gj+k?@a@^``y33d9?Tae$S6HXU?2CbLPyMnXad?wR|pt z&yWLqoHXIPr2HD9ycJAe|I>D|{~fK>Cizk7=i2xF5;eLmk$Eh(N(nR(qoFHI7kO$$ zAT_c&v-O+;LS1?r;ws#RwCbn{A;(`bvpj^s9-DurL*2VHFX1_Sv*uxkE1Zh1IfV(G zU98A-b+1+7fLr7^?M-pmO)q|TVZRgAfP^dt2?jE|=YBV>9+@X;xJass`4Y=E$uzik zD<FBKk!s9`mL*X&GrW49;VrX47yjw|cJ5H1V$Z(_A0{Ht(+s5D zYx?GyZ#40=?;rJ;f6h~gjZd(bmQ0NJ>4A}@RIQ&cs@Sv%dNYtcZA-uR6+VB0rQ_&d z4MyosQj#aAgJzoq1Ny%=99O%CbM5_-_l;b5H2^?>vS7n4(#)7q6EMqR6aBpW8e)@0 zRj^Nz9Mr3>xYcBeeQjK&iu@8o|K@jiMLvkWLPdV~Bo(=0t|2&~q~l%}N~J1x3RdpE z!nJe-sxSafR7JPzamFJ@%A;)_%{Z)itfdXA@_mKV9CSBIVa8~s%9x%`8z=};h#7LG zNRrIl6q|QG=2||9Vmk?OepFMQ8F;?4!|1gbVy3&bD{6(lY1Q9;%P@=~9g(Ub9651b zC~8xp#rM9iq}DmOR3xTaQy65@FpdpiH+dTat}bJhRzjHotU8_2@F`d=2OrhVv3I+4 zNGl)(a=}i@0hL5FAN0fmlBOz%SKJJ?X4s=(Wa$KSCEA zkUB9BYbP_u5eScwCIbUa4&OyhWBXCQZmu|H1Y}lybieT59aVl~~(z z>75+*mRkFI&VD!{J!IGQ=QVC~3QcoIW3kQuh~noZ7^I}l_fIBTz--9GR<-rJ?2NKp z&)DCnW7o6%;*C+@F;V4E{L9LOR#`6^^?))rAf=Qw4wGAb z_`su8s4(1Ho#2k0qfjAxkm09aT)1VOY3WhA6jJ?czR)tx;gQSEw9EmRIMr!mOdCS0 zlfu9zRur6qkc7s^hL?i{;+!+{?J75ukIKkw{m(Ayb6oRLDBGINVjIsYQmC)40R&43 zR;O;igkqe`n&^20=EEIY+jMV02nuW#(ypw_N5&Q&?I*t31c%kr1ft0mCW8rEbi31~ zaY@X$0e;}!9&uS2Y#qo?BODH3XOBIqvftjjq#l|;W-VJvgTCly6|$M--`B!Z8R;gp zaMnp>1dnQeQlLO#fp!YF&sA%%v~KPHSqij(sP@{B>=+yu7`GM>;~a)b!x#tzkse61 zIHEcU7vf!I?b}!Q*qAD9Jh%Gb@Y2M!qDig%FrZaSHb3WsR`ggrIXDBwhUR53oWDO< znZPUjbG@~W)8B3K^rejB zp+~BbBicP6ueHk)x=Ui9~pUK z3`~|DDkg|w{f}DrT*G2gzWGQFzUgDq4P@{9He{Fp%hxq%PJYF9D)TBMz>l6UsUy0J zI^imZ=oFJC7FSdIZmKSqb#3$e-bATU?Wft)e-|aB3h#J-Vo&glnYl^EA`I)VGj_)P z^<#AGB-JZ&?(iSrFLpuD$h;KEXpA~>1U*4tq|ho92*@O6uXd@)M^`Y-bxCygQtEfz{eu-o#@-z0y_?OUE=%W1}lO zaYR(LA9V_BQv(k)mc+F5SenMO;v`6cp2v$s?z3g+0K*3?Q41KV#kop}Na-oQ1 zSW6%_Gz?!!hi+?=o>^)fxbdh&Esvd-!sDkbvttKqPVp!ji-=}?=&wT0M09X6W=ka-CFX0as@kxT+S%*6GwBZ&dcuw!<&wpNz z3+C(4kj9foF33a`ANw83;rYBQ(aYy}`Gj7U@v=xSpNK;~%*)9Nna|57^>Q39r|IQr zUM|whVZ5x;%Nu!V(MvTiSLj8T$$o>E#M7Zh(+fXKYlvBXfn__|{c$b#=%9M{{fKIp zlZRo!N8kVYrnq9p#}~g9c7otht*}m_w^%gOHu&pET5E_z1$v2+=I-a>_^9@n()3r7 zKAu#x?5Zguq-JJL+gEt^`3%82&Py{Pn^&Q?BzZ75Pf_tb{a~Hz+HSbFciJQB=79&= zMtek?cBK~Gl_T{D}Hyv#0@S)Y3*-{lbf5LARs!;<=j`rOlK zB@3v2G~;j~@+}bY_Sm=vaCR)1ol~2Sj0AZ*HrQo~7Z^^lbws%pPD;073yE((!cZCl zgM7Oc@A<<7e#v(f?dQ=(espmFpd4zW)d1M7TR-sjq+3sDSq_jAYlKTq9m^MFhG}6} zhh3-vU(M)1Q-xiAq({tsXW(Bs!nxo<3PiQvERC%vR-9(%29vdilXisOH#&+8GXWKq z*u*4Pj6dvaK!wd8IoL`*^Fam-VWzrTZmcK=*dY> z;#zf)>D7*9;VIE8@b%TuEQdB^7Yf1Jra}Di+g^isLLc8{LA5L(SUBH&Clk?PKD#T>m1vcn-r`cF4ZlwP}5# zfXLgfbXDcBhn2~8{B6G28KnMKF@qdlplZvjkl&kJ)f^x>RYG^6>S;bbgl zoOc`t+^BuIu}0QWGh_SRt>!6WBdidNYL6q6Q28Y>u1ROCLe=zTd&821j=H??FW-=z z;cz1J_RC(2#@DrsO>dgnmz_zdM!b>N`@2ReZN^r(1|@6+0vakF&DcgKa^}2~rTyV^ z=@5l0e;jXn^i8#_sLdf0T}4ZHbK}>1woRaNVZ*C!cBdMbg>LybDHu81K-`zrM*V*B z??`vDl-tuF7*!k2k#LXN1u?_1<$B~TL*SRyqH?x|@RlC^Vt9GCvM^IqS`^*Z!~EMo z=$kVen7S(Q6uGoIZt~&?dpz^)p%}|?{I+$XuD@H_b@h&{hIT4jr&3k#e0!UUpdm_u3v)lW zea`Bn>D`LG>8+w#OuWD+n+<1g*K6LU1aa#e2>>zKX|ByJQ;BR&P&IYMi|?V0YWEGv zR-7fyw=E|F#0oq{NgcE20Aw+*#jnN<$j+TvR(10N%$p{R3%jkPiK{-HLXL zpGekMcQEWEzO59pQ0m7+lMJcNhsHx{{ZhZyV;0hP5b29KFj-6Mb(?u#;aHL*<7`C* zD>{oG-r(<9Lm8+i_$VwUF>50ErhbwE2;bQYs6R_FT861xt&mQXn}xaU3v<6FEuq-F zquPzgK1DwF8{vx}eLz0uC9s5Hu*|L0bd70ICOW6URUGxFy9TO*3+D>|qASq?_8N!l zG~7Tw+yhFURMM^t5(Soni21$@d4aWasGz!fMx%{_Eh8Bccb^wO$U@^-jS*q!4I&cRdhh^ zS@%FUU_s0xU=(-V-osfQTO%-f|l(kz&bau!Dcp@grF5_O#olM|_5F9i2v}CT* z0HgH7=)Ev{HpVJB>|9JsZyg^#oA!jxi!VoCQqKqC%CrA$s|JpjQ7Yjc&9!Mk} zGwu@m_Nr{B#oKHsUdEnZmA%G8DNPEoFfb+XurEtUHmxH_Yr6Os0?XHrhe~Y!?1+B5 z0DyMK!G<=A*-~dK$v6gD1)iPi|E4X6tkOv!An4WmjvlgKNUi*^?(wE0s3e1`v~2hO zNswkCdyLI$ikrd#1CJyc#Cfnp1r?QqcG^abb?3u%{(`$O_VpFW-4-PmDZYI2qbY-T6PrNA>n3-gzxXC1J z*G7A^`^4@4>`LoQhqtJu^6er|-a@o+ zWMj`f`2bHAabi_=y@3&cququ8^IFq5Y{8&AmbTJ!IQ35sZl2vZ_5p@j(?(9vc8-eHfS6L`>nk%E1NOUTC3Ir6MOWruH1kj9C}7J@D~3z3yXh(i|U zSH~a6r$-xW`9O}EEap}M4j^wlY+}$O>I_M$c_%a-n~YD1yl&#=MZ2xb_h60&LG{Q% zHuXCqaU@DLz9~)!L`Dvin^>{z06;khRc+V@&QqdTeMr(>fmck3amlZtXjD4SVYZ#z zUXQfPZbnV@$SqZn-L^15#(1|(m@$6+Sjt_2OsUH1nCN~`C$b` zkk0f2?uTEqF=e)61!+{bt>Eqy6I%F0n|-q#l}0nP9uP5d^lgn+)jWnIPWRCZY!>t8 zgo8)7A6U{8>ZJCTs_nZCn=rHKAqyB?`dsk-{(&OmZNVV^6?!Cy)1Yjs!Wbo$M{j^$y%(>WZntuB+X~mcMP<0p zSCkQhx6%O^mo=xR0i?4$axXedos}I-;GaIgFl&YcZCnV`DUcA%6`Hr0IMBhT*Nb2w zu5e1VRNm{!BK_o`_>$8f(_~IEO@=bDj+;Xrk|Z=2CtBU#mr*IvyMN0uj!t2S>;$^r zXPwGAHbMO@Ywk?hjhg*5>HD{PllFo+oT?353O*tP|CG{%$sRn#UHielVm7ZY#|?@k0)Zk5Rq=yb&S{@ z4Tx3i&+h_GOS(fcumc&_deOhr?KZ+2Dm?5~J88}&8s?v?;ub{1Y;bF1w**G6Ynf&J zKi4o(DuJ&$_StD=Oci;P(q5uoniVopFJ+9>@%5Gybz{H~y!vOOJh|hE-=BgGe2My%^E98_EWy-|> zrAMmD5A;bcFtpORno3DRocT5@#4#lE(_B9E{r>C|~he12F$odrWVzz_%>4uhT&c z!IW=8S+2-0ulsYVg{L6zg_)T+YSM;`(7QD>txT=jihE>?kgK#my(3zb9xM2=J5YmohW&JP9$m0T14MTJM_44GZA{scs2`|$YbqBfe5QlJoD^agu7nvnTb?8UsKY>4ymz5Z0^ zd}K>o*(lMezMX5|#A52KSbWmL4l@ybPky{Ti8z?V}&&>Mh5JBcUFPJ1JuEyg` zL`J^Yk@HoiC|m7uDLq$oU|2q^gEu^G{l+wo;EAMu7P*8a| zq#XK-!~C(Q)JO-uvZCMK?8BdPP3D@(;zuy)-H6*)> zN0Lc?Se!Y6R2uIRM{4XC?^?#&c$Ww<-leLJcd6bCUG}SLj(4dd<6WwidL9x<=(3#C z!6TF7zVRJ}8WFu^`^ucPL#!5st`&9xyql^O3siouYg(Nh>%LzfIG zEC{+S@e~DRp!0zru6FK-5n#;m6r-NPx^75eLBQDGQ;d0vI`!O;!h%S#YY)TJSTc0+ zkivpUaSti-q0Tz$vUu7-O@&Z9XGm)_^`EUj!=-5~x=b%J*~N^n>`+FLnN@bt9M)WE zk7zXy#_;9#h}2G*e0n8(xQy3QQP+QL@9Zr;U(PV;)vn<6SDINNU^4A&1oTEO%YB zn&;a^Y5HrZuN4=mxRVxYpw|4E(K?#H4J(Ul7dIYgAo|nvC?w zPgqHNHZ!_L1IYlZ`F>k2ShwJ)mj|q+orw!_(e*q^`DyIfUgkpt(y$uJl$xRJX0-(c0(zACAvlnOO>sbDdc zxGs2anq}?KRb!9#nLJASOF>i8tU?)Vsb;p$UM(bFH}ic<3X?R(Q*0^MHD2R&IeCeEH?^VfsswnT`GH-iLaBlx3H4KLhugXR1D{erd%= zGyWU1Ujl~ioGN?+Fe8`72#k+^U;>PXutS!^xNA2Uiv^>$tmqqe%XZ~%*Zg@tEG!Y9MA499@#N;=Cl+`ITPo4*!Rnwdo+udZmodOfkrbY~ z3$1w?41D`C9-$RkYI4HUihaE_29Vm7424OJ$=Kzk+816g#!xo2bS)?T6pe)&dEr@m z2VCupz2R{Hx!a4E*;n}Zi!a+MZJCAO-&FI&LIB$iINPe|45k5lw9mCiG>1ni_af~# z?{rD=lN)16(Xx+83WR#QfCk?O1lM5h zT5djo+7#u5uRJhL=Pg5o2x1o<^KQ7)`X3Q{p=l`!=Pe%C&fahBnxy#`Q!*{b_PFT7lon>EPIF$}tl<@h0( z>#wZX4Xc%Fi_Ou*uJ?l}0obPsw_@RnDqi4$Rp1K}Dbb82_NaYEfw2O(N4xwIQCZGvaVsE9Q|0)QT(oQ}-(r~8o$zaYEY`olog%s`dx641O)vhtoSZ%!Us zu*+pCsn|-ZX|&ovHYju^&E3p^&H6(_4d1i)hPhdT(%$-RF41jXMrnL85L9cV%%ZjyJ@voYYm$m8xzu!hZ>uKu_hkNRmPx+;4zt!1Qx8zefD^9KK!7Asddll$tm zC}&nl*oVt7Z!&c`Gn-D>+~|$`-G8N#_k=EmibPLLw?Fy?NAiG-iyiw6D2HTxaDyF=RUh!3OwWjzM6>e+FX2X zExu}*DkSKLU)>t8c^2VYEDrL0`B}Ov`YLJY=w@UJ{^>S=xfgo0-&Fdhq0e|H0$aGQ z(-OC~s}6*z4r*k_Hwas1qu2nV8ILlWZb^BgIRku3#zm91?aLg1(Fyfmf*PTuIprnDmQURr+lhQy#QMn`5`^lS#UnRn|b%B zuvF8hH{amptx|cywvh4i4uh1-y*wj`b(r6E#!yxXio1@NcY$yJf-dlVS;<&@Q-0d@ zk3Y~;EtRp54`z~AtZ_-CCs(9jJIJU;avMUuS`11_%g+KKFJXdA0>wlo&H0S5^oHD&uB%MexY)b)NV!mCW@-;3w1}@L2Nhhc2HY$=u3_W(wz~OX{ z+qrSY44s~#TaU=IN40lh#238|c#lgf*6a}JaqRa)?6dDSsh%drphUGF`GMzq*kg`P zsHD?TycMF_OFg?Y!5dDam72@IUl_o*JCHXO!G9*ieAQxf!FAZP=RSVwbXNboIrb$K zE^n8^ON;OLG^4gjrxv63l$IWm_sDfI>XVYY<2r*h%Vw?|GA_MXq=hG zcFsN-S}X9RjY(gzl-`Mgcng+d=XfmrfA-m0nRfr;lkpHG3xgCG#`e|{myJ@<>9z&a zv22KygGR*>SacZ6dKv8d_qIl;c#{VW5Hwgx(D3&a?&k?LqrcCkF7)p;8!>q@3inH4 z%xx=t(>SH+GE(+u^75F`2~sTRvZh{4^+ijiiyd{`l8)?=@6yCnA8}ZeBJZ!$yGcoD zOE&=v4A!&)kHzm$@For+DUSA?jP|6Zaz5IBAJZ}w>|nI-V6;E3INFzA$lVEjSvD69 zi%u}heVnqck?RT_#d=mQ5}%cl*G!$-@kyQ(t!tUwh%@Fa;vt&<#F2BQ?B}v6kkY;_ z9^|!sTk&f?YnhWF$O?D;5irK<6Ta%yW`}>=ShduZFp-7Xhq^#jj zsHR~(SVuTs@l6L(M={MNjVo`( z$nlGTL4hq>*;!@t^)2-#VzM}Q2?bPZ3Cd-9gsY-*=8G^q90~_`jv@nrzPW-Ml zxlcGa_Xj|!#*2VlLVpE1?FYPV^iVyIv5i$0c!ITyUHxg_VGF@AO>fV%{7@mNzpsq# zNNpx+x4MKi6kKprlyhbE0;`>cwDjl!Z(gSOuwIYus2yIN7DQ{g6G2HpU*XX|!LjkZ zS{~2ftl0v(wv7H9?H^5F&0xRz@ES-P)gJsEJ?5ve%@mf8*nGrmX1m;mtSoo?h>2Ba z94bv8e)-`pD{!Wu=O;^N`)_=%Vtid=DLue9WV;u>^^lex0ZM7@RlSC`O$~nn%VPrC zJWr@iL3laYe(OkE{ieh_ye&RyoJtx;A!-~wcNkMS44avUo0a0d0b(D{r4$B@=g?%! zOL4ZT%Z`uR>^2x&l`>9WJ8`nxB)=`AV~kH#_Cq^_~P_I&)4UQBpENYSxQ#zI}uaWnK z+V}sHS7+f-u2@J3puQpYkPv&c#Wo!`GO;;1|8*Ad?EF_1X??co;bLR!B<^CpI0%hI zx>l#pCJo}U5hRDDa2viBY>JS$jxFZKk(x}4WtzfMDa2A%nd2?^B8H{VPTuCB=|j6- z(SceWG>aaC*~oC=8xHcpfK*LD2`^Z!i~-_P5M08C4gd0QZnx-=%i7Yl*^Qz$n;1v5 zlVqkS4$EBdhnL4UH`j>3wKeUr7XQp&OpE^l2`yJ%1CqbhRr>PfCP6D&AHt_uA5NDH z$+x>KT|!nn+98uq^n72_Nue~je)pf)9`Z(1Ms8^@$r*t2pNO>=CN?#;rW3E_XrlnO zyx>0?ReW!ntcZ4D0n<+Fmg_jt9vQcnQjXv}p5|~8+@tqhwY{6_hnc${D-t#A!DLxi zvQN$J$S;0r^P$<1lXL+x*OiS`Z2jAzxqCEcn^G3H^@Y8Y%aNyy7Pm>RmWow6@Jp}i zOIu~xbh%gDWo#!v zUtt>D#obCRYi{P++4Y_bZe66{yYEu^LLKk3@6HY8(w)F~r^4_e=k>gSFCuSrEfd=7 zet@j_<4=Kq+n!UZZtI=04Zm(=o1UFh26E|JxbybBf##FAoH4!eyx!{lQz^w=`-R?l zdUh~MA)zn@vC{!PQ!62fH`~AbUIS$8D=D9FYk4Wx6IpUoAZ!dMa2S=C9bSp%FUL*uTFmD_N+j#dK-AHC3B^F9eF%Um@-L_pCk&t}&& z7cO}N)M`}y+1xd2|CLo4@9hg0V}4AmX4Ui+l97+hM)3%I@Z+3-ZxGA%xGhnHXk_cp)q!=-A) zJAl~IqhHQd^I@jA*jtXK>w+ykb1d;Jgtzd>F9Q`lW#pjzo8>T*3XQ2IiTY5ybR1-V5Y@l|V)nDO5k^cAH zWl(Mul;<&F1=O^SByJTmFtg!n5-8UJW%wtSO=Lts7Gl>Fz5$@>}aypN)wN^ojs|&ob!MlSBX0p|1vg ztwFbw=$*06bmVk5X*usjYWDyH3#4q!P|RGA6n(XPu6OZvSaa%fFoDCo59h68+ff}m z3XikyI()eS^d5+ijXaZquqKM9AQ%-X=2)N`6G4tu;DaVo-V{2^MYKBLHjoYH;adh5 zQCDNtSM&!Vh39P#1(sCwR@OL&{{%&2LVu}P(WWzb_bhm2MztRc0MC8Y)S}r*4T8q# z60E2j4*w3=bXoOK73plK(`ba&XKsap7c(oV6ItV`8ugzXGXm(g217NP@!)lsu;+xF zhbbr9#9pmI0&N3kLB#GT{P<2QYp#j}haWwx0XRL#D7I(3No(38gq0s%!N82g+IJ(C z3S;assAU7xkSc1mr}rIp>-r^+A>4EmI^*opdtDY^bvDv>Y>M2b(%t2hSkfh=q#l%y zLfv5$8vZv`-0V~&ik31KnMLpOyF{j{>=lzouiWX;=UX(JSYU#E(PrLElb}4%ad7tw zVe4%M$afyk$Po4!51UJvoO>P^5I+H87&@U>_SXijRQgxb?z(t+$!8uk}d86Rmyg`wL{Z@kxFZW zKu5>4tXWu!?*W179;Ahf?Iy(PVDEQd?I;{@upy_0qU73&5PbYK;u)6ZY}=e%w+4xQ zMuQA6|Le{0q}h0hC^MjLekh)T$bc$AF73X=fQrxQO8Ak%{#<)R%dJD0i|R6etqW6L zU}t#EcxVH!>O7?^=`#f>#_Y955z<5IxgRfc{3hjR6Jc9dDx4h!Y#~!NSF+Nb1NQ z$A!7xg}M6||3tfX0-yWe(!;;Z@CqTHi}xtEg<*B_*oSV(MD zwPC08T@AWd{uL*_JO$XDK9Sx>aO3W25gxYC2usbPFWE5X*nCY}7lMr75 zbz%<3SSZ@1BrJW2KT6Vk)Y3G)ArJsv7A8I$sx&~3k<-W^dQ+={83F>!y5esmB(ftLSZJ-@@@M-&4ecrC!h~bU(QC8^E8|!s`ldsHeV5Yl; zF;pz%L;PLu1SOfGML{*==3@>cI;y=p8|yypJ8g2!0J3;ve(ANq_XgD(Z#@7V(A`Ye zTGm`^N9bCEG%mN6iDn$5>2Y&L5tvuc|$990#u<>hLJwj&+77Kg%Ea*GGQFuHH z(m_Y@<-&IVZ6;?M*U*fuxpLM$=q#%A?wsES$*WuL0^o<29|Rrf~1b zXT(~ZWScApe@VN0HQ|DeCrQXMSfAUTa9>~HClAt&QefpJBeuiM`)NVc0(D@URa0JO#0 zy3pu&Q(?SmXuN4~ylEh8l|NjQXKm=4;QsM1+&h{$ENm3xlw2-avW0%q3$%gS8gy+sc)PQLlB!tmil2%2slw9Ak=K9pSz?ySOrrqluu!mTqLvxpR zO8JC4{UixKb%cgKrz&<@%+@c7t<8^$NH5`an~c#0U=>O69ZFztRkv0HqqSAPv|YM$ zc&8B0Yea%^%=JNhggIFbNbA1~V?KMN%U-MoO4&)uUcUzfmudkSB1Ep(z0A9&@?GGY z(H4P~U))S5#&AZOsCIqmpjXONB6)Uvy44O>Fv-@=qJ=URk#!K^IJg8#U4W8Fpjgf9 zHhKfJ$N&{94sKJZo7m-OJ@GbEEp#J{rb30C-#22pmQj@rM~K3t>F%K475(x+%Ng^Ms>ptBIFrOEu02^k+PVOH3tU zu%M9ck+)$1?Z!fFN|`V)5+9##tNI$gnX!jcleC}XVr}|P%6Aq|&VQrB(NGAT3C>@z z>R_sB10+Y)=jSe1DODJ`Us8o;Y~ir0stq?;yF*2~`r0duR%&tU`p=mJJ-rZSmD>M8 zxcNf==0GL=P-P}}vg#r|)iiNwDw^;T0>Jy|k7nzZ%ao>s44edamj%}l3{!!>-=|IS zTCY|Xf#y?=uMKm9HduD7SsfibKL3uiR*UYe)k1ta$P8ekDv0M-%bEwzuF7uk>Z-Bk zc!Ij>(5>F~9m_WcVa8I8pCxuIlV2_Dc*?m^eRn0f47>h%bD|3ZY3;qH;!24nvDFk@ zOtbnRI<{SPqlj4~P-W`usfAw1H7))a*_XFLaPBZHoBH#MAEfr92*<%N?On@B3yG=D zY9F`$M6pG$+&mLF$#}TrK6OEjO*RzLBc!1O@fx`MdKauUZ6H#nbfCvt`R#7i7A?L>{z#skpp%gC> z$07v3Rt3U`2oE7*WkP0KkJzE%ygSfYHF)s!VCvY<4$N)juWcaWv<+%LdP2>qEab(gqYjzslQjCMdV@JBP=^N+NpPMGy!`XFj9!+$19 zcDSx*`A)sfLjsmNyw`UT=WkyH)tK;R5`-Vr)QQ#k((NS^YM2o7aKe_+AL*HVn zgyt<~pvX5@N=fgq5y*^(Wf7ZSJ~Wjwk3DnejlFrV{3FP^OGdT5$!I6R#|T9yck4!S zs7D=mvbRuFYr@P|Vu_ z5Hw%1LibN#oJfcoid{o)as)+OX>)b_{(MHd*uU;H|##Eh*Y#p7jx zu_JQ$fG|} z3R1q!>17{D-4z239UJ<<{EvWnp~fm_x&b9hH%c+14RhV#q!HE5Dy`%U^}rJ;OQ3X! zR@BtycVV0j4iN0kU#2AHD*+vdRFFy?6Y1BQjs(M*O-&86sPPU9L9TH6F+9uK@eg=fCumPs ze%e0HJGC_LTX)ObU7Gj)7fMM5=5dwhW{&o=Y<$H65hR`@UJqNpXu5>22ELO0sf+ro zgErGaoBd=pUfK9B)3_3rlgQ!u3Q~R{j`!%OPot_W-{(qb_7F~dpyOCs|D<>Psx-xIN)h+{wUj9-V6JDVJu-~@cXje+ zCY^Hby1EqL3M=yO$#y|$wqrb-aZyyeqBQCtk1}41YPWkAC|u_{q+1wd3)B1;H1(JS z$3sdXZW~h_V;&HrH^Rcp4>_*;#nHPdC@|6-eQSE!a>U_M%{|vKDr4VO1#6X7c zdQ{>5GUBv_&^yXP*M`s=%0j;wLjSQW^s^!K(z4Ko5PDWw=tn~6VukkE5Viv{fl24dYf(_jpma|<2c8)E~%4nhTW>NTWxXK$4?tjUH?$SC;EqRK}V*-)Q`Re z+bTtPpesCY`d4Wt*E#&GqmCU5rdFof=nZ94gu|#*qBjm8e9;>-2%B8j0trYQLU~M7 z3=jc|jHhYY<@V(d?DzU&BF!V!bR@`y#QmV!9AB(wVeVcqd@FK0pH+DrZPB>D?Zuf* z*zk4yklz6Ms?ZTBP81NeHn_Q@M{C-N>l|KZ$k5-_RQ{3jN!?LjrC!<3sGJ`C zGLe2CC4`UF+Tt2#&dg8MaBcbrUmN=vzi7rMvO(9^$hF}bmSQTsL&QLhxBWw090zBj zd z1EMNL=wDu?hnPoe%etcSJpzo1pkl~oh2|Xv&mA8*#!*OrQIf16C+f@^ssV4*C^z#o z9%e|lP1-B^QtwKQECH%TdrsdwC{wqi7;pZ@Bsb&g%Vo}BZU=Q8)%^vYS)744k7%n` zl$|Ri=rhLR?>^J4GvaWouk%DAK%54~HN#!%XSnh@z)Cga3o3(~N(d4_+@X2nB~BMC z2s_;B@R>Vb9$%2p&J%#VwF(-;xtXYERGZ18_8~<@{QkxHkZ8L?+>G*LD)g!+ z%`Ce?^Y475+9b%=&4d)~^fEU{{t_Ju3ePG@LjHfh$U^6Ms6W~*jrQgu8w4zp6d z=Gr!@Mr8!bOg9mkQ_m`)5nn0KZB{>weaW{a^~j9mQc{Yen!$J#!^+oX;<8(|)dgei zUD{JWi|G{bsl))ZjMGOm{;9b{C|=mE*}JGrx=og@d^EcHj->y@ZgV!}U8-Tr$4S%c z?7egkWUBN|V^3Oo88X|_HBu&4wU;QTberUy8pxRI8GKAc?Hb@Qp;wxOD-aH`qG(j< z*k)kK&A|M&cPgY^IblSLmz4^z2|u4Bim0{#t@4jC0L5wP$3NFy%Yb7lBlWWQ6un2oQo)s?Ics56{f-y z(ZIg3oN?O@hnpJVnxr5$c8jAQ2u!MxA~{TAucJzuf+1hmBk=#8Fq z(31`s9Ov)A3(3vy;tVZFoCiu<_-~!|w1cc*5%iUKxqhVx4^97TpA8x5a9Q@8Yp zTjn*L;Vn!ELB?on56!phr8st3LEb|@|MpTy&M&k|&T{121vAspdbKg!@bd;Vu;{mi ze7@p0zp6$Ex=uMgt>(7X8tX1$1#zUA?Z;5&C2ArH>j!k`vVH5YjHl6Wrg zA57{ggZ0wdzkY$dVEm77(3AB7Eg+lk;Gn6%TVmhA2lDi$yR1P;MUFAmv9ECUOfvcv zXo7d$IS%hH=ZO*=bCKhiH+diUo`b>UaHB(Vs;8Dg(_=E32}?gg;hJ6dc1kfcxB^${O;4Z7r)ac1I~hAHSIY@ zdx{cVTT)kzHK}E&k|B}KB2~3*qf?#N&JKHBY*dqsU`V&-n^(;|7p48R(xXOL`u#{B zF9XF}z5)S1zQS5AEGB6go7di1VPPj>!oD|OSf8ZU%IU{ z8VvRX9!WOQWd)kaTpgbs$)}d`u1C3F^f179}j?< z(nUar7@(&2#PtTV-GNpGpuZ)t1ARvT$}aXNX#v$3RwokY=QgS6dXXv$@i3c6+E2uWdSkBnsaXH>Ku_bR&;{k&1Vf zJ+d$w~-n(m!F94e$64S?IPAxmC7Jpd}PsxzFSic1g-uY z8((BiMmPK+Iv?!cAK2b-kW;ohjkP&GY_>6OYh@8xK9`M`U=Ud;0Q`-78tqCS;6Zw< z1<+3l+#Cxy8uEC2%j0{LMpsUn?bu)Do-vEKAj;ZpkiB*neJe0r)rJ|UBt@oMhg65r zFr@n(B%3&@O*#t*bW)Rn%xn}Z5L-N8$hoqz5W*}sX(UUpTk|_t84wLSyZz z#0BmdOw_P-*a9C%9*~)$^GI|f+nqP7Rf-KDSZcb2;8=N$*UEjKZ}>N|t>3OeAfBKx zUKZB=kUp4xDW85R8I9_s6oo5Or4vn>_HAw-dJtOfGtioT zk}lA{<`UQ>-QSviij&qLUuxvs%=$I>A8>sE@(%i&=r{zlR&W#Bj`UM&t8Pp0*X z@sj{VtXR`M^rrFg!qdoY(J$TW8vuGafwNMH!Zmo7^2emKjCl^;Guc@^^48q}wtBMO za1de}Nz0Va8aAB=I+wbg_(=E_q|6xgPK}&QzJm8U`i77h(~UwB8FTp&G=9+)%T*pqb(M$6GOFMB{ej!-dw1sMwm`K2hXh$e9HC-5 z7@@*0U6c-bKg%@ivwlQ-u^(wk4{`(T;0fv8%N`&sbJl?BnFqf376$zRV@V8d!7G8= zF=>R_xL>D}8%^FZlgbxMyTuA9r_aAaPj1+C`asWe`hd>l^!bMy68fy)wNf%V*8`)n zE_pq_SSvd0@qg#ehBeM0+VS>&ddf^u{eNU%!ZeD80jU?Gf=ErclH0 z)bu*#!yTEZuf~HGmkD^Wg+z;4y}}VGr^6@goz{Hndv;)z`B#*hzdiz`5&=2~0a_>? zt5_&bJ9rJ#jx~e%#XD)jLhz5(0sja#ihGk5X7?C5OTwcd4x0C@EzUeO(m)7YPxEMM zA_)-`Sv46skMTfUhy3vFv9;`HOc!n!E3+c9`V?#+`{*5@(_zcDc-HdTyI&@Z0htIz z1}J}dh<+WW1|uJ(u-4>wi!chQzocwVS{h|4i=rw8DPi%K1+FFCDq+&BYx#@5tB zJ@$!Mj{gK@4<3@IpI5v(c|+bI&Q0$TSYNF03p%3tX9LS zS27*2wyB1T)HVXTy0GMNm@2qXhAaOx9e~txEruykZYjh?!6fW(4}-gH*F&emstJoP zsbRiJ$jiS|h~HSRi4?b@5V9!u#G>3&i*mnPlpEm+n1x(phOJ%~*Z&gm{eJbCUy3%~ z)XKeQ<4qmoO>L@5#%=J%JT2Sn&?hImyJDm9mbP+^T2Ii$71mhsRfheGR3JM$LT@n_ zmODA@Dfz{$N^SVm5%YO5;5D(Q`h{q((bKPog=GDrKy zpfh`O^Gh?(dk#%FH!Npye%{ghlUL*>>0Wvx%tH{#Z-6@^dVa07U|!}Zt*tCC{t&CdtKb6bgBo$Qn!NDng(Fn-S@ZzJ>+BT5KmZ^ zlzoNc2~o#eWaEq!EJ|VznQtc3uib`Z-%5XpM#{jPqq@Pzl}1D2)vngW_d*krQa1EG z!(wMmtv7{dXLuT|3GWTx{oy$fo`d$ZQxhd8#Vo#Oavz zy@{I^eLtS4v!r2B?w-P2MqH5(A~U*_pJP*bEs)qMSfnb|T0WUrE2ZM3dj%tb`XB8T ze4mD|N%jg}{7*5TflSRr(M>gm=mBGx14eYcv&}HZu*HmCEUjaV$$izWbnkS*XXfVs zP2EQOb;dk%JPFBZ_BE8zL0^9lq&GVxn?{T!N>_D)U@(LSU7;tFTpC_sOm!vKS<23nXoUTC4E zgE=-_*;TyS=Q)_{^Ynu=WgbZnCF8`@YhGsR^Q?NS83%N)(NUxrv<5F^qLq6pJ=UY# zHrJ$9e%qL&YQxqz4_7BuZMcCiQWmOitHbChi{t0v0llTi63Ax?mgLkwfjuUTmNn1% z?JOt*)~Pz49nCbi`6d)%A9o%gdNfyI&i0kB}SfT#td?LoA&`z z6Mi_i$tnrb(TvJcnSMPUO zLLyDd*@PXFJJO>}j!h8vrSGL#Qp2BO_K{ED`<<hpcQy^-X?r5%n^f{@}B;b$oMC16WT<4{)RjyMyfjG@uwW z3(8iYpp~BWG;Jv;`x}4@N&!>_09Jgq_tHu>ZVoSSj5Sx+gvyrEkyVc4Yd}A!6#7rT z<>+znN-3;)hpw6hMask0UUJaHu-rCGXYYa}@Gz^spR5=XGh_e6f4E{O)sns!)55(c zq;IMEI_%CaoY$t}^sm@T$&80SUP8rb37T4JUV1N$gk|ifuMI73lLJj>3b#q!*&Zql z^~!hNevp`i$7)K1R&Ft3bkszb%cJ6QseG%XNDL8Mw;f1&zXa^nKH?Z2##ApiLr{llYx& zupDw~U5C1Gnez47tCKpe-_;9DY$eMmJ(DZl@|BAg5Qck89gm4!tIsr4vZDK#W~A2^ zI}oMfl2yTbJvvC82L+{K5OpQL=TucJs`!O;mnj3|h^mTj+GNro;8-73Tv76k8(77q zCEthgeL=~072jtRzuWLL3CkT<$(Rs!(nPfzmEyi5O(M4Qo5w zkU9Zpk(w56jw7!jvasY(Klkr5XHGcx?_&f^e(oQhFlI83%MHeN+rOT-rsPHf?kF}- z-ciY^oQ{N;MMZpgD0~yy&zz*CN9~@H3y5Brd}Qq5m2{z9Z3d@`BW{C?$6G`r*DqDn zmVC1#KIG^tT=xxzl1Y#Gd4QPEb)t%oe@@FiT;JyBExKx6Xl~Q4+r+qAqpL-lhFa6R zVCx~|`xw>I`&hVY%0`td?=Kzw>q>{KiL9&z5kK7E8r75bc|s$&jYmjk8;=a;o*Ep( z@U({a-TKvD#mboGJ7(7_Xi~CB`{^~e*BqaN3v!FQCp|QyqHmd4gr%dX;_#2yDAwx;hZ zoFul-!*@&XtGe}9nJN4m@I_&Bx@bC-#TQ~AuGt8vqaBU#)(6N272g8)-B+Y!=pOg6 zPWMfEwerrZX*%4Hm+Huk2}PnGWXSgweupdm$mdIAUc$^N`t}hc7`=r(eIf#@abA6MSJ2oPh;M{hXu5NphP-uX5A@Tm z4?KYdt;5bm(E%e$hVRmGOli9JTs5tmb{!vnh&4#$M{iurY+00?K^*bpw_OyCOlb>g zI8lXIEh`JwYDBu~C%P>zg20^BpRBxfQj%5sLMtiVmS1{vu3A;Te~gtqYpb?g!=4-| zyie8Fjv$dv2reoH|H$kkQ4B8ERKyem`4~iY0!MFPwl|sRGxv~w4p5OtM{iuqzu*R2 zPB*n_TWiB{lZMt>DBRHwvpI$ zu=W$C3au{5ddGyUhI}2!v!Y)P;EDu*Hjz5rT^?LggkeQC1{!{n9Gmk;k(LdvbFtNf zeX3BwFrs^;Pd<+k6Y;Ge-z4pJQ+ZN?@Cma~(o0~0E&Vhv1sp^E*vFH3}{<>P^ zRM2ueV@t0q)ocoC$la~CMfqiOLr7gN{dK)EBY$tzZTG zJ(aVxPF|dQh_%nJYZ+nw1sH!#3KXuwEFzQJ@FE{w1g1B152ONzLs>^`uvlVTY&qAp zHp~foV2OYqE7+c%@Z-COU!=A|il(YIs7~f;ZDOB<_x>D`=j&j)wYY(3LOmHS+dZKb zc@^4bvBh;%4Sf$bkJ+pbwdB(}v@nvf5`ZN+@}vq^fqk8iM=gnHF! z6{KpzeB;p&CUIAcK7L!(0c3Xz!xbg1DHuu5v}yQ$Jr(^{%a#OdVMXK+QS{&s6eb*)<0Y;jXMcQ*~5- z$nb&9BTlm&?~a9S2Qw2|>2-*%&n=E=^q=t2P`<6&&7CZNrE2(KdXDY848tjtedGg`cSSPlFMhygIRN z7K~7^6<)M@mU07qOr2-1J3dh42ba^q#TMep%g_U3-$yqc> zBu^-d#WLVlh^NAuFP53bg4rKt)XzS{@niF+y9iMk@K!@*8!u&sy=-&b2(&@9QOx!c zgmofT8OLj%zM&>HUi*9d{k8q}+3)TA231LZh}@>VK=XiknxQjYk&iiG4kU6Y zYS@#<Z(F((D6>kS+!UZBjU`x50PEAQ z0&A7SdIDH;N?@HqFg!h)YTTES4j^W9MXtJyXIZBly{x2DHqeofc})X2b}YuzCEbgU zPd5(3_wL@a2Gr13k(=lzLGwxRkdzN(ip|qUp{-4`(f76JJUW#CH&u<2YH*7tS^`qZ zltBP^y~yG13P#gGzZuh6C7Z5yPe9O03cA=3E5yN{HjZO*r|V} zkbukZzX-8cLg!~+DGCIDKH;B}0-Xv_+5(=7tA@TOyJf#SQ^y2-c$ZOnV)bM9Z<86` zjGanZTJx&QPu5@$*fM^t1FN7YO;|G*Dx4B$D}By^TDf+XB&Kc_2bW_w0qD5jG!A5j zJo?%sX1je@^rV@5BohuybEo=uwLMT4<)Zu`3$nd?A$iD!2c$7@PeVKhPoGzLWF?Ey!TQB zu$}{_=M2{pA+TgJoc_A11SiIAJYX0i($7MEb7|SKr)Ur4wCI}9aI%zG2Q1~AUo+)i zA?4GWk-jQSQ#2@@X;?|hy4M!K8q>YE7KLW)lzlCp-a%;YMfIuflhBJXrCewpRxrjM z1=-XHlOsGSG)eQ*%LhxjV2mpnG`LA(kDA23f49c}dedtVdfz}4tuIU<3Siy0$UHl? z>=#l#$T>%^o|1!etVwQs&6LcnEoE~_N_7)hP18nmLehk_kg2Gl`9>;vC%AVG5@l@U z4Z<*ASABeXXSh`HgV1Aaj)F~_T)$1Zv}tYYm~HatzUfB)%T)cCDKjHnx{$A%iLQG5 zw#$BEbG<|;)`%_9NJee8ia#@nM=4E)tZ5vr)_B%%i_phmY7cfO!hYk-JJl3+V5lZW ztVkIu)&8)Rl+5v4WBI(uQ)g;GR?rJUulNCt7UrFV4&fMN9I#U97*41hy!kAA<%ue+ z?1Z7q*mOegX0Entvl=q7#(gC8ir zw{eJVP5%)g@ke1-+V%T?!ccW<`j4*DLZ1Zr9}%OIh+&ve(#%~afnt^(JDQvv!^FE=i9zq(wxg_P9`^6*Dv?k-<^P9 zU<6bH^ycdhW&#=$L&hY#l3{T-k?~~dY-Dl^JLp5I^_EIm1IymH(pdIU$i|$F* znzE`;h=_ZZZdjhu-&#FVPv}PPv+FK=Wm2t}9HCEGu-CV6`YEpE9T*VGv@)f=O8twzEZfbTqu%fT7 zIyFUaeRT)f%s@R>fPiCwHp;R_FViZnEjkS*Dbu_j?3siSc8M>lDqEd*F)9MbH@n0O z`hA55SrLSZ8{KZ{YZEweV6oBRE%Jqx^nDCKv@@5LEaiWC$W*TcrQ4~S(yA&pI6-9N zzoEyR3c{s}9ke4;+Eg`tPQPFh1@T;p39U8Byha1t%GzN&gdm(QFqlE)4Y`&e4F4@svMQHUp5lO#RJlFFf#{m!oRx}2rZT*JZU z>AIl{R0H;V345k;hW&RvT(Z`tax)Ftl2Wz~RU1wU(!Dl5;Y)({@SuGLEFa~~6gGRl zI^sCsJ{#9hbSpp`W}aaRC`!%Jms#HgDbZ)@G{(j|zm29gNJ^cuku{mI4kqIya!oxn zVY&TbA7CO>P|k8pA;TOOan(=>t@dSAS9;L!QkRvZRkukdVXLry#%Ju}y#b!HS}RUz z6o+|HY%hLv-<1Ab!$Hcg0e`G!t?mcur{C2$-IZl8&r(~OWu|ADS(0U@vh<~~xS~WZ zM0~!2^1u)c4>gSeA?&OKpT~Xqo<`JY9yGmGE$N+-7{U$x^Rk;_=oa8N~u-s(?+#bBR=KC>>&Ri*Jctxn%=$b)?s(86E8{m6&eFx*bjgN{8GbG}yX*${2QV16$|ZTg}mK`l$ze8mx| z4_Fh2{;?0@HvKT;(!(N~p<-4MwaKuK(r8H!O+lHiLL0KM5q>>sHS?y2gZ4E14JBRk z$OqzN+xZ5U6Vf}^?gj1HwjH)=3uh|JE_hs!4B~e@saZ=*<%3oxGHcJ5CGQdMHStR~ zFSBj%P02SFO-90QwnUS;BXy&3${neDN9tWxd;bj8)%Ni|b7JgZ%-^63W;F-y1m4xm~&(8MiHH75j^?2pV zI|welSBjji#|x;I;wx=B2saXb#sQ|i{@M_ndr9{{Y=GlyN3 z@vSPWsbeO}DyCeN-2HjRw!Z8T5$l^nUZANOiMTnMkE8@!4G+j^OQ2V{uF?g-Eh{us zW_Kt@)NT(?Qa)y8|J5oG=M{SfK$USpUV&=|88_b^hXsOq4Kq&4urD2YCNQ+L>)^ur zH%AlfzGnQlb4rF=NgA!(O%ap$%3XY1Lvqnjzb(^s_41g&0)5$?1nLhh=>u;SspsFu zB&6`Cdj!sI?9maaBw`v;Og;Pv%~JAtjkQvb-@nr(Q$Qw)2JO-QpgppqJUB{B_b^4Z zXHy31gmtRId9-B9*q%+x`~n|N{}q6IkMid|d)|;2aRiLjHeF=F;e)oN<6Wh|=0P0! zT03%}l^Qu5#}d^5HWCtBQVi45Wv0;NC`?t^532rtJ(0o}GDFB4VGv|xKA7u>NqSiW zh9mVdTQcqH8N(L6yTW9DODKSpd?ld z{{pkb7k(+W&*CV4lCNyqg zpQm0Pe3(3`5-AWtTM?N#+Pz3C3bqJ!ruGA0h5=kY=FvGYT-;I=tT zcI>UWhPUIltvyCxea(mSB_)+F;VW?+ALC7c?=BubQvIWt0B3EZ;65JQn{O6$s)2OF z8!g{F%L-fCsgcb?W-0{Frmqjex(ds;S%dhB6$ROt`Icuyet{rwuFb)a*5GR>Bra!F z8Eym4UD6~A2cHFzaHJ)&Lw+x+M_nBt`W!q+kHC(1{D<%22fPQ4Hd^_ za71NXQBiS3MPwh~nKzf$|;95Tu!SS>VZJnf&FG|Dmb1-H)3mpz6`&y*q-!j$Do#O#?{UfF) zBN?KZC%p%M03+=ny@iDM=dIN{WDogvzHDM!UR*)1Dn?aRZc!Pn;r;|Y{DuVlw3n<*i8NARTeE@c6nAf+ zt9Agv)fmjC zM!ODO2qmZB7Z=xeI1Xi%PNTQH(QQ+5RBjLS8Cgeq__<>NN+Vws0dy=s#cxH(!@d(6HSWlJD@8AhscJig=89a+rwC+I&R$I$DR!;gso_!&cU7ugyQ|(w?;4=ngrzTOgX(j8jF^G) zY#?KtuNOLiBG`poi2SfBf$@BU7<@LT)sG0%Fw}XZOj?NNRE03m1xSiHe|6})7JSQU|-9cfO@K)T`sV1Wb&qra%3i{D-xs0X3JynM9 zAHv0}^a^M|BD(_qKbm*~J$M+tpPt6L)H^FZ*H$ z2F-uZZKKsZbe?Ury;6`<_Eg)sf|d+eJkqSYm47=7QAQ-_-q(vMn+?e3tEZ?BVg4s4 z+|<0~FNLbdG(E(_VD#LxR7N?Or&~^yhzguFP^4<24)#Gvny@~K*?^Lt26^?nqUv`# z@gyJ~;8iha5E9GZ_(acDO7clb>L)&LgN1U{*&%cZJh=XPfoY-bw3GfIUGM5!>yW~( z+Nkrfs|{_;3Q;x3lVZ$3$SaMx@XE4t;T83RT$LN1Q7*vGf=f#%u53^{0<^!3`Q6$X zc+dyayvpr(O^ytt=R=83rV2He(qjHI6jMlQ#AyE%B}PF|2@IA39adiqQ=C2Z~IWc4>`nV+0PfS0W#3{xT0B3z}>;@6u3({oZd=I<(a0Qp!kxTFdTh# zjbf?C1JqN$Yni|d^=cOlOzaG#MV3G^uy0j5u*VfivY1~uB!2-+%E)G3xkA_JszIpJ zfGis~)RpH@L&fxA{m9^QR2v4AYv2i5o?b3Bc6gFt4A_HF)%8e!;D#Hh8Fc%t6u0m7 z#qQE;2i{bxCRxNa9afOU`mzftQJqTE)JCFP9f{VDtc5gLF%q|GeYKP(DC^5+lLq-9 z>l!?(_809$HS@lJ9H^egvHdZD?#@=fQEvZ?s4_~9`vm6x3JWN@rwNxdc{h`08aTrG8&k)wDIT3o@`q9$7};-^lO%^7~Es zy<2`iCcn4J@0;cKI{AIE{Eo`+I{95Izo*FW5`1$5zW@ya3-J~7y1NdY9Yq>2?WGPs zK#o4zZ|g@MmxD7n`E^XJzCJO9AJ6y>;Bo`V^=lf3XH&&5NZoY5aLq;AaDi-#vsd7K z2zWHG-6fd8mHlO)jtt#ushN%JNEWXzd&|ZBrQIKhCIy@-TbjVU?FVorD z4u4z%A_L?<252{Qga^MyghsZs1}06_JLyW_45UFH`$Fan^xh|VivmH6#)aPccjQet z<>lw=zK}aJ&;6Wz;L2)Pf5ksc zPtk`xPG3o$5>;#dTearLiZ$PsTfO&9yZrff)5d(1_&e4$o#!o}_dS(gQ0{$xLw$jk z|Ni;ZagWm{!gRdmEh*O)Uu`)X>S-4Ush^kH1sDH3joMB+w)U-&%z$~-gY zR8O@*{%bpy_F9h`|nl|Mk9L$Ow4Mh{qo@e5T>?N5WylZw4b_ z2Tvw)a1w#&*kQwj>6auYQK0{i%}L~hMb5knJYyHA<50x!3pGaKreK~FAb)vKYS;~3 zqzJ~Kw9tyLoW=y5mgbX4-BQztr=5E0W058jM|ue6k9P?=)F_tl`@-Rf>52Mcal_*a z1Y$-!uEDs!(Fi0$hNoiYY)>c>S)7Q9MqfA(g8PGUPt3S55sVoDF~#;&B#LGo3dT(% zY{bS=8B$(!@kCCbK>r_>6Clr|06HryY4POvWznTOs34()ARr#`FQ!t({PbC~Rv;--so}3Os%K%y*pjK8N@T&HNmhS#Dn1mPuvKhf#nVnVPlD1Oj(5~1dflJ!BEH(^2HiZ5hiNHGo`{i zyRvrn^z$q8Jb_?5W;FO>0YMFM!T^D&EX1CFC#}HYq?N?q+W#c2tN)v{j^J+?e&Y}u z{1d4SiV0!{hpS#^@;Ctj};Xw1tdn zF;(8tkS`b(W+WCf!e*KYbwN`zmiU^5FA)evU;-UCMTgtxblemS@Hrhd4No|@MnfVN z5|M@mmwGyn`I>CGXgD9W9Fmy`X(IVe9+>s6lr8!7k+7L>0$vn{H=KTxKubK7Ruq&N zAo3G|2nG^|qnqMOBB*Mk#c;t9ziF8HaT6vriDkj4i`kM7B;Oxtic)V!2W|ath8+U!vL!7Oedp)cHEc!)n6F)Usm^udW@`rsyy&tn?CXv7rLQCYDt zGM{b4no+vSSS%8gxlY9dVTo@k+!AXJ`V9|qZ^o!7Rm?g|OslP}9#&LPMAeoPN4+Zr z7?RBB8PHd%mBLZe2)MPP}!)8SCMeL)OOAS}k;jpj6fr z6;GB!XX~&>hH7aLPotm}m28OqnC%rnM}LvylPx=^&XaSVCuiE&oEc+tW_za2s1>rY zmq92Wf0Wg{ocID+b`h%+vuNI-Mtvdc(Kb<@ja5z1bH*@bDJ<0Xx%jM}r68i`dy5St znvWjSY}i#Plg>a*P7H}A{JB!7e=CGIq|%(zpNxBi;^B`@)uBf^0!_ol zhCzpH?$id+A22be7D*G_Kroh@6Cc8pYr7kcL;s-}wpo@i>+?(O)<;bM3RIP93Wo_% zN;9tUrHz<4!k(ZRGR9922aFa^q~1eChjkK^hR4mN;G2zkX2A1n%9Pq_17btSs5i%9 zavz}RpC1c0G-57XWHgQQ$SFv@uPGQ>I@W_lY9t=@`HgX&i%N$nZKcCx-d##*V1Xe; z>G=ccQfg9!^I*0R;!Mg4VJ=%uo^G@~JpiLk2<(|?SL|vqTL}~){;56$A(XN$nd0%Y z5!O>ms6x16F=~ZSlyKQ_*bG!wqO35|Mc#zbR3uL@P-fPR=WZatRRvY;Gk0%y8e=Fbiy+OfOs;lMMZu!u%|d(P3V%em*C zn@=$rvp8B7p$0g*Qta$clKu10C+ygYahSp=jfVYOj{s;O@Tn*dg(6GFdZt#^=6PtI znCF>RSzeLnnLKOe%*x3)omE{seb&s`QhLT&lV?>aOA()Bi;(TmXu%RaPOIKv+>4N< zk9=}F2AIDgC^3pS2;oqnTZCsg$|+|k=?!*RCY#wJvDApm>6dn-C}=dJzIc2|K%8+# z0kRyp95mV(9Z2W2&anjR z4@l)~(`P2oB}Nv?3I=gaE~#JAKh-}`WpOdPvgVx18t=^V8I{gs2die*tXev)m^FFM zjLMm{UJb}ay=+o&0V#8 zbf+6AJfvSNA-8lQJ|ZF%jS*=5Crg}~09Q#rfVJEO98+N_E)@_~)bshKVT z6imT0X4O`D%PT5s9EGT!RU->AdveY6>RMS`nTTvm$22fydQ~O)h168z#~DzFDYI1G z^0c<5eCF&b6p#&~63i~c-m5_OsU=Uz_3WEIS>IS(bOnLcx>LbMF>m|8n6rB>9= zs1~)A^fjXzo)FcQHC0v9Cy5!eW=@?oYj&j<9u!p-USKulP)fGQ4&|kslpwV)ZneBIT1~W zWc!uv-H{s8lV(G9G&2(M1Te?OdJ#huHFwg7$u9LmV#>`fDiLZ{esoXEG>Mk8a~TA& zmnOHDX>m*oWf}Z1@X5upsE_#?nh>Fl0F8;X9>OLadTHF_iy0p5vtcVOgd7o@^(ZFi z*C?!9$YQ$)`=K-|^HD;r3ku@c@Df;@#_AEVpMDQj2xxbq<=nT+9{?@7Bf5!qx)WfZ{E|Hsg}Gpcyxf?;fCN`J~Ael~Wvmug)JZ>cvozBMQ9v1M|jRoI6C$XQ--+ zX^G;Imp{;7Q1}Iy#|6>oyx4+aUL7U&UtfB8%)^+%6z@Ib(bty^;rh!|q(^^n|H1$CGaiBy zRQnh^uCxqid+;aPWo5VT(6LkJW4avMwOjWdJ$oH@eD4!ZJgEpx&%&Y;1$L(UkQmtQc9Op11 z1^bjZ9XfP~$E+*BRx}#S<4prBpQ zV3?I5gAOMxogT;?Y}O4PGLFQWATn+^NWTIE5KH{KesL0hIp1Q z_slEI^AzWKiWW#UFtNFE!LZFVnqjDiOrWGja{)HX zVPyf=SWQM`V#MVSX z9L2+>YhNe?!wO=NC0ITc4#_h~7Of#3fyK7wTx{Oe*`+Unh_8Tl2IBMLemKxy45ZG1 zgh|9-M3q=>nz3MA!ZdORQ-m8lB+nBjaer|JuIW@?ydaa5Gs_H81G;&eW)-pq=OAMi|Z-3CAv1x{p!b|-s16NYY zqcPB>;><)Ce<5t}HDF>86|=AupNUHw6^7qdCJ#g`Dp7@{&Rs&m`O2&7e97vkC~SfSb%9n{FpgmtkRtTE*dPs zWmJ}!oroH-nRH1+jomae#mXUss}=nyIbTR%=?OGWVWd}cZ^@2^mNIiFoJ!L-BQR79 zEXP$3Z0_UwdIP4EP)fTh3A)f=1p0ZZLxv9*=H+Y_BX2zh-$u+kA*Lc2(&KteJnoqq z^U)->pEzTZ;ipN0ZSNVjOob7~)^tD7&*ouAB94Jv8PiYXJ5TdPC0T)s(sF#aXB)V1 zg-Lh;X2i4Ipdrx3CC~$U%-E#04Ri?TUeH^{AwB2; z(5~IEZ#n_#LB~x*deE~$L!bfBb)fHoZUfDqg!G`dgB}F^8nkP7AugMdv_^m)J1c3` zf`)KQkqP=7=tfX49*Wul`UL2Epx@w`ufw3@8cK+{Eugo7 z-UzxIbO-2bcx>T4&~|ua=`iSK&^~yOsS94SPy*TybS`KeXbb4=pf`fP0J;NoBwpw7 z9_Zbmhd~#_l2%_lN3a336!dw}`Je;v+Lsle`$4yWhVVL>U7*`R_k&g>@SEVr32_9} z0~*4ck0yfN3%U^WZ%dFK)OTspx(jsDWl3u{=$}D92d%k0X|+Ed_Ja-t%~^?iq(Cb` z8$q83T?hIt=r+*TuYlh{e{&`L4*D)=*WQ@dtUgZ4Z@h)=FfT7{q=Ux)OdcWy*_(BrO0deHYaq5XjdZ%kTm zfqn)01L)?Pl2-2%g;;ts>K*i)TTt(y2SH8HJ8wh1gAUk&^q}qUfZsu}nx~K+Gy>ZGWFejc9SFJ@x93%W9s&)3p7J!(gH8gy3v>?XZqP>1&p|H% zZGVaon?MJG-Va&d^rIcS$>kiIYaE9gMbsh}00Pk{zN z{{*@c^!R6y9&|eBZqV7g@IG14vgeXk=Tn8)0-6h&1f2$Y)*sRCK<@=z4SMqPNoyZ%4})$a{8hAD(33$Ag64pB z#l*Z2G!OJ~&??XaZz4Tt|GywTXg%mQ(Dv^jJ?L7{gP=cxcJ&Bx?z>12dfIzP58Cl# zqz8TNuSgF%^E0Fey%}^bXw~OP4;lyU+7JE*%>(@avAW?lP(kGH?&f$sPk=|Qu_4|>sIqzCPXdx*LY zK>G#F1MS`3vZ_GqK|`RIgRTQz(ZRB|f%fWXS$jb%K@Wm{-N~}LVpq4hvt{Lhmg2Ws zt3a;+4S~J@x(?Le1?fS@_dt5kte%$j18ClHmemJ$@xFAtWtD(NdRx|9(CsH!RtxB% zlPv2-&|xRz715yo1$_^6*(sKF7<3WBB=(nJqaZCH}hgeo2Xzx6v1HHch=|FwMkPh@$#YhMG1(tF9K~Elur63+4 z_yUl>V=)A_V-U4ku2mS&bg4@FToFT-u=i{ko(9`F^ZqTd? zU^i&C*Rr;Nw!<$8>;hd1x*s%92fK$N-vI0eZ33MLx;X^9LH{0s-Joa0kskDV&|RQ; zCenkhSOUBA&|a2X)K`;0bi;b22mKhd z5%l$|ENdg^XB#Z*5zxkK&`v;~xz@6dfSz@oW%V6~@c^_GwAV)X4RjRfa!^0$X3*Iy z@C#@j=m(%xpbMWwdeA;kAwB3`&~2dgJCPprmZy;(bnCN7KMMWhIiv?Id>-jRle>`~ z^!*o+9`uDhNDulc=w8qXuOK~W|Gh{*8u`73^q`-ER)PNW4WtJh|0dFd)`M;XeFtUeRe|35F4BX(@&TSa0Ik}Gb_co>^a$u)(B5Ovo`w3f zTUI05we)OvO4m-EH?-^2lW+`wV)fvph3;j4+Ljjrp;F2B!~CNIPP+G;(!I}_J&s+{ zd4-s8^0+gG4@5Lq`Bi{=ptmyt{Gq(&*7CY^EU&p9+I?BEvfWT$(FY51Z;qRg_EDP!cM;r_$%Pw=;B{z^N#?ZbVky8v>gt# zec9XFkw9NS^zyHFhbFDtT>P7Cekt%dSf_X(Yp0)=vTr`~W3Kc~cKYSOe^-#SW;oMl zO|$LW4E|f-*JeBPXV1#k_U#0}b8!-Z*1^yEubqA$_Nm}Q-bj-2&jo`lz{z#V% zg|-c=!T;u5tU+A-vuyrW@J~Ar`cW3!hU__6lmYo*5BPKEWo}Ccz`p|gaZdZ1rFk+v zJ*7_1bzkh{XDzkur?)^P!N*i4mA@~Qej51g=O?XWkx$CLj&@sZ1pnI$k`{)D6kjz3 zng43=+j*1LElz&cCOiMF;4cS1?BWM){vPmO0skZ?zb0kh0q~y#zud`Rp5k{#jQbS) zGAF+!#m@!b0zYHlE~52S3^2AMIw zq=jKJ<->4_zZd+f415og90cDB{z4qvbySW#&QIy+*%4zQWS(})WbLraQ3!rX9p?Bh z{*^Yr8vMJ!uW<4&N$HP*zX$w{PJY(acKQwAm-^HEkoB<5-wys;;Aisl>);OzWUj|U z;Fp6x-qp{>$bRO5O+7oQy_#jm;6(Rz)I)ak7~6&ska;wmv_5f_VV}*f1-}{lGMRj2 zg8wP_D_!Z8lc+Cm1b+(lYtD4>E2Vx9ut&g;g1^Ser?%qo^Lvna8!}ijrpm$f>;ZHb z{I|fr#K|We37L%=|1eGu!#+`-Q>G!sF9m-b_?i4LAN(WW%f}A2FS8%DW7=}?H^no@ ztj*v*5B?ply4q~l)lTqfA8Nca=1^UYkYPubVLxOpXu;avS%xgXT~`A2d=L1U+Peq* z$xD;gZ(ZqcwbM@o{{`?Ty5jOUJ1#E-|BGKIt-D?6x7g`dfWK&Y(mLD4ud?}Dz`q6j z0+$bl*go6^{=F9^t)E@#58LVYgTLzHr1gS}zsu$ejIBd2Nm>yXf05*SfO)`Q2L6lA z{K>~Vr3uo<6_DwBDW2zZ%4DyzZKR9l>o3E8pev7G+cvBO{~zE#?Bc7yNB!Y0@K;=( zv_5k2-?P*22ES}&X8z~k{}=pCuJqT~>DwQR{&YpsdfZiq57~7%5d2Q7VZW<R3BHPu(TcE$e0hNPA6@f&cimNvpdv z4{8hTWj2Cjsv&d7b=c!^%1m9CeK{ssBt`XULT1gzr1gqZCi?}utQ)}}zA0&41X()< zXQ{!M(mw+J2JrvtvhxGGzTN_V)=f#P*_Hl6+t)vUe>eEAxYEC1r|;bj={F~>9B2B4 zDPNBOzZU#sUG{gh?XLxY!mZe!bf)*F(wpE<20!FV-(aWT2>#W#W!C=)_{(ljTC<$` zv(B{3_ZIl~g5S}lzn!iB2hzVKX<@mT@~@e)uXlH>gTXI#@|UFeBf#Gcep@kv>Zca` zM2qUHtn}fICVAAE$26n~1N{NRrTA8t(Xr>FR};O8DC zy$SyDN8xV-KZ*Lyv{rZo{GLZi{}%W^A$_KG>kr^l`HpkiKO<#-?_MYt_*0zxta2$p z{u=>)1NhkPNtIuP7vTX^3;spmcX9SVijy(|s=bdE$oTI}T7P%y$oj(0<3{lF?@C&J z7ykmAzXSXz_!qeN=h^)Cz<&Vz87_WmZ{aZbA08!rA2{b%cPFh2UFk!%{u1yPfxp?s zzrp6u1^-L%Gqtf6@ZSc%-j&`b(|ds32>vPeB&~DPeKm)ZI61K*GIMVRZ`<7jqXClVn0kAQDJoV3O| z(>v$?*zdRs{7h@PQt%%F|2CI@Z?gS6AN<0{GTXNt{2Rbu?94w)1!A&qGx(o^?{o3z z+vVE{{s3Ihe96WCqs`w3{wv@g=l}tG{qb1`yZqo^i|dLnyXt>;s{T(v{XL5{l5@_K zz0BUzCqeX())1^CNceAPf?`v-r*?#$!-eDJRY-|I@R7NL}W zIrwjY|Fz5iU)uiP4E|*Fln_}1B5%90x zo3#GovhUBS@?(IW^rxiNuRR3p_S3gL3CQw;Klu%;4PE))YUe*6{1@KDb!%7u_^aJN z=sN$Jw{e}?mH+K_{&fAn+dG-}#CC$e8vMCf-=yrDP1~Z8~ONA@29 z|2yzA&BOZk!JZxXKfBVW)|RE<@BIYpJ{NzTZU21m%Ra^Z5l+6^K9=?^2mfsF?{WF> z4%>g5!GHHNym!KxK5Lb&e<%2pKF8YB#edG`?*sn;_|skd3Y&if{9a#R?e65OWvR5U zFYb3J0{=EAKkFtteJS`4g8!kbeY_*v$3Uc+5B{RRXwFj^o z{AJ+Rx%dn0^jpE-3I1@G{RPr~57O)b|Fs{JR+f`bYjD+Er4J86=Kg=8F|YHH#W@81=mt$c27R zTGzR3xk}nXZRbYt{|f$7&bBq{>g=o9ukWy~WA^W;k>x^e7vy4DcoxB#U$vIIyc1s{ zQ00g0_V$)_lT$W(qg{txVb~DdU-5{`rU#`>9$iOUkCp^-0LClMAbHCPq*_w z1b)ZkENhNyPEal91XRYJ2!`WMvaH!o`>BjmqzdWB5s+Eb$Fdf?=2i9fys8%bM^Cq` z^Pta;%UQM3kH}t_;C}=DEEiubz&yYF}XW!G%9tK!ewTpk2y1VrQ%!m z?b4;vjsWC7$+fJht~#A0>(m21E5YwP6whcl$7%9;AGJ3{GFu^Y4DOW)I(3{W_m$2k zMdVky&uV5No?*eU?USt4c6sRjtEa&K%&8;$W803dSTJ8a+_KuG`9163QiUu_A!O!_ zu&ksjkN?}0@#8i>3jQ_VXPWbD0Dt~yyuiUyfGYqD`8WX!WH>ken^%ie6yyB-1m zU$gMD6)qoD*gkp-{L{|1tTUj?w$YF#NFV$Fe(q8Dz5C(53-E_K)2r<(nSKQLmEd3Q z*SJc+58$3Kk4yh4 zw*I-q$Gu{i=I$-vUpe2(xaWT(_$Mz&i*H%4+V<@L{}u2zx$?ip&i_5|CwkG&UG}R@ zDjGKrgC7R}J12ieYTV4)FSC-q95?`d2KTicp9NuiOzCdNjSBDw<9@d*oVun_98{au z9^j3TSq+(Uoc5kYGHPU@c2D;`KIzXKzvzC*!MKm^4re}Dn{A)aeUe+j&vEh{`_^>- zg6!`o@$W^1y!<{9-5HaSgu;{5Oum4}t#~_(PrP>r?vIf&a}>^4|vj zPv8%Brmst--wS@0fpOL84kp`qzQ~x5c>M(wSZ@*JV502L4~c$M$`y9jYxo$=?h9 zUhp%;orB=-2j6t2cihj@br9M)?$4w*|EAh`AKQO<;1@Mn)|W2+CpNzd{C|frb~yDr z)>9$yPl{Mpk&~~s6s7&^z|RH0t+9>z>^AUgz<;s>PINzX^x5pKsX51cklk-umM_~O zn?2ti#}0$vuf@uEJ*^KKSzqw)b=sPBm)+M&z`q-Ouge$bOJ8`9W-j=jFU364nV#ln zj(u{v@Avp+ZO^Z$z0v)^lfnPgsUzzn+lHOsclb5#4|MTU*Gcw)Uj+Vimk%mz9~=Sy zeB3YF-&KZF?fUEsr_aB{vaWLR*Vz10@LySBS$}fnzsI(3KKM&6MSpUo_uA=~ga6cJ zmbJ>2{!%;rX7Kx6j{9s~{M5Z7JHfvm{7mEgKJafp3jYZB_a24ccL?s|KMKDT{HMWx z&Sl?D+y43BU$8Q>eapdbJPLm^__3q#cY?qCDExikuL3`le~*BF5d0l3`&0MY^o3(r z;=bueTzs`2r1n_~ejnUVeY1;yeX9K6Ukm<7SN*5%d0P(t@2*5VbH&5Xc0Ak+{zlxF z{eUa|y>|QA34Z^zmi2*)|F+HF2mZcwmi1>B|7Dwh1pMDzWmzA(`0v>Kz8I(~aewzg z7yoZIzZCpl*CJjz%kQ|3IUoG);JfwzCCl<8>+c4}l+b z@*VfQ%?Cg0mdx>MIrzK5zulGoX1o1t27mHq%X-ws-){4Fg8v@)gIxaWXZvp-_#fkb z_X}P8kmP%y^9cCEZpVDW86Rn$eX?}1AQ=xPL&d+vvkER9>fR5qMFssqX2YF4pP$sd z=ha!0y7##%yRy4yefvq>bJum4*1d35$7$V5F7Gs>`@~rHlJf3_<=t~9b@xCH@{_uE zmiKM1gPtAGL)}4tdg9X!{rtO&yW4fH_bxeQH^f{*cnSRUk zzf50a{h7S}(o2dnV2`2&Ovf;NmFd~fDE=c%7wlB$4Noh2+_Q>$nLf?5V3)#QVfsGP zI?lJtTZ*6Q`~P(NKKht89Pmsf7vNJq&x9XjK5b>tN6R0|pyywV(^fitwERzLdMrNg z{8wd<-kUg<&j&Kq`R4NZ$TWNmpHEK1r}B9XQ(az-pPME>kI#)XJjmxu((qsN`6{NJ zRB^>seEz#M`TO|%@ihD?K7T00{$U#a zS3dtC4L{81T|RNQ!)|=upQ$d_AU>a*hEL`5KpNi2=PhaYaz0;|hHv2W2h#9|`21<6 zx?cXs=YLAWwfvimYy02f^Doozzw`MIY4~A2Z~v+CkJi(f&reFjPvP^SY4|Wc=Wddb z{3vfu!u2PXIKt<;f3^Qf*`dp?&TwA?%Xei;@0OuYH$}vu_mu>0SCpT^ivE(G!snft zp3Jm_`Ly3nAI-zOt)UBz@0(|edc#`Hy|?=bz6>5oi1;+lfY zpXnf`qnJ)%dJfZirp-)OG2O)U9;S~meUa%qOuuCMBh!w!Rv`0dI*92grc;=n!?d1h zGt*T}H!;13>0?Y^Wcm)%FPZ+xv||D1&vX#eQB0>WJ%?#M(`Kftm~LWv57Wn(zR2_) zre8Ask!iL=*0 z7Dc`-tYSr_!e8V0*M@(oxTxvR->dWYepGbJVMVnCS8zOD!*o5QnnZWv{HyV>I#wtf8y=Gt`9sc@n{;}k8!;|*NH~spq==Y=zMm6 z32CoRk$7wWGy$i4?H^i`sqkJsDc{=9Hv(_V{ySMu7v48`ko7#y_!Erta$4*K-VU>k zLiU@UXS~gLNgDn!>p7JQh>u5pZT$fYTYjoblq{D1f&)#MO*{%lL0u{x-(1 zS*w7F-2Ld8Da!Ya^$Ne6mR&G@s7f44yaFEIWm#uwbCfH2PK^B&{tZ&2qS zDI&gOd=WJ~d^RZ}I>9d4Zf{b6e3u3e`!K%f4u#A2PvCGM<6qvcaQWT}92PPj`JKYM zvpwS(Uvsa*<+~$rIGyp+A6EE4MMO2@lNp!qS^$sUpG9`+eK4N3i3=Im`(lGx&uYf? zKHBk&(=)H6NAIg?{1L|WzS>DFzlU+X&!+KxjO%^29xVSo<9griSjOr7T9mKehog8z zpVJxF`+{127~^`MP~#IA*ZYR@o?hsg&A8r2)bfiM*ZYd5%oWdUF|PLmk7N8g#s~9$ z-YCXzXZ)m_RmFB=d>iAN{-^+p@fR4^`-2xS{t@GPe~`Pq_?~gSU#R7e!9tY$ruPpo zWId-dUa(66n;9R;_=M*aAfH3WVFlv@UR3x5ZlCiQKk}Nw$0{NsjE{O<0Tqm|WW3K` z6mTWu*E7DD_b*>!{9eZE_A8)@@kbedfboYIf1dG$pC~}L=hqp(lJNm7{~6=IXS{;( z?|{>|kee3w+ILX?{D$S{vivEGFZ)aZUdD$rKIKydOl7>9@%4-^V?4%qC)N{Z{94Ax zQ-H;1G2;&aZ--U7XG(vG+z7kr^D4`~&wAu@H^BEXzWWO)CggJpIQ)U}PJdIle6|>e zU9e$5?dR_Y6)v9%#$gWQ$Np2{zg1?5F^u2;ox zPh|W6-LQF`mWtT+H~MH2EtTe?3k9TE^dG9L+<1ZUIjIkM>iB zT*vtD8Gml5!XIIr-q}X-i9ChxV1r&_Jb#$N_bMXZXZ%0(13mbRWc+*J)E}p%^~a7V zIN{Z4cpu=DZ$YtA@CN5QlyPf>TYnYfBStBFCg*D~{%)xPk`J#;E9raCKC8Y z;8ZVBUN7qXv-?^8`bwooJ|hYFT~fY}SjhG-1V*1XSpFN9pQT{&8RKPBlpfAT9F}@| zid_u!Vfh}|P$NH#o~GnE9E<*pFOm4#-b4%dh8#tmD#^jJME)6Cawl(dQb*NBb0@=b4)szm#$L+#lp0 zXMB55$;;>cfWOT6y&OMzdM7?)e4@Nr7VofO`~SiCMpNmL&*VW*5;(=%UA)iN6BvCu zcTxE3Y4}Nu?@z-A0H=Dnc$w0FhEgL&GQKqppTYQ>j1On|0OK8gt@K>Z_?3*WW_$$W zn;GB9xWV{V#``T-dgL>B;QbLe)niZI@6apB4_SWXWlCPR^M5dYCgbusJm|3)e~17&Zh<`HvkLML|knx`x|B(lF zJ&v4;g(3NQ)XPdxzEcu;7Xfc;eO(5e>|eq5YkOu%ypPzER*&;oehbU5;Bti-_tf;4 zNPzLBjIU-KVNHI11Dx!vc}>}={dN=M%NUQc{15$<{NEYZ{=b9e_r9+5@G?x?%lP6q z6#gjdd4h4zn+hMKh6-6#fi)ma%+xe#N@-;lb%J-Lp_eY8A+*0)I4ER^9$NP}VS3XmSWIr=*-k|Wc-0_Y_K%n}4?N)_P zU&-<>0w@2>jVWLU<8Nlr|78aJ z=M4C9=v?fS^gBBk5#jtki_}K zK~?~#@~*g0ffdYK%lND^1?Y9nEv$bNPcYYTz1*8YKfS{d|66_DV?FwQz%H!kpTNnU zAEGMBI!;ONawNa$`wHbd55enxyuv^1sT6Ew`F@N~<&Ec07#|~XK5>vLmY;OD0_8iB zad<%n`6$cl`yMgvl%G`@f$#$RFi*MC%ie3u*!AC&Qdg&gDqmTxIm;7I0u#rU5%aO(Yv!xDEW;KOb*es&kT zH>rBr&Uo+sZI|m;8RG45*0Y4?Cv27|%^-hn27D24^8fabG9=9QG_(G%Zc%oAsfbw3 z_$5y$!7Et)rVRSGvHpj+eh0DqV;SUMVg0xNMG0~^7Vk4&Hb)sE--iT|e=t66mBRIY zW~UQWxlZ76>3zk%z}sp+^jnB+;eW{xuO>_R?&5}aD&L>ETyr?z-5fVIGVW#kl{E@r zcZdkcN#`0J93_g7`mUzY*D zGy{G;aB9!nctcB<>-G%t4@n&HlNW+|UB5enJiS|!;_YYql;QFnsW?2yc>C?DTvsU~ zl8n!|PXSe2-V-qYBt4(6Rk(b|4tT>E|Mm|`Fo)&GNt{m{WERWcd!5pw_kaArY5tHt zzm2l|HUCmd?qXf*fs@~+a{%CBM%*Oj9U1cB{jBHSwD|KlB>JDBw<<4Zaz{KNK&@iB1n&s}Nb<3W}`lj}F1_58s2Z#pPFFEZZg zSITcw9#gok$3DP&p(X13Z8%#onB_0JUMX0?dWHkIoWRcb-<~-%}q*}r*UEv%NKFG()Qn-LH`phfB6ojNB8T!jNi`#vK}8l%An_; zz{#F-E>U{caT$IB-V6K8`}uyM)r=p94cNBg@L=GiCvmY7{DkF;rF?g>koRW{#wW4- z=a(tqN#!OnljRSxV|cg~b0yA+9VCIkB74Bi}^}6RZsKhr3c-{gv3j z`;*!gCt%>9a*e)KA)hc~2ym*G7WSvfc#z|mzHeYZ?EB`!y#McQbz3XyrHgUQr}{ zit$0$Dm^bMws=+I3Uhw%XZhSKl%R*@|HF7zKuK3K-l?zh=V{!3;YRs64mkP0p8Mme zjGqjg>MMO6J&5JM>wAi{E73FAWsv; z)r@zVu5dlSqW8O!{g2bthZ-7($%;osmnQi*7ly?}& zhdtmZ%J-tJ3h2t^@<_b3d@*op&p&ZPmcJJUvGJ^@BhLf%criv?{^PF8QKbOZB-A~_Pylk|RkFkIL zCUI8kAW4>=mo|=cKTY}hJRXnkVLbzZlRcku{9nns3K*x~IHixiE;)(yEPFyJ7|D9( zu>1-xSD8vCye$98Qwo^Ecnjmx9#=pqU-ee!cFhv(bl z7=N1O_4AB>XZ#(;`_w2s^4+)Kea-mflNA0c%eTWkko3RL{ax4BF~F(a>gP6f95|Kn z2YEn~?|_1?V%9T)7hV^${_#?tPaLEs1K!B`zh}R(yM@X4!xNMeJs()XxPCrUkH4E3 zkJl;r^EvN389$vB_>?;Yz5lkYad3AA{G$x`cdXy!8!mKv%l5Rb|AY+qFo|~;`ngs; zPo4&x>dW8;c)U=b^H~119qN2L;|;)Ryzb58wVod)fRmo=%aq_JEPp9*s`ujI3b>K+ zYZ;$?p8_so{8owciGw^O@$OQTA8YXrFoh4kINuW!zJ01$MNkE&Z?eq ztG!aNmhm`nD%bWE3gB%WaS3pmx9jIvR;I$CvEc zomO98GoEvb(zA=@{{tNVTYYYo{k`>b7AFi)`VVs)&~fq%iMLWCN`X^(M{@vvnnk8C z{xH|?AjWH0|L)_IofESZgWd;BFgg??04H>2pC>T9z%;>g-y!F9w(CdrEd`rDX*o-X| z^)X+Q;SD63nwBDoQDgX^WE3)tG~Pc#}W1*40K#)$ezB32hP1*E(QGZ^xQB1?>zALXL7zCZv8!(lp( z8BLL9!#?%Uu;V`+7%;b=tFsXlKos9A@@()*N0Fzz*Cu}F-LiHVbNgiaz+ct*J* z7)G0eoytmeM9y|QDup{;l|r4)N}(jHn^6iSS&jPqej}=^CcBy%V%|nyIDoF@H_ z7r`oR)EA6VI8klgfhi?gP?nV1A2*^zEC{bOMG=O=rtpQ#xn@MjYZ4|LW1eDVOcY>r6l|afHqDI zz?+hnfh8johDIa7uqk_%%uObbsc=JTT9&%AO;_)42$J@==`(|Vlq483gJEwI!h+Xa z8bzcAlgel#wk?Flj0+QJ>*`-1r#sC>8U7k=0{4&^*)40Ov9DZ&q zIF=NR8jW!!6okvYsf6Th3Tzk`lv`MrbncRP8)xxG-(uO_s4$^mm_m4}B&Z^EWK@sW zFntZu6HTTJnG}}MQ*2+TA|R?a80pm?H)057RO(_Wu1Xh=2etFklqkocMPk4V`(%(t zzm;BV3M`5sbBjz`H3#1_p9PJQ6d#i{j{80i(E} zWF*FKCq&37N{-<>fYJqw7Fj5}^ipk3^y2zr%QaX09Olj zb96cCtsx9TW@Fn8X_WGaY~ga)mX`4l9>%;PUQjZ+NRGteL=#$vFX~-tU`!*kRIQ^e z8@fGU(8sjGfGLJoP6Lp-cqGZ94#N?2qeviFA4IbTBzuc2b|gvzsniKMIjT?~;oe2E zQcQJlv?Q6Dy9xTQKTuFoQY@<${TLoZzxVTSi^yk$<-o0uWFw5m4A_pK+7LudHwR;p za1%vCWF(F_jWm zQ%0iE#S6xa7%5GXl`OgOM(Tq!-$W6~+CVstm?sap!2_TvS|a8*aNv)`0)m7b{gPZB zjOuBhH&XAFeThP$?6-P`=Zh~5`@Ke^u)U9&c^s3_282G+Z6L%4fT)oLmg!>|R%4jC zVC>`L=n_aKq6nJ^L6{i?sY$acZCfB1kA{3pMIs!;EZNl5%fZ7w*Ike0U`jMZtBWZ$ zdZOb%4w`PQb*RF4f+D6GqZbFG0%MfvMJtI;oH(^=`lQL;;)3FW zk<^0Fk=+>TuAXLgREetLBvhP|?_s4*@OY@q3hFM;?Ej@^ERuMTagRmx^L0M^6#a%wC`4~opK1Tp;k8)LNW z3j3o=Te0m0uQWx^MwEC{TFuGYP_v4d@J_Ft0jKKpwKFEua=F%5ho~Ai1Cc~)n{`)` zi_*qO+*FeV+kG+~#1nOKe=JysNgYK7V)81%hd$hlbu2Q#iny`K=l5b#R3yAcOE4`n zDs&r#l}#%VwzDARSfI)X$4!aq3uq!nQ#09$%t!*$>{u($QQ(kHL!(0k(-p^29WBmY zFHxA2QA*B0)Pw~Q75&{Om!)piXoS9i8-hVx-Ocf^I&ur3MN+;9F>c(kbKvR{YH3Hy z30^`_4s!WRC35)OYcF}~{b4iY)~-9a&kZ9}O!-hPdg`n!){UJuDv+J**LEzG5m`=g zizz@v4VqE5(P5O4m@$zGT5w|G#LHCFIsPN=)XM?WZIjpAqGF&MrkI1dn;V2?*-)A@ zbZ5?)98N)Hq*sJN9(Do?6GvJK;6IK9oQ#V!U+={Ll%)_RagHYK_7L`TwWJ%FYfzwC)P zrEsC$2_H~kY^9XrK|M7?irJBR%#>S6$xe#k>x+|tY0f8C)JGF$x_78VYD0uq?K8+O;VRI<=jPAyL1aTRql+bp2zdgR50*j zHigL`8YI<<8FA-Q55M@`5DG(`D}jEGq14x)=Gn44QbAQW!f03@Y@u^))e<>y%AlVf z9qqd0prodOvR}9A1eCiy%BO8}QCD(L=Tf4MT{fz$Hp+y=GD|NOI7W+_jwpkg64-md zq3ryPzIdZ*T3EaoO|2Rg&yVD+3eE_o2LL2#HPWiakNq}scX~Urdl}76XzP(=+6w=0 z4K>gv44G(dGG@xi<{AKHSCuez9DAEV!l_nb^M=b68r7Ph4U9-@zft|l`LqnqXo=WC z$95965q6l~YeMsqdqU3ncr$GYQ*c5XZtWM$6PLt-6b&(VkWHEAd?apSSFu&glqHKM z>JTSoW29vY%1@^lfQ_c8xwKVJf^rJPs;kH*%Qm^%n(QK8Zv$4(s%)5O%USHG5v{C1 z4RLU?mtCqQ($*k3C>~)aPaAmwF)a?WJb0-q+YswJWcU{T}VI8({x5JJk-wmc?L zq*~9iWk`^9Z11y5Ps!O4ImbJF7LsC*!kfSzhjbmnlN==2J$wlP9o!K+cm_@#3dM>q zjW_cWsg+A)=9m&gz*^ zc%xgftRbHaB~X`>U=(S8~aL(V|~ zb73f@(NFu6+P54SRP&a3QqXYit~nD)wY=xuswiopOb&R>WW1aYV9iQ##7iqgI-hR6w+?!M&R?roBJxtjbsiM^nFblpS>o!-EY_76|%ew;QsxwJCF*S2ww3P-WW#qq=|~hbDNLcI7!P-yUQ>ERrxZM5Wx)UtpHqKGE z*t*s6RCe)19U^|CZl(SN))Vmtwug1PbPM!qO6`({1l`V^7g*8I)&7$Xq^{j384f6hkP5h# zH)k9>-gU8vFCaHnDL$t)540JqT3Z!AjC&w_A+&j#Nn`Sb&;v<1d1@s~eI|%m4OWJ! zZFX5uI;HASTVMz%Ffm}%`>>u+ZA0&H0hb+@=Qqxgz^T%)5h=y(3A=P3wFzt^>()d% zX{|z?sTsqYzs09I6-w2r46ZIBTNyT<7q=3F4>))<$(frP%XyL6Xf|OREp^S#-eGc7 zi=gWht<;9~Dgai}#a(Y5?Qo{VLJCXS&r(YZVctuL6LfmD2Oj@!hRws z!i1!a`bb{WjEVwW2r~-GCr!_%tE%d(A)F|ni_d|4TxlqvGjggZ2rLalpQ4z-N)BIV zcb#~_!<^Pf3HT@)GDU$5bp<#qXo%p{q!m^Hg#-vi>M zsTBH{Qc+$|Ano!sVMDb*>B8Jb6wtbxERj)PhXY(^mlh5$}@M`QOL~n&xu44oo{U z)nq0P=$=`feit8TIt}lUp-)HrQQ38ReLwa&z_RhD)9d#)YpUPp4-xrE_umCT>0S9c zy?)QLrY~|jZNHY&bTRn!?tOi(-v_PfLQbDnOs_6ZK|<@CD#^z(h1_M#5z_;?)0bV!f4QjR*ke($!X71TK#pY;CsEO^fJ`u*IR z9>{kj#-a9`MqkE3cl=QwqK|%$cVUIHC|zEkYx*|Q^uV7^uiy7w@;^-f3DT1NI=y}` z_(V>>T{ld~(8nXcQ(xcUkVJHP{r>PnXDa&-k#c;r8f~|32Xx=OGk^V_@%>dQeIKn@ zYDxJ|>-l$Ddiy!!YL)(VPN#`SA29tHlyvEA_E-0poYy%$KSs^ct;4&D_><*cRSahx|O%ps@p}Y9`0vd-t#-A>?j=$7DwCzp}yH=|7{~h2&RenySSBCUY QZdK{^eeXJrwqKwBKbeU*6951J literal 0 HcmV?d00001 diff --git a/util/mongoose.c b/util/mongoose.c new file mode 100644 index 0000000..9026762 --- /dev/null +++ b/util/mongoose.c @@ -0,0 +1,16548 @@ +#include "mongoose.h" +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_internal.h" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +#ifndef CS_MONGOOSE_SRC_INTERNAL_H_ +#define CS_MONGOOSE_SRC_INTERNAL_H_ + +/* Amalgamated: #include "common/mg_mem.h" */ + +#ifndef MBUF_REALLOC +#define MBUF_REALLOC MG_REALLOC +#endif + +#ifndef MBUF_FREE +#define MBUF_FREE MG_FREE +#endif + +#define MG_SET_PTRPTR(_ptr, _v) \ + do { \ + if (_ptr) *(_ptr) = _v; \ + } while (0) + +#ifndef MG_INTERNAL +#define MG_INTERNAL static +#endif + +#ifdef PICOTCP +#define NO_LIBC +#define MG_DISABLE_PFS +#endif + +/* Amalgamated: #include "common/cs_dbg.h" */ +/* Amalgamated: #include "mg_http.h" */ +/* Amalgamated: #include "mg_net.h" */ + +#ifndef MG_CTL_MSG_MESSAGE_SIZE +#define MG_CTL_MSG_MESSAGE_SIZE 8192 +#endif + +/* internals that need to be accessible in unit tests */ +MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc, + int proto, + union socket_address *sa); + +MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa, + int *proto, char *host, size_t host_len); +MG_INTERNAL void mg_call(struct mg_connection *nc, + mg_event_handler_t ev_handler, void *user_data, int ev, + void *ev_data); +void mg_forward(struct mg_connection *from, struct mg_connection *to); +MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c); +MG_INTERNAL void mg_remove_conn(struct mg_connection *c); +MG_INTERNAL struct mg_connection *mg_create_connection( + struct mg_mgr *mgr, mg_event_handler_t callback, + struct mg_add_sock_opts opts); +#ifdef _WIN32 +/* Retur value is the same as for MultiByteToWideChar. */ +int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len); +#endif + +struct ctl_msg { + mg_event_handler_t callback; + char message[MG_CTL_MSG_MESSAGE_SIZE]; +}; + +#if MG_ENABLE_MQTT +struct mg_mqtt_message; + +#define MG_MQTT_ERROR_INCOMPLETE_MSG -1 +#define MG_MQTT_ERROR_MALFORMED_MSG -2 + +MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm); +#endif + +/* Forward declarations for testing. */ +extern void *(*test_malloc)(size_t size); +extern void *(*test_calloc)(size_t count, size_t size); + +#ifndef MIN +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif + +#if MG_ENABLE_HTTP +struct mg_serve_http_opts; + +/* + * Reassemble the content of the buffer (buf, blen) which should be + * in the HTTP chunked encoding, by collapsing data chunks to the + * beginning of the buffer. + * + * If chunks get reassembled, modify hm->body to point to the reassembled + * body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK + * in nc->flags, delete reassembled body from the mbuf. + * + * Return reassembled body size. + */ +MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc, + struct http_message *hm, char *buf, + size_t blen); + +#if MG_ENABLE_FILESYSTEM +MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm, + const struct mg_serve_http_opts *opts, + char **local_path, + struct mg_str *remainder); +MG_INTERNAL time_t mg_parse_date_string(const char *datetime); +MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st); +#endif +#if MG_ENABLE_HTTP_CGI +MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog, + const struct mg_str *path_info, + const struct http_message *hm, + const struct mg_serve_http_opts *opts); +struct mg_http_proto_data_cgi; +MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d); +#endif +#if MG_ENABLE_HTTP_SSI +MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc, + struct http_message *hm, + const char *path, + const struct mg_serve_http_opts *opts); +#endif +#if MG_ENABLE_HTTP_WEBDAV +MG_INTERNAL int mg_is_dav_request(const struct mg_str *s); +MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path, + cs_stat_t *stp, struct http_message *hm, + struct mg_serve_http_opts *opts); +MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path); +MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path, + struct http_message *hm); +MG_INTERNAL void mg_handle_move(struct mg_connection *c, + const struct mg_serve_http_opts *opts, + const char *path, struct http_message *hm); +MG_INTERNAL void mg_handle_delete(struct mg_connection *nc, + const struct mg_serve_http_opts *opts, + const char *path); +MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path, + struct http_message *hm); +#endif +#if MG_ENABLE_HTTP_WEBSOCKET +MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev, + void *ev_data MG_UD_ARG(void *user_data)); +MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc, + const struct mg_str *key, + struct http_message *); +#endif +#endif /* MG_ENABLE_HTTP */ + +MG_INTERNAL int mg_get_errno(void); + +MG_INTERNAL void mg_close_conn(struct mg_connection *conn); + +#if MG_ENABLE_SNTP +MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len, + struct mg_sntp_message *msg); +#endif + +#endif /* CS_MONGOOSE_SRC_INTERNAL_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/mg_mem.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_MG_MEM_H_ +#define CS_COMMON_MG_MEM_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef MG_MALLOC +#define MG_MALLOC malloc +#endif + +#ifndef MG_CALLOC +#define MG_CALLOC calloc +#endif + +#ifndef MG_REALLOC +#define MG_REALLOC realloc +#endif + +#ifndef MG_FREE +#define MG_FREE free +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* CS_COMMON_MG_MEM_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/cs_base64.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef EXCLUDE_COMMON + +/* Amalgamated: #include "common/cs_base64.h" */ + +#include + +/* Amalgamated: #include "common/cs_dbg.h" */ + +/* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */ + +#define NUM_UPPERCASES ('Z' - 'A' + 1) +#define NUM_LETTERS (NUM_UPPERCASES * 2) +#define NUM_DIGITS ('9' - '0' + 1) + +/* + * Emit a base64 code char. + * + * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps + */ +static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) { + if (v < NUM_UPPERCASES) { + ctx->b64_putc(v + 'A', ctx->user_data); + } else if (v < (NUM_LETTERS)) { + ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data); + } else if (v < (NUM_LETTERS + NUM_DIGITS)) { + ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data); + } else { + ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/', + ctx->user_data); + } +} + +static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) { + int a, b, c; + + a = ctx->chunk[0]; + b = ctx->chunk[1]; + c = ctx->chunk[2]; + + cs_base64_emit_code(ctx, a >> 2); + cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4)); + if (ctx->chunk_size > 1) { + cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6)); + } + if (ctx->chunk_size > 2) { + cs_base64_emit_code(ctx, c & 63); + } +} + +void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc, + void *user_data) { + ctx->chunk_size = 0; + ctx->b64_putc = b64_putc; + ctx->user_data = user_data; +} + +void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) { + const unsigned char *src = (const unsigned char *) str; + size_t i; + for (i = 0; i < len; i++) { + ctx->chunk[ctx->chunk_size++] = src[i]; + if (ctx->chunk_size == 3) { + cs_base64_emit_chunk(ctx); + ctx->chunk_size = 0; + } + } +} + +void cs_base64_finish(struct cs_base64_ctx *ctx) { + if (ctx->chunk_size > 0) { + int i; + memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size); + cs_base64_emit_chunk(ctx); + for (i = 0; i < (3 - ctx->chunk_size); i++) { + ctx->b64_putc('=', ctx->user_data); + } + } +} + +#define BASE64_ENCODE_BODY \ + static const char *b64 = \ + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \ + int i, j, a, b, c; \ + \ + for (i = j = 0; i < src_len; i += 3) { \ + a = src[i]; \ + b = i + 1 >= src_len ? 0 : src[i + 1]; \ + c = i + 2 >= src_len ? 0 : src[i + 2]; \ + \ + BASE64_OUT(b64[a >> 2]); \ + BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \ + if (i + 1 < src_len) { \ + BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \ + } \ + if (i + 2 < src_len) { \ + BASE64_OUT(b64[c & 63]); \ + } \ + } \ + \ + while (j % 4 != 0) { \ + BASE64_OUT('='); \ + } \ + BASE64_FLUSH() + +#define BASE64_OUT(ch) \ + do { \ + dst[j++] = (ch); \ + } while (0) + +#define BASE64_FLUSH() \ + do { \ + dst[j++] = '\0'; \ + } while (0) + +void cs_base64_encode(const unsigned char *src, int src_len, char *dst) { + BASE64_ENCODE_BODY; +} + +#undef BASE64_OUT +#undef BASE64_FLUSH + +#if CS_ENABLE_STDIO +#define BASE64_OUT(ch) \ + do { \ + fprintf(f, "%c", (ch)); \ + j++; \ + } while (0) + +#define BASE64_FLUSH() + +void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) { + BASE64_ENCODE_BODY; +} + +#undef BASE64_OUT +#undef BASE64_FLUSH +#endif /* CS_ENABLE_STDIO */ + +/* Convert one byte of encoded base64 input stream to 6-bit chunk */ +static unsigned char from_b64(unsigned char ch) { + /* Inverse lookup map */ + static const unsigned char tab[128] = { + 255, 255, 255, 255, + 255, 255, 255, 255, /* 0 */ + 255, 255, 255, 255, + 255, 255, 255, 255, /* 8 */ + 255, 255, 255, 255, + 255, 255, 255, 255, /* 16 */ + 255, 255, 255, 255, + 255, 255, 255, 255, /* 24 */ + 255, 255, 255, 255, + 255, 255, 255, 255, /* 32 */ + 255, 255, 255, 62, + 255, 255, 255, 63, /* 40 */ + 52, 53, 54, 55, + 56, 57, 58, 59, /* 48 */ + 60, 61, 255, 255, + 255, 200, 255, 255, /* 56 '=' is 200, on index 61 */ + 255, 0, 1, 2, + 3, 4, 5, 6, /* 64 */ + 7, 8, 9, 10, + 11, 12, 13, 14, /* 72 */ + 15, 16, 17, 18, + 19, 20, 21, 22, /* 80 */ + 23, 24, 25, 255, + 255, 255, 255, 255, /* 88 */ + 255, 26, 27, 28, + 29, 30, 31, 32, /* 96 */ + 33, 34, 35, 36, + 37, 38, 39, 40, /* 104 */ + 41, 42, 43, 44, + 45, 46, 47, 48, /* 112 */ + 49, 50, 51, 255, + 255, 255, 255, 255, /* 120 */ + }; + return tab[ch & 127]; +} + +int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len) { + unsigned char a, b, c, d; + int orig_len = len; + char *orig_dst = dst; + while (len >= 4 && (a = from_b64(s[0])) != 255 && + (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 && + (d = from_b64(s[3])) != 255) { + s += 4; + len -= 4; + if (a == 200 || b == 200) break; /* '=' can't be there */ + *dst++ = a << 2 | b >> 4; + if (c == 200) break; + *dst++ = b << 4 | c >> 2; + if (d == 200) break; + *dst++ = c << 6 | d; + } + *dst = 0; + if (dec_len != NULL) *dec_len = (dst - orig_dst); + return orig_len - len; +} + +#endif /* EXCLUDE_COMMON */ +#ifdef MG_MODULE_LINES +#line 1 "common/cs_dbg.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_CS_DBG_H_ +#define CS_COMMON_CS_DBG_H_ + +/* Amalgamated: #include "common/platform.h" */ + +#if CS_ENABLE_STDIO +#include +#endif + +#ifndef CS_ENABLE_DEBUG +#define CS_ENABLE_DEBUG 0 +#endif + +#ifndef CS_LOG_PREFIX_LEN +#define CS_LOG_PREFIX_LEN 24 +#endif + +#ifndef CS_LOG_ENABLE_TS_DIFF +#define CS_LOG_ENABLE_TS_DIFF 0 +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* + * Log level; `LL_INFO` is the default. Use `cs_log_set_level()` to change it. + */ +enum cs_log_level { + LL_NONE = -1, + LL_ERROR = 0, + LL_WARN = 1, + LL_INFO = 2, + LL_DEBUG = 3, + LL_VERBOSE_DEBUG = 4, + + _LL_MIN = -2, + _LL_MAX = 5, +}; + +/* + * Set max log level to print; messages with the level above the given one will + * not be printed. + */ +void cs_log_set_level(enum cs_log_level level); + +/* + * A comma-separated set of prefix=level. + * prefix is matched against the log prefix exactly as printed, including line + * number, but partial match is ok. Check stops on first matching entry. + * If nothing matches, default level is used. + * + * Examples: + * main.c:=4 - everything from main C at verbose debug level. + * mongoose.c=1,mjs.c=1,=4 - everything at verbose debug except mg_* and mjs_* + * + */ +void cs_log_set_file_level(const char *file_level); + +/* + * Helper function which prints message prefix with the given `level`. + * If message should be printed (according to the current log level + * and filter), prints the prefix and returns 1, otherwise returns 0. + * + * Clients should typically just use `LOG()` macro. + */ +int cs_log_print_prefix(enum cs_log_level level, const char *fname, int line); + +extern enum cs_log_level cs_log_level; + +#if CS_ENABLE_STDIO + +/* + * Set file to write logs into. If `NULL`, logs go to `stderr`. + */ +void cs_log_set_file(FILE *file); + +/* + * Prints log to the current log file, appends "\n" in the end and flushes the + * stream. + */ +void cs_log_printf(const char *fmt, ...) PRINTF_LIKE(1, 2); + +#if CS_ENABLE_STDIO + +/* + * Format and print message `x` with the given level `l`. Example: + * + * ```c + * LOG(LL_INFO, ("my info message: %d", 123)); + * LOG(LL_DEBUG, ("my debug message: %d", 123)); + * ``` + */ +#define LOG(l, x) \ + do { \ + if (cs_log_print_prefix(l, __FILE__, __LINE__)) { \ + cs_log_printf x; \ + } \ + } while (0) + +#else + +#define LOG(l, x) ((void) l) + +#endif + +#ifndef CS_NDEBUG + +/* + * Shortcut for `LOG(LL_VERBOSE_DEBUG, (...))` + */ +#define DBG(x) LOG(LL_VERBOSE_DEBUG, x) + +#else /* NDEBUG */ + +#define DBG(x) + +#endif + +#else /* CS_ENABLE_STDIO */ + +#define LOG(l, x) +#define DBG(x) + +#endif + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* CS_COMMON_CS_DBG_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/cs_dbg.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Amalgamated: #include "common/cs_dbg.h" */ + +#include +#include +#include + +/* Amalgamated: #include "common/cs_time.h" */ +/* Amalgamated: #include "common/str_util.h" */ + +enum cs_log_level cs_log_level WEAK = +#if CS_ENABLE_DEBUG + LL_VERBOSE_DEBUG; +#else + LL_ERROR; +#endif + +#if CS_ENABLE_STDIO +static char *s_file_level = NULL; + +void cs_log_set_file_level(const char *file_level) WEAK; + +FILE *cs_log_file WEAK = NULL; + +#if CS_LOG_ENABLE_TS_DIFF +double cs_log_ts WEAK; +#endif + +enum cs_log_level cs_log_cur_msg_level WEAK = LL_NONE; + +void cs_log_set_file_level(const char *file_level) { + char *fl = s_file_level; + if (file_level != NULL) { + s_file_level = strdup(file_level); + } else { + s_file_level = NULL; + } + free(fl); +} + +int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) WEAK; +int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) { + char prefix[CS_LOG_PREFIX_LEN], *q; + const char *p; + size_t fl = 0, ll = 0, pl = 0; + + if (level > cs_log_level && s_file_level == NULL) return 0; + + p = file + strlen(file); + + while (p != file) { + const char c = *(p - 1); + if (c == '/' || c == '\\') break; + p--; + fl++; + } + + ll = (ln < 10000 ? (ln < 1000 ? (ln < 100 ? (ln < 10 ? 1 : 2) : 3) : 4) : 5); + if (fl > (sizeof(prefix) - ll - 2)) fl = (sizeof(prefix) - ll - 2); + + pl = fl + 1 + ll; + memcpy(prefix, p, fl); + q = prefix + pl; + memset(q, ' ', sizeof(prefix) - pl); + do { + *(--q) = '0' + (ln % 10); + ln /= 10; + } while (ln > 0); + *(--q) = ':'; + + if (s_file_level != NULL) { + enum cs_log_level pll = cs_log_level; + struct mg_str fl = mg_mk_str(s_file_level), ps = MG_MK_STR_N(prefix, pl); + struct mg_str k, v; + while ((fl = mg_next_comma_list_entry_n(fl, &k, &v)).p != NULL) { + bool yes = !(!mg_str_starts_with(ps, k) || v.len == 0); + if (!yes) continue; + pll = (enum cs_log_level)(*v.p - '0'); + break; + } + if (level > pll) return 0; + } + + if (cs_log_file == NULL) cs_log_file = stderr; + cs_log_cur_msg_level = level; + fwrite(prefix, 1, sizeof(prefix), cs_log_file); +#if CS_LOG_ENABLE_TS_DIFF + { + double now = cs_time(); + fprintf(cs_log_file, "%7u ", (unsigned int) ((now - cs_log_ts) * 1000000)); + cs_log_ts = now; + } +#endif + return 1; +} + +void cs_log_printf(const char *fmt, ...) WEAK; +void cs_log_printf(const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + vfprintf(cs_log_file, fmt, ap); + va_end(ap); + fputc('\n', cs_log_file); + fflush(cs_log_file); + cs_log_cur_msg_level = LL_NONE; +} + +void cs_log_set_file(FILE *file) WEAK; +void cs_log_set_file(FILE *file) { + cs_log_file = file; +} + +#else + +void cs_log_set_file_level(const char *file_level) { + (void) file_level; +} + +#endif /* CS_ENABLE_STDIO */ + +void cs_log_set_level(enum cs_log_level level) WEAK; +void cs_log_set_level(enum cs_log_level level) { + cs_log_level = level; +#if CS_LOG_ENABLE_TS_DIFF && CS_ENABLE_STDIO + cs_log_ts = cs_time(); +#endif +} +#ifdef MG_MODULE_LINES +#line 1 "common/cs_dirent.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_CS_DIRENT_H_ +#define CS_COMMON_CS_DIRENT_H_ + +#include + +/* Amalgamated: #include "common/platform.h" */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifdef CS_DEFINE_DIRENT +typedef struct { int dummy; } DIR; + +struct dirent { + int d_ino; +#ifdef _WIN32 + char d_name[MAX_PATH]; +#else + /* TODO(rojer): Use PATH_MAX but make sure it's sane on every platform */ + char d_name[256]; +#endif +}; + +DIR *opendir(const char *dir_name); +int closedir(DIR *dir); +struct dirent *readdir(DIR *dir); +#endif /* CS_DEFINE_DIRENT */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* CS_COMMON_CS_DIRENT_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/cs_dirent.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef EXCLUDE_COMMON + +/* Amalgamated: #include "common/mg_mem.h" */ +/* Amalgamated: #include "common/cs_dirent.h" */ + +/* + * This file contains POSIX opendir/closedir/readdir API implementation + * for systems which do not natively support it (e.g. Windows). + */ + +#ifdef _WIN32 +struct win32_dir { + DIR d; + HANDLE handle; + WIN32_FIND_DATAW info; + struct dirent result; +}; + +DIR *opendir(const char *name) { + struct win32_dir *dir = NULL; + wchar_t wpath[MAX_PATH]; + DWORD attrs; + + if (name == NULL) { + SetLastError(ERROR_BAD_ARGUMENTS); + } else if ((dir = (struct win32_dir *) MG_MALLOC(sizeof(*dir))) == NULL) { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + } else { + to_wchar(name, wpath, ARRAY_SIZE(wpath)); + attrs = GetFileAttributesW(wpath); + if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) { + (void) wcscat(wpath, L"\\*"); + dir->handle = FindFirstFileW(wpath, &dir->info); + dir->result.d_name[0] = '\0'; + } else { + MG_FREE(dir); + dir = NULL; + } + } + + return (DIR *) dir; +} + +int closedir(DIR *d) { + struct win32_dir *dir = (struct win32_dir *) d; + int result = 0; + + if (dir != NULL) { + if (dir->handle != INVALID_HANDLE_VALUE) + result = FindClose(dir->handle) ? 0 : -1; + MG_FREE(dir); + } else { + result = -1; + SetLastError(ERROR_BAD_ARGUMENTS); + } + + return result; +} + +struct dirent *readdir(DIR *d) { + struct win32_dir *dir = (struct win32_dir *) d; + struct dirent *result = NULL; + + if (dir) { + memset(&dir->result, 0, sizeof(dir->result)); + if (dir->handle != INVALID_HANDLE_VALUE) { + result = &dir->result; + (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1, + result->d_name, sizeof(result->d_name), NULL, + NULL); + + if (!FindNextFileW(dir->handle, &dir->info)) { + (void) FindClose(dir->handle); + dir->handle = INVALID_HANDLE_VALUE; + } + + } else { + SetLastError(ERROR_FILE_NOT_FOUND); + } + } else { + SetLastError(ERROR_BAD_ARGUMENTS); + } + + return result; +} +#endif + +#endif /* EXCLUDE_COMMON */ + +/* ISO C requires a translation unit to contain at least one declaration */ +typedef int cs_dirent_dummy; +#ifdef MG_MODULE_LINES +#line 1 "common/cs_time.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Amalgamated: #include "common/cs_time.h" */ + +#ifndef _WIN32 +#include +/* + * There is no sys/time.h on ARMCC. + */ +#if !(defined(__ARMCC_VERSION) || defined(__ICCARM__)) && \ + !defined(__TI_COMPILER_VERSION__) && \ + (!defined(CS_PLATFORM) || CS_PLATFORM != CS_P_NXP_LPC) +#include +#endif +#else +#include +#endif + +double cs_time(void) WEAK; +double cs_time(void) { + double now; +#ifndef _WIN32 + struct timeval tv; + if (gettimeofday(&tv, NULL /* tz */) != 0) return 0; + now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0); +#else + SYSTEMTIME sysnow; + FILETIME ftime; + GetLocalTime(&sysnow); + SystemTimeToFileTime(&sysnow, &ftime); + /* + * 1. VC 6.0 doesn't support conversion uint64 -> double, so, using int64 + * This should not cause a problems in this (21th) century + * 2. Windows FILETIME is a number of 100-nanosecond intervals since January + * 1, 1601 while time_t is a number of _seconds_ since January 1, 1970 UTC, + * thus, we need to convert to seconds and adjust amount (subtract 11644473600 + * seconds) + */ + now = (double) (((int64_t) ftime.dwLowDateTime + + ((int64_t) ftime.dwHighDateTime << 32)) / + 10000000.0) - + 11644473600; +#endif /* _WIN32 */ + return now; +} + +double cs_timegm(const struct tm *tm) { + /* Month-to-day offset for non-leap-years. */ + static const int month_day[12] = {0, 31, 59, 90, 120, 151, + 181, 212, 243, 273, 304, 334}; + + /* Most of the calculation is easy; leap years are the main difficulty. */ + int month = tm->tm_mon % 12; + int year = tm->tm_year + tm->tm_mon / 12; + int year_for_leap; + int64_t rt; + + if (month < 0) { /* Negative values % 12 are still negative. */ + month += 12; + --year; + } + + /* This is the number of Februaries since 1900. */ + year_for_leap = (month > 1) ? year + 1 : year; + + rt = + tm->tm_sec /* Seconds */ + + + 60 * + (tm->tm_min /* Minute = 60 seconds */ + + + 60 * (tm->tm_hour /* Hour = 60 minutes */ + + + 24 * (month_day[month] + tm->tm_mday - 1 /* Day = 24 hours */ + + 365 * (year - 70) /* Year = 365 days */ + + (year_for_leap - 69) / 4 /* Every 4 years is leap... */ + - (year_for_leap - 1) / 100 /* Except centuries... */ + + (year_for_leap + 299) / 400))); /* Except 400s. */ + return rt < 0 ? -1 : (double) rt; +} +#ifdef MG_MODULE_LINES +#line 1 "common/cs_endian.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_CS_ENDIAN_H_ +#define CS_COMMON_CS_ENDIAN_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * clang with std=-c99 uses __LITTLE_ENDIAN, by default + * while for ex, RTOS gcc - LITTLE_ENDIAN, by default + * it depends on __USE_BSD, but let's have everything + */ +#if !defined(BYTE_ORDER) && defined(__BYTE_ORDER) +#define BYTE_ORDER __BYTE_ORDER +#ifndef LITTLE_ENDIAN +#define LITTLE_ENDIAN __LITTLE_ENDIAN +#endif /* LITTLE_ENDIAN */ +#ifndef BIG_ENDIAN +#define BIG_ENDIAN __LITTLE_ENDIAN +#endif /* BIG_ENDIAN */ +#endif /* BYTE_ORDER */ + +#ifdef __cplusplus +} +#endif + +#endif /* CS_COMMON_CS_ENDIAN_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/cs_md5.c" +#endif +/* + * This code implements the MD5 message-digest algorithm. + * The algorithm is due to Ron Rivest. This code was + * written by Colin Plumb in 1993, no copyright is claimed. + * This code is in the public domain; do with it what you wish. + * + * Equivalent code is available from RSA Data Security, Inc. + * This code has been tested against that, and is equivalent, + * except that you don't need to include two pages of legalese + * with every copy. + * + * To compute the message digest of a chunk of bytes, declare an + * MD5Context structure, pass it to MD5Init, call MD5Update as + * needed on buffers full of bytes, and then call MD5Final, which + * will fill a supplied 16-byte array with the digest. + */ + +/* Amalgamated: #include "common/cs_md5.h" */ +/* Amalgamated: #include "common/str_util.h" */ + +#if !defined(EXCLUDE_COMMON) +#if !CS_DISABLE_MD5 + +/* Amalgamated: #include "common/cs_endian.h" */ + +static void byteReverse(unsigned char *buf, unsigned longs) { +/* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */ +#if BYTE_ORDER == BIG_ENDIAN + do { + uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 | + ((unsigned) buf[1] << 8 | buf[0]); + *(uint32_t *) buf = t; + buf += 4; + } while (--longs); +#else + (void) buf; + (void) longs; +#endif +} + +#define F1(x, y, z) (z ^ (x & (y ^ z))) +#define F2(x, y, z) F1(z, x, y) +#define F3(x, y, z) (x ^ y ^ z) +#define F4(x, y, z) (y ^ (x | ~z)) + +#define MD5STEP(f, w, x, y, z, data, s) \ + (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x) + +/* + * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious + * initialization constants. + */ +void cs_md5_init(cs_md5_ctx *ctx) { + ctx->buf[0] = 0x67452301; + ctx->buf[1] = 0xefcdab89; + ctx->buf[2] = 0x98badcfe; + ctx->buf[3] = 0x10325476; + + ctx->bits[0] = 0; + ctx->bits[1] = 0; +} + +static void cs_md5_transform(uint32_t buf[4], uint32_t const in[16]) { + register uint32_t a, b, c, d; + + a = buf[0]; + b = buf[1]; + c = buf[2]; + d = buf[3]; + + MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); + MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); + MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); + MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); + MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); + MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); + MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); + MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); + MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); + MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); + MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); + MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); + MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); + MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); + MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); + MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); + + MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); + MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); + MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); + MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); + MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); + MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); + MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); + MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); + MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); + MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); + MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); + MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); + MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); + MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); + MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); + MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); + + MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); + MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); + MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); + MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); + MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); + MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); + MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); + MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); + MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); + MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); + MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); + MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); + MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); + MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); + MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); + MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); + + MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); + MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); + MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); + MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); + MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); + MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); + MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); + MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); + MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); + MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); + MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); + MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); + MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); + MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); + MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); + MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); + + buf[0] += a; + buf[1] += b; + buf[2] += c; + buf[3] += d; +} + +void cs_md5_update(cs_md5_ctx *ctx, const unsigned char *buf, size_t len) { + uint32_t t; + + t = ctx->bits[0]; + if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++; + ctx->bits[1] += (uint32_t) len >> 29; + + t = (t >> 3) & 0x3f; + + if (t) { + unsigned char *p = (unsigned char *) ctx->in + t; + + t = 64 - t; + if (len < t) { + memcpy(p, buf, len); + return; + } + memcpy(p, buf, t); + byteReverse(ctx->in, 16); + cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); + buf += t; + len -= t; + } + + while (len >= 64) { + memcpy(ctx->in, buf, 64); + byteReverse(ctx->in, 16); + cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); + buf += 64; + len -= 64; + } + + memcpy(ctx->in, buf, len); +} + +void cs_md5_final(unsigned char digest[16], cs_md5_ctx *ctx) { + unsigned count; + unsigned char *p; + uint32_t *a; + + count = (ctx->bits[0] >> 3) & 0x3F; + + p = ctx->in + count; + *p++ = 0x80; + count = 64 - 1 - count; + if (count < 8) { + memset(p, 0, count); + byteReverse(ctx->in, 16); + cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); + memset(ctx->in, 0, 56); + } else { + memset(p, 0, count - 8); + } + byteReverse(ctx->in, 14); + + a = (uint32_t *) ctx->in; + a[14] = ctx->bits[0]; + a[15] = ctx->bits[1]; + + cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); + byteReverse((unsigned char *) ctx->buf, 4); + memcpy(digest, ctx->buf, 16); + memset((char *) ctx, 0, sizeof(*ctx)); +} + +#endif /* CS_DISABLE_MD5 */ +#endif /* EXCLUDE_COMMON */ +#ifdef MG_MODULE_LINES +#line 1 "common/cs_sha1.c" +#endif +/* Copyright(c) By Steve Reid */ +/* 100% Public Domain */ + +/* Amalgamated: #include "common/cs_sha1.h" */ + +#if !CS_DISABLE_SHA1 && !defined(EXCLUDE_COMMON) + +/* Amalgamated: #include "common/cs_endian.h" */ + +#define SHA1HANDSOFF +#if defined(__sun) +/* Amalgamated: #include "common/solarisfixes.h" */ +#endif + +union char64long16 { + unsigned char c[64]; + uint32_t l[16]; +}; + +#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) + +static uint32_t blk0(union char64long16 *block, int i) { +/* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */ +#if BYTE_ORDER == LITTLE_ENDIAN + block->l[i] = + (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF); +#endif + return block->l[i]; +} + +/* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */ +#undef blk +#undef R0 +#undef R1 +#undef R2 +#undef R3 +#undef R4 + +#define blk(i) \ + (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \ + block->l[(i + 2) & 15] ^ block->l[i & 15], \ + 1)) +#define R0(v, w, x, y, z, i) \ + z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \ + w = rol(w, 30); +#define R1(v, w, x, y, z, i) \ + z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \ + w = rol(w, 30); +#define R2(v, w, x, y, z, i) \ + z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \ + w = rol(w, 30); +#define R3(v, w, x, y, z, i) \ + z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \ + w = rol(w, 30); +#define R4(v, w, x, y, z, i) \ + z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \ + w = rol(w, 30); + +void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) { + uint32_t a, b, c, d, e; + union char64long16 block[1]; + + memcpy(block, buffer, 64); + a = state[0]; + b = state[1]; + c = state[2]; + d = state[3]; + e = state[4]; + R0(a, b, c, d, e, 0); + R0(e, a, b, c, d, 1); + R0(d, e, a, b, c, 2); + R0(c, d, e, a, b, 3); + R0(b, c, d, e, a, 4); + R0(a, b, c, d, e, 5); + R0(e, a, b, c, d, 6); + R0(d, e, a, b, c, 7); + R0(c, d, e, a, b, 8); + R0(b, c, d, e, a, 9); + R0(a, b, c, d, e, 10); + R0(e, a, b, c, d, 11); + R0(d, e, a, b, c, 12); + R0(c, d, e, a, b, 13); + R0(b, c, d, e, a, 14); + R0(a, b, c, d, e, 15); + R1(e, a, b, c, d, 16); + R1(d, e, a, b, c, 17); + R1(c, d, e, a, b, 18); + R1(b, c, d, e, a, 19); + R2(a, b, c, d, e, 20); + R2(e, a, b, c, d, 21); + R2(d, e, a, b, c, 22); + R2(c, d, e, a, b, 23); + R2(b, c, d, e, a, 24); + R2(a, b, c, d, e, 25); + R2(e, a, b, c, d, 26); + R2(d, e, a, b, c, 27); + R2(c, d, e, a, b, 28); + R2(b, c, d, e, a, 29); + R2(a, b, c, d, e, 30); + R2(e, a, b, c, d, 31); + R2(d, e, a, b, c, 32); + R2(c, d, e, a, b, 33); + R2(b, c, d, e, a, 34); + R2(a, b, c, d, e, 35); + R2(e, a, b, c, d, 36); + R2(d, e, a, b, c, 37); + R2(c, d, e, a, b, 38); + R2(b, c, d, e, a, 39); + R3(a, b, c, d, e, 40); + R3(e, a, b, c, d, 41); + R3(d, e, a, b, c, 42); + R3(c, d, e, a, b, 43); + R3(b, c, d, e, a, 44); + R3(a, b, c, d, e, 45); + R3(e, a, b, c, d, 46); + R3(d, e, a, b, c, 47); + R3(c, d, e, a, b, 48); + R3(b, c, d, e, a, 49); + R3(a, b, c, d, e, 50); + R3(e, a, b, c, d, 51); + R3(d, e, a, b, c, 52); + R3(c, d, e, a, b, 53); + R3(b, c, d, e, a, 54); + R3(a, b, c, d, e, 55); + R3(e, a, b, c, d, 56); + R3(d, e, a, b, c, 57); + R3(c, d, e, a, b, 58); + R3(b, c, d, e, a, 59); + R4(a, b, c, d, e, 60); + R4(e, a, b, c, d, 61); + R4(d, e, a, b, c, 62); + R4(c, d, e, a, b, 63); + R4(b, c, d, e, a, 64); + R4(a, b, c, d, e, 65); + R4(e, a, b, c, d, 66); + R4(d, e, a, b, c, 67); + R4(c, d, e, a, b, 68); + R4(b, c, d, e, a, 69); + R4(a, b, c, d, e, 70); + R4(e, a, b, c, d, 71); + R4(d, e, a, b, c, 72); + R4(c, d, e, a, b, 73); + R4(b, c, d, e, a, 74); + R4(a, b, c, d, e, 75); + R4(e, a, b, c, d, 76); + R4(d, e, a, b, c, 77); + R4(c, d, e, a, b, 78); + R4(b, c, d, e, a, 79); + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + state[4] += e; + /* Erase working structures. The order of operations is important, + * used to ensure that compiler doesn't optimize those out. */ + memset(block, 0, sizeof(block)); + a = b = c = d = e = 0; + (void) a; + (void) b; + (void) c; + (void) d; + (void) e; +} + +void cs_sha1_init(cs_sha1_ctx *context) { + context->state[0] = 0x67452301; + context->state[1] = 0xEFCDAB89; + context->state[2] = 0x98BADCFE; + context->state[3] = 0x10325476; + context->state[4] = 0xC3D2E1F0; + context->count[0] = context->count[1] = 0; +} + +void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data, + uint32_t len) { + uint32_t i, j; + + j = context->count[0]; + if ((context->count[0] += len << 3) < j) context->count[1]++; + context->count[1] += (len >> 29); + j = (j >> 3) & 63; + if ((j + len) > 63) { + memcpy(&context->buffer[j], data, (i = 64 - j)); + cs_sha1_transform(context->state, context->buffer); + for (; i + 63 < len; i += 64) { + cs_sha1_transform(context->state, &data[i]); + } + j = 0; + } else + i = 0; + memcpy(&context->buffer[j], &data[i], len - i); +} + +void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) { + unsigned i; + unsigned char finalcount[8], c; + + for (i = 0; i < 8; i++) { + finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> + ((3 - (i & 3)) * 8)) & + 255); + } + c = 0200; + cs_sha1_update(context, &c, 1); + while ((context->count[0] & 504) != 448) { + c = 0000; + cs_sha1_update(context, &c, 1); + } + cs_sha1_update(context, finalcount, 8); + for (i = 0; i < 20; i++) { + digest[i] = + (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); + } + memset(context, '\0', sizeof(*context)); + memset(&finalcount, '\0', sizeof(finalcount)); +} + +void cs_hmac_sha1(const unsigned char *key, size_t keylen, + const unsigned char *data, size_t datalen, + unsigned char out[20]) { + cs_sha1_ctx ctx; + unsigned char buf1[64], buf2[64], tmp_key[20], i; + + if (keylen > sizeof(buf1)) { + cs_sha1_init(&ctx); + cs_sha1_update(&ctx, key, keylen); + cs_sha1_final(tmp_key, &ctx); + key = tmp_key; + keylen = sizeof(tmp_key); + } + + memset(buf1, 0, sizeof(buf1)); + memset(buf2, 0, sizeof(buf2)); + memcpy(buf1, key, keylen); + memcpy(buf2, key, keylen); + + for (i = 0; i < sizeof(buf1); i++) { + buf1[i] ^= 0x36; + buf2[i] ^= 0x5c; + } + + cs_sha1_init(&ctx); + cs_sha1_update(&ctx, buf1, sizeof(buf1)); + cs_sha1_update(&ctx, data, datalen); + cs_sha1_final(out, &ctx); + + cs_sha1_init(&ctx); + cs_sha1_update(&ctx, buf2, sizeof(buf2)); + cs_sha1_update(&ctx, out, 20); + cs_sha1_final(out, &ctx); +} + +#endif /* EXCLUDE_COMMON */ +#ifdef MG_MODULE_LINES +#line 1 "common/mbuf.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef EXCLUDE_COMMON + +#include +#include +/* Amalgamated: #include "common/mbuf.h" */ + +#ifndef MBUF_REALLOC +#define MBUF_REALLOC realloc +#endif + +#ifndef MBUF_FREE +#define MBUF_FREE free +#endif + +void mbuf_init(struct mbuf *mbuf, size_t initial_size) WEAK; +void mbuf_init(struct mbuf *mbuf, size_t initial_size) { + mbuf->len = mbuf->size = 0; + mbuf->buf = NULL; + mbuf_resize(mbuf, initial_size); +} + +void mbuf_free(struct mbuf *mbuf) WEAK; +void mbuf_free(struct mbuf *mbuf) { + if (mbuf->buf != NULL) { + MBUF_FREE(mbuf->buf); + mbuf_init(mbuf, 0); + } +} + +void mbuf_resize(struct mbuf *a, size_t new_size) WEAK; +void mbuf_resize(struct mbuf *a, size_t new_size) { + if (new_size > a->size || (new_size < a->size && new_size >= a->len)) { + char *buf = (char *) MBUF_REALLOC(a->buf, new_size); + /* + * In case realloc fails, there's not much we can do, except keep things as + * they are. Note that NULL is a valid return value from realloc when + * size == 0, but that is covered too. + */ + if (buf == NULL && new_size != 0) return; + a->buf = buf; + a->size = new_size; + } +} + +void mbuf_trim(struct mbuf *mbuf) WEAK; +void mbuf_trim(struct mbuf *mbuf) { + mbuf_resize(mbuf, mbuf->len); +} + +size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t) WEAK; +size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) { + char *p = NULL; + + assert(a != NULL); + assert(a->len <= a->size); + assert(off <= a->len); + + /* check overflow */ + if (~(size_t) 0 - (size_t) a->buf < len) return 0; + + if (a->len + len <= a->size) { + memmove(a->buf + off + len, a->buf + off, a->len - off); + if (buf != NULL) { + memcpy(a->buf + off, buf, len); + } + a->len += len; + } else { + size_t min_size = (a->len + len); + size_t new_size = (size_t)(min_size * MBUF_SIZE_MULTIPLIER); + if (new_size - min_size > MBUF_SIZE_MAX_HEADROOM) { + new_size = min_size + MBUF_SIZE_MAX_HEADROOM; + } + p = (char *) MBUF_REALLOC(a->buf, new_size); + if (p == NULL && new_size != min_size) { + new_size = min_size; + p = (char *) MBUF_REALLOC(a->buf, new_size); + } + if (p != NULL) { + a->buf = p; + if (off != a->len) { + memmove(a->buf + off + len, a->buf + off, a->len - off); + } + if (buf != NULL) memcpy(a->buf + off, buf, len); + a->len += len; + a->size = new_size; + } else { + len = 0; + } + } + + return len; +} + +size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) WEAK; +size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) { + return mbuf_insert(a, a->len, buf, len); +} + +size_t mbuf_append_and_free(struct mbuf *a, void *buf, size_t len) WEAK; +size_t mbuf_append_and_free(struct mbuf *a, void *data, size_t len) { + size_t ret; + /* Optimization: if the buffer is currently empty, + * take over the user-provided buffer. */ + if (a->len == 0) { + if (a->buf != NULL) free(a->buf); + a->buf = (char *) data; + a->len = a->size = len; + return len; + } + ret = mbuf_insert(a, a->len, data, len); + free(data); + return ret; +} + +void mbuf_remove(struct mbuf *mb, size_t n) WEAK; +void mbuf_remove(struct mbuf *mb, size_t n) { + if (n > 0 && n <= mb->len) { + memmove(mb->buf, mb->buf + n, mb->len - n); + mb->len -= n; + } +} + +void mbuf_clear(struct mbuf *mb) WEAK; +void mbuf_clear(struct mbuf *mb) { + mb->len = 0; +} + +void mbuf_move(struct mbuf *from, struct mbuf *to) WEAK; +void mbuf_move(struct mbuf *from, struct mbuf *to) { + memcpy(to, from, sizeof(*to)); + memset(from, 0, sizeof(*from)); +} + +#endif /* EXCLUDE_COMMON */ +#ifdef MG_MODULE_LINES +#line 1 "common/mg_str.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Amalgamated: #include "common/mg_mem.h" */ +/* Amalgamated: #include "common/mg_str.h" */ +/* Amalgamated: #include "common/platform.h" */ + +#include +#include +#include + +int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK; + +struct mg_str mg_mk_str(const char *s) WEAK; +struct mg_str mg_mk_str(const char *s) { + struct mg_str ret = {s, 0}; + if (s != NULL) ret.len = strlen(s); + return ret; +} + +struct mg_str mg_mk_str_n(const char *s, size_t len) WEAK; +struct mg_str mg_mk_str_n(const char *s, size_t len) { + struct mg_str ret = {s, len}; + return ret; +} + +int mg_vcmp(const struct mg_str *str1, const char *str2) WEAK; +int mg_vcmp(const struct mg_str *str1, const char *str2) { + size_t n2 = strlen(str2), n1 = str1->len; + int r = strncmp(str1->p, str2, (n1 < n2) ? n1 : n2); + if (r == 0) { + return n1 - n2; + } + return r; +} + +int mg_vcasecmp(const struct mg_str *str1, const char *str2) WEAK; +int mg_vcasecmp(const struct mg_str *str1, const char *str2) { + size_t n2 = strlen(str2), n1 = str1->len; + int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2); + if (r == 0) { + return n1 - n2; + } + return r; +} + +static struct mg_str mg_strdup_common(const struct mg_str s, + int nul_terminate) { + struct mg_str r = {NULL, 0}; + if (s.len > 0 && s.p != NULL) { + char *sc = (char *) MG_MALLOC(s.len + (nul_terminate ? 1 : 0)); + if (sc != NULL) { + memcpy(sc, s.p, s.len); + if (nul_terminate) sc[s.len] = '\0'; + r.p = sc; + r.len = s.len; + } + } + return r; +} + +struct mg_str mg_strdup(const struct mg_str s) WEAK; +struct mg_str mg_strdup(const struct mg_str s) { + return mg_strdup_common(s, 0 /* NUL-terminate */); +} + +struct mg_str mg_strdup_nul(const struct mg_str s) WEAK; +struct mg_str mg_strdup_nul(const struct mg_str s) { + return mg_strdup_common(s, 1 /* NUL-terminate */); +} + +const char *mg_strchr(const struct mg_str s, int c) WEAK; +const char *mg_strchr(const struct mg_str s, int c) { + size_t i; + for (i = 0; i < s.len; i++) { + if (s.p[i] == c) return &s.p[i]; + } + return NULL; +} + +int mg_strcmp(const struct mg_str str1, const struct mg_str str2) WEAK; +int mg_strcmp(const struct mg_str str1, const struct mg_str str2) { + size_t i = 0; + while (i < str1.len && i < str2.len) { + if (str1.p[i] < str2.p[i]) return -1; + if (str1.p[i] > str2.p[i]) return 1; + i++; + } + if (i < str1.len) return 1; + if (i < str2.len) return -1; + return 0; +} + +int mg_strncmp(const struct mg_str, const struct mg_str, size_t n) WEAK; +int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n) { + struct mg_str s1 = str1; + struct mg_str s2 = str2; + + if (s1.len > n) { + s1.len = n; + } + if (s2.len > n) { + s2.len = n; + } + return mg_strcmp(s1, s2); +} + +void mg_strfree(struct mg_str *s) WEAK; +void mg_strfree(struct mg_str *s) { + char *sp = (char *) s->p; + s->p = NULL; + s->len = 0; + if (sp != NULL) free(sp); +} + +const char *mg_strstr(const struct mg_str haystack, + const struct mg_str needle) WEAK; +const char *mg_strstr(const struct mg_str haystack, + const struct mg_str needle) { + size_t i; + if (needle.len > haystack.len) return NULL; + for (i = 0; i <= haystack.len - needle.len; i++) { + if (memcmp(haystack.p + i, needle.p, needle.len) == 0) { + return haystack.p + i; + } + } + return NULL; +} + +struct mg_str mg_strstrip(struct mg_str s) WEAK; +struct mg_str mg_strstrip(struct mg_str s) { + while (s.len > 0 && isspace((int) *s.p)) { + s.p++; + s.len--; + } + while (s.len > 0 && isspace((int) *(s.p + s.len - 1))) { + s.len--; + } + return s; +} + +int mg_str_starts_with(struct mg_str s, struct mg_str prefix) WEAK; +int mg_str_starts_with(struct mg_str s, struct mg_str prefix) { + const struct mg_str sp = MG_MK_STR_N(s.p, prefix.len); + if (s.len < prefix.len) return 0; + return (mg_strcmp(sp, prefix) == 0); +} +#ifdef MG_MODULE_LINES +#line 1 "common/str_util.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef EXCLUDE_COMMON + +/* Amalgamated: #include "common/str_util.h" */ +/* Amalgamated: #include "common/mg_mem.h" */ +/* Amalgamated: #include "common/platform.h" */ + +#ifndef C_DISABLE_BUILTIN_SNPRINTF +#define C_DISABLE_BUILTIN_SNPRINTF 0 +#endif + +/* Amalgamated: #include "common/mg_mem.h" */ + +size_t c_strnlen(const char *s, size_t maxlen) WEAK; +size_t c_strnlen(const char *s, size_t maxlen) { + size_t l = 0; + for (; l < maxlen && s[l] != '\0'; l++) { + } + return l; +} + +#define C_SNPRINTF_APPEND_CHAR(ch) \ + do { \ + if (i < (int) buf_size) buf[i] = ch; \ + i++; \ + } while (0) + +#define C_SNPRINTF_FLAG_ZERO 1 + +#if C_DISABLE_BUILTIN_SNPRINTF +int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK; +int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) { + return vsnprintf(buf, buf_size, fmt, ap); +} +#else +static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags, + int field_width) { + char tmp[40]; + int i = 0, k = 0, neg = 0; + + if (num < 0) { + neg++; + num = -num; + } + + /* Print into temporary buffer - in reverse order */ + do { + int rem = num % base; + if (rem < 10) { + tmp[k++] = '0' + rem; + } else { + tmp[k++] = 'a' + (rem - 10); + } + num /= base; + } while (num > 0); + + /* Zero padding */ + if (flags && C_SNPRINTF_FLAG_ZERO) { + while (k < field_width && k < (int) sizeof(tmp) - 1) { + tmp[k++] = '0'; + } + } + + /* And sign */ + if (neg) { + tmp[k++] = '-'; + } + + /* Now output */ + while (--k >= 0) { + C_SNPRINTF_APPEND_CHAR(tmp[k]); + } + + return i; +} + +int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK; +int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) { + int ch, i = 0, len_mod, flags, precision, field_width; + + while ((ch = *fmt++) != '\0') { + if (ch != '%') { + C_SNPRINTF_APPEND_CHAR(ch); + } else { + /* + * Conversion specification: + * zero or more flags (one of: # 0 - + ') + * an optional minimum field width (digits) + * an optional precision (. followed by digits, or *) + * an optional length modifier (one of: hh h l ll L q j z t) + * conversion specifier (one of: d i o u x X e E f F g G a A c s p n) + */ + flags = field_width = precision = len_mod = 0; + + /* Flags. only zero-pad flag is supported. */ + if (*fmt == '0') { + flags |= C_SNPRINTF_FLAG_ZERO; + } + + /* Field width */ + while (*fmt >= '0' && *fmt <= '9') { + field_width *= 10; + field_width += *fmt++ - '0'; + } + /* Dynamic field width */ + if (*fmt == '*') { + field_width = va_arg(ap, int); + fmt++; + } + + /* Precision */ + if (*fmt == '.') { + fmt++; + if (*fmt == '*') { + precision = va_arg(ap, int); + fmt++; + } else { + while (*fmt >= '0' && *fmt <= '9') { + precision *= 10; + precision += *fmt++ - '0'; + } + } + } + + /* Length modifier */ + switch (*fmt) { + case 'h': + case 'l': + case 'L': + case 'I': + case 'q': + case 'j': + case 'z': + case 't': + len_mod = *fmt++; + if (*fmt == 'h') { + len_mod = 'H'; + fmt++; + } + if (*fmt == 'l') { + len_mod = 'q'; + fmt++; + } + break; + } + + ch = *fmt++; + if (ch == 's') { + const char *s = va_arg(ap, const char *); /* Always fetch parameter */ + int j; + int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0); + for (j = 0; j < pad; j++) { + C_SNPRINTF_APPEND_CHAR(' '); + } + + /* `s` may be NULL in case of %.*s */ + if (s != NULL) { + /* Ignore negative and 0 precisions */ + for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) { + C_SNPRINTF_APPEND_CHAR(s[j]); + } + } + } else if (ch == 'c') { + ch = va_arg(ap, int); /* Always fetch parameter */ + C_SNPRINTF_APPEND_CHAR(ch); + } else if (ch == 'd' && len_mod == 0) { + i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags, + field_width); + } else if (ch == 'd' && len_mod == 'l') { + i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags, + field_width); +#ifdef SSIZE_MAX + } else if (ch == 'd' && len_mod == 'z') { + i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags, + field_width); +#endif + } else if (ch == 'd' && len_mod == 'q') { + i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags, + field_width); + } else if ((ch == 'x' || ch == 'u') && len_mod == 0) { + i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned), + ch == 'x' ? 16 : 10, flags, field_width); + } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') { + i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long), + ch == 'x' ? 16 : 10, flags, field_width); + } else if ((ch == 'x' || ch == 'u') && len_mod == 'z') { + i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t), + ch == 'x' ? 16 : 10, flags, field_width); + } else if (ch == 'p') { + unsigned long num = (unsigned long) (uintptr_t) va_arg(ap, void *); + C_SNPRINTF_APPEND_CHAR('0'); + C_SNPRINTF_APPEND_CHAR('x'); + i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0); + } else { +#ifndef NO_LIBC + /* + * TODO(lsm): abort is not nice in a library, remove it + * Also, ESP8266 SDK doesn't have it + */ + abort(); +#endif + } + } + } + + /* Zero-terminate the result */ + if (buf_size > 0) { + buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0'; + } + + return i; +} +#endif + +int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) WEAK; +int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) { + int result; + va_list ap; + va_start(ap, fmt); + result = c_vsnprintf(buf, buf_size, fmt, ap); + va_end(ap); + return result; +} + +#ifdef _WIN32 +int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) { + int ret; + char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p; + + strncpy(buf, path, sizeof(buf)); + buf[sizeof(buf) - 1] = '\0'; + + /* Trim trailing slashes. Leave backslash for paths like "X:\" */ + p = buf + strlen(buf) - 1; + while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0'; + + memset(wbuf, 0, wbuf_len * sizeof(wchar_t)); + ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len); + + /* + * Convert back to Unicode. If doubly-converted string does not match the + * original, something is fishy, reject. + */ + WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2), + NULL, NULL); + if (strcmp(buf, buf2) != 0) { + wbuf[0] = L'\0'; + ret = 0; + } + + return ret; +} +#endif /* _WIN32 */ + +/* The simplest O(mn) algorithm. Better implementation are GPLed */ +const char *c_strnstr(const char *s, const char *find, size_t slen) WEAK; +const char *c_strnstr(const char *s, const char *find, size_t slen) { + size_t find_length = strlen(find); + size_t i; + + for (i = 0; i < slen; i++) { + if (i + find_length > slen) { + return NULL; + } + + if (strncmp(&s[i], find, find_length) == 0) { + return &s[i]; + } + } + + return NULL; +} + +#if CS_ENABLE_STRDUP +char *strdup(const char *src) WEAK; +char *strdup(const char *src) { + size_t len = strlen(src) + 1; + char *ret = MG_MALLOC(len); + if (ret != NULL) { + strcpy(ret, src); + } + return ret; +} +#endif + +void cs_to_hex(char *to, const unsigned char *p, size_t len) WEAK; +void cs_to_hex(char *to, const unsigned char *p, size_t len) { + static const char *hex = "0123456789abcdef"; + + for (; len--; p++) { + *to++ = hex[p[0] >> 4]; + *to++ = hex[p[0] & 0x0f]; + } + *to = '\0'; +} + +static int fourbit(int ch) { + if (ch >= '0' && ch <= '9') { + return ch - '0'; + } else if (ch >= 'a' && ch <= 'f') { + return ch - 'a' + 10; + } else if (ch >= 'A' && ch <= 'F') { + return ch - 'A' + 10; + } + return 0; +} + +void cs_from_hex(char *to, const char *p, size_t len) WEAK; +void cs_from_hex(char *to, const char *p, size_t len) { + size_t i; + + for (i = 0; i < len; i += 2) { + *to++ = (fourbit(p[i]) << 4) + fourbit(p[i + 1]); + } + *to = '\0'; +} + +#if CS_ENABLE_TO64 +int64_t cs_to64(const char *s) WEAK; +int64_t cs_to64(const char *s) { + int64_t result = 0; + int64_t neg = 1; + while (*s && isspace((unsigned char) *s)) s++; + if (*s == '-') { + neg = -1; + s++; + } + while (isdigit((unsigned char) *s)) { + result *= 10; + result += (*s - '0'); + s++; + } + return result * neg; +} +#endif + +static int str_util_lowercase(const char *s) { + return tolower(*(const unsigned char *) s); +} + +int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK; +int mg_ncasecmp(const char *s1, const char *s2, size_t len) { + int diff = 0; + + if (len > 0) do { + diff = str_util_lowercase(s1++) - str_util_lowercase(s2++); + } while (diff == 0 && s1[-1] != '\0' && --len > 0); + + return diff; +} + +int mg_casecmp(const char *s1, const char *s2) WEAK; +int mg_casecmp(const char *s1, const char *s2) { + return mg_ncasecmp(s1, s2, (size_t) ~0); +} + +int mg_asprintf(char **buf, size_t size, const char *fmt, ...) WEAK; +int mg_asprintf(char **buf, size_t size, const char *fmt, ...) { + int ret; + va_list ap; + va_start(ap, fmt); + ret = mg_avprintf(buf, size, fmt, ap); + va_end(ap); + return ret; +} + +int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) WEAK; +int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) { + va_list ap_copy; + int len; + + va_copy(ap_copy, ap); + len = vsnprintf(*buf, size, fmt, ap_copy); + va_end(ap_copy); + + if (len < 0) { + /* eCos and Windows are not standard-compliant and return -1 when + * the buffer is too small. Keep allocating larger buffers until we + * succeed or out of memory. */ + *buf = NULL; /* LCOV_EXCL_START */ + while (len < 0) { + MG_FREE(*buf); + if (size == 0) { + size = 5; + } + size *= 2; + if ((*buf = (char *) MG_MALLOC(size)) == NULL) { + len = -1; + break; + } + va_copy(ap_copy, ap); + len = vsnprintf(*buf, size - 1, fmt, ap_copy); + va_end(ap_copy); + } + + /* + * Microsoft version of vsnprintf() is not always null-terminated, so put + * the terminator manually + */ + (*buf)[len] = 0; + /* LCOV_EXCL_STOP */ + } else if (len >= (int) size) { + /* Standard-compliant code path. Allocate a buffer that is large enough. */ + if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) { + len = -1; /* LCOV_EXCL_LINE */ + } else { /* LCOV_EXCL_LINE */ + va_copy(ap_copy, ap); + len = vsnprintf(*buf, len + 1, fmt, ap_copy); + va_end(ap_copy); + } + } + + return len; +} + +const char *mg_next_comma_list_entry(const char *, struct mg_str *, + struct mg_str *) WEAK; +const char *mg_next_comma_list_entry(const char *list, struct mg_str *val, + struct mg_str *eq_val) { + struct mg_str ret = mg_next_comma_list_entry_n(mg_mk_str(list), val, eq_val); + return ret.p; +} + +struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val, + struct mg_str *eq_val) WEAK; +struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val, + struct mg_str *eq_val) { + if (list.len == 0) { + /* End of the list */ + list = mg_mk_str(NULL); + } else { + const char *chr = NULL; + *val = list; + + if ((chr = mg_strchr(*val, ',')) != NULL) { + /* Comma found. Store length and shift the list ptr */ + val->len = chr - val->p; + chr++; + list.len -= (chr - list.p); + list.p = chr; + } else { + /* This value is the last one */ + list = mg_mk_str_n(list.p + list.len, 0); + } + + if (eq_val != NULL) { + /* Value has form "x=y", adjust pointers and lengths */ + /* so that val points to "x", and eq_val points to "y". */ + eq_val->len = 0; + eq_val->p = (const char *) memchr(val->p, '=', val->len); + if (eq_val->p != NULL) { + eq_val->p++; /* Skip over '=' character */ + eq_val->len = val->p + val->len - eq_val->p; + val->len = (eq_val->p - val->p) - 1; + } + } + } + + return list; +} + +size_t mg_match_prefix_n(const struct mg_str, const struct mg_str) WEAK; +size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) { + const char *or_str; + size_t res = 0, len = 0, i = 0, j = 0; + + if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL || + (or_str = (const char *) memchr(pattern.p, ',', pattern.len)) != NULL) { + struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)}; + res = mg_match_prefix_n(pstr, str); + if (res > 0) return res; + pstr.p = or_str + 1; + pstr.len = (pattern.p + pattern.len) - (or_str + 1); + return mg_match_prefix_n(pstr, str); + } + + for (; i < pattern.len && j < str.len; i++, j++) { + if (pattern.p[i] == '?') { + continue; + } else if (pattern.p[i] == '*') { + i++; + if (i < pattern.len && pattern.p[i] == '*') { + i++; + len = str.len - j; + } else { + len = 0; + while (j + len < str.len && str.p[j + len] != '/') len++; + } + if (i == pattern.len || (pattern.p[i] == '$' && i == pattern.len - 1)) + return j + len; + do { + const struct mg_str pstr = {pattern.p + i, pattern.len - i}; + const struct mg_str sstr = {str.p + j + len, str.len - j - len}; + res = mg_match_prefix_n(pstr, sstr); + } while (res == 0 && len != 0 && len-- > 0); + return res == 0 ? 0 : j + res + len; + } else if (str_util_lowercase(&pattern.p[i]) != + str_util_lowercase(&str.p[j])) { + break; + } + } + if (i < pattern.len && pattern.p[i] == '$') { + return j == str.len ? str.len : 0; + } + return i == pattern.len ? j : 0; +} + +size_t mg_match_prefix(const char *, int, const char *) WEAK; +size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str) { + const struct mg_str pstr = {pattern, (size_t) pattern_len}; + struct mg_str s = {str, 0}; + if (str != NULL) s.len = strlen(str); + return mg_match_prefix_n(pstr, s); +} + +#endif /* EXCLUDE_COMMON */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_net.c" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + * + * This software is dual-licensed: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. For the terms of this + * license, see . + * + * You are free to use this software under the terms of the GNU General + * Public License, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * Alternatively, you can license this software under a commercial + * license, as set out in . + */ + +/* Amalgamated: #include "common/cs_time.h" */ +/* Amalgamated: #include "mg_dns.h" */ +/* Amalgamated: #include "mg_internal.h" */ +/* Amalgamated: #include "mg_resolv.h" */ +/* Amalgamated: #include "mg_util.h" */ + +#define MG_MAX_HOST_LEN 200 + +#ifndef MG_TCP_IO_SIZE +#define MG_TCP_IO_SIZE 1460 +#endif +#ifndef MG_UDP_IO_SIZE +#define MG_UDP_IO_SIZE 1460 +#endif + +#define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \ + memcpy(dst, src, sizeof(*dst)); + +/* Which flags can be pre-set by the user at connection creation time. */ +#define _MG_ALLOWED_CONNECT_FLAGS_MASK \ + (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \ + MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_ENABLE_BROADCAST) +/* Which flags should be modifiable by user's callbacks. */ +#define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK \ + (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \ + MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE | \ + MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK) + +#ifndef intptr_t +#define intptr_t long +#endif + +MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) { + DBG(("%p %p", mgr, c)); + c->mgr = mgr; + c->next = mgr->active_connections; + mgr->active_connections = c; + c->prev = NULL; + if (c->next != NULL) c->next->prev = c; + if (c->sock != INVALID_SOCKET) { + c->iface->vtable->add_conn(c); + } +} + +MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) { + if (conn->prev == NULL) conn->mgr->active_connections = conn->next; + if (conn->prev) conn->prev->next = conn->next; + if (conn->next) conn->next->prev = conn->prev; + conn->prev = conn->next = NULL; + conn->iface->vtable->remove_conn(conn); +} + +MG_INTERNAL void mg_call(struct mg_connection *nc, + mg_event_handler_t ev_handler, void *user_data, int ev, + void *ev_data) { + if (ev_handler == NULL) { + /* + * If protocol handler is specified, call it. Otherwise, call user-specified + * event handler. + */ + ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler; + } + if (ev != MG_EV_POLL) { + DBG(("%p %s ev=%d ev_data=%p flags=0x%lx rmbl=%d smbl=%d", nc, + ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags, + (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); + } + +#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP + if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL && ev != MG_EV_RECV && + ev != MG_EV_SEND /* handled separately */) { + mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev); + } +#endif + if (ev_handler != NULL) { + unsigned long flags_before = nc->flags; + ev_handler(nc, ev, ev_data MG_UD_ARG(user_data)); + /* Prevent user handler from fiddling with system flags. */ + if (ev_handler == nc->handler && nc->flags != flags_before) { + nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) | + (nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK); + } + } + if (ev != MG_EV_POLL) nc->mgr->num_calls++; + if (ev != MG_EV_POLL) { + DBG(("%p after %s flags=0x%lx rmbl=%d smbl=%d", nc, + ev_handler == nc->handler ? "user" : "proto", nc->flags, + (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); + } +#if !MG_ENABLE_CALLBACK_USERDATA + (void) user_data; +#endif +} + +MG_INTERNAL void mg_timer(struct mg_connection *c, double now) { + if (c->ev_timer_time > 0 && now >= c->ev_timer_time) { + double old_value = c->ev_timer_time; + c->ev_timer_time = 0; + mg_call(c, NULL, c->user_data, MG_EV_TIMER, &old_value); + } +} + +MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) { + size_t avail; + if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0; + avail = conn->recv_mbuf_limit - conn->recv_mbuf.len; + return avail > max ? max : avail; +} + +static int mg_do_recv(struct mg_connection *nc); + +int mg_if_poll(struct mg_connection *nc, double now) { + if (nc->flags & MG_F_CLOSE_IMMEDIATELY) { + mg_close_conn(nc); + return 0; + } else if (nc->flags & MG_F_SEND_AND_CLOSE) { + if (nc->send_mbuf.len == 0) { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + mg_close_conn(nc); + return 0; + } + } else if (nc->flags & MG_F_RECV_AND_CLOSE) { + mg_close_conn(nc); + return 0; + } +#if MG_ENABLE_SSL + if ((nc->flags & (MG_F_SSL | MG_F_LISTENING | MG_F_CONNECTING)) == MG_F_SSL) { + /* SSL library may have data to be delivered to the app in its buffers, + * drain them. */ + int recved = 0; + do { + if (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE)) break; + if (recv_avail_size(nc, MG_TCP_IO_SIZE) <= 0) break; + recved = mg_do_recv(nc); + } while (recved > 0); + } +#endif /* MG_ENABLE_SSL */ + mg_timer(nc, now); + { + time_t now_t = (time_t) now; + mg_call(nc, NULL, nc->user_data, MG_EV_POLL, &now_t); + } + return 1; +} + +void mg_destroy_conn(struct mg_connection *conn, int destroy_if) { + if (conn->sock != INVALID_SOCKET) { /* Don't print timer-only conns */ + LOG(LL_DEBUG, ("%p 0x%lx %d", conn, conn->flags, destroy_if)); + } + if (destroy_if) conn->iface->vtable->destroy_conn(conn); + if (conn->proto_data != NULL && conn->proto_data_destructor != NULL) { + conn->proto_data_destructor(conn->proto_data); + } +#if MG_ENABLE_SSL + mg_ssl_if_conn_free(conn); +#endif + mbuf_free(&conn->recv_mbuf); + mbuf_free(&conn->send_mbuf); + + memset(conn, 0, sizeof(*conn)); + MG_FREE(conn); +} + +void mg_close_conn(struct mg_connection *conn) { + /* See if there's any remaining data to deliver. Skip if user completely + * throttled the connection there will be no progress anyway. */ + if (conn->sock != INVALID_SOCKET && mg_do_recv(conn) == -2) { + /* Receive is throttled, wait. */ + conn->flags |= MG_F_RECV_AND_CLOSE; + return; + } +#if MG_ENABLE_SSL + if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) { + mg_ssl_if_conn_close_notify(conn); + } +#endif + /* + * Clearly mark the connection as going away (if not already). + * Some net_if impls (LwIP) need this for cleanly handling half-dead conns. + */ + conn->flags |= MG_F_CLOSE_IMMEDIATELY; + mg_remove_conn(conn); + conn->iface->vtable->destroy_conn(conn); + mg_call(conn, NULL, conn->user_data, MG_EV_CLOSE, NULL); + mg_destroy_conn(conn, 0 /* destroy_if */); +} + +void mg_mgr_init(struct mg_mgr *m, void *user_data) { + struct mg_mgr_init_opts opts; + memset(&opts, 0, sizeof(opts)); + mg_mgr_init_opt(m, user_data, opts); +} + +void mg_mgr_init_opt(struct mg_mgr *m, void *user_data, + struct mg_mgr_init_opts opts) { + memset(m, 0, sizeof(*m)); +#if MG_ENABLE_BROADCAST + m->ctl[0] = m->ctl[1] = INVALID_SOCKET; +#endif + m->user_data = user_data; + +#ifdef _WIN32 + { + WSADATA data; + WSAStartup(MAKEWORD(2, 2), &data); + } +#elif defined(__unix__) + /* Ignore SIGPIPE signal, so if client cancels the request, it + * won't kill the whole process. */ + signal(SIGPIPE, SIG_IGN); +#endif + + { + int i; + if (opts.num_ifaces == 0) { + opts.num_ifaces = mg_num_ifaces; + opts.ifaces = mg_ifaces; + } + if (opts.main_iface != NULL) { + opts.ifaces[MG_MAIN_IFACE] = opts.main_iface; + } + m->num_ifaces = opts.num_ifaces; + m->ifaces = + (struct mg_iface **) MG_MALLOC(sizeof(*m->ifaces) * opts.num_ifaces); + for (i = 0; i < opts.num_ifaces; i++) { + m->ifaces[i] = mg_if_create_iface(opts.ifaces[i], m); + m->ifaces[i]->vtable->init(m->ifaces[i]); + } + } + if (opts.nameserver != NULL) { + m->nameserver = strdup(opts.nameserver); + } + DBG(("==================================")); + DBG(("init mgr=%p", m)); +#if MG_ENABLE_SSL + { + static int init_done; + if (!init_done) { + mg_ssl_if_init(); + init_done++; + } + } +#endif +} + +void mg_mgr_free(struct mg_mgr *m) { + struct mg_connection *conn, *tmp_conn; + + DBG(("%p", m)); + if (m == NULL) return; + /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */ + mg_mgr_poll(m, 0); + +#if MG_ENABLE_BROADCAST + if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]); + if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]); + m->ctl[0] = m->ctl[1] = INVALID_SOCKET; +#endif + + for (conn = m->active_connections; conn != NULL; conn = tmp_conn) { + tmp_conn = conn->next; + conn->flags |= MG_F_CLOSE_IMMEDIATELY; + mg_close_conn(conn); + } + + { + int i; + for (i = 0; i < m->num_ifaces; i++) { + m->ifaces[i]->vtable->free(m->ifaces[i]); + MG_FREE(m->ifaces[i]); + } + MG_FREE(m->ifaces); + } + + MG_FREE((char *) m->nameserver); +} + +int mg_mgr_poll(struct mg_mgr *m, int timeout_ms) { + int i, num_calls_before = m->num_calls; + + for (i = 0; i < m->num_ifaces; i++) { + m->ifaces[i]->vtable->poll(m->ifaces[i], timeout_ms); + } + + return (m->num_calls - num_calls_before); +} + +int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) { + char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; + int len; + + if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) { + mg_send(nc, buf, len); + } + if (buf != mem && buf != NULL) { + MG_FREE(buf); /* LCOV_EXCL_LINE */ + } /* LCOV_EXCL_LINE */ + + return len; +} + +int mg_printf(struct mg_connection *conn, const char *fmt, ...) { + int len; + va_list ap; + va_start(ap, fmt); + len = mg_vprintf(conn, fmt, ap); + va_end(ap); + return len; +} + +#if MG_ENABLE_SYNC_RESOLVER +/* TODO(lsm): use non-blocking resolver */ +static int mg_resolve2(const char *host, struct in_addr *ina) { +#if MG_ENABLE_GETADDRINFO + int rv = 0; + struct addrinfo hints, *servinfo, *p; + struct sockaddr_in *h = NULL; + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) { + DBG(("getaddrinfo(%s) failed: %s", host, strerror(mg_get_errno()))); + return 0; + } + for (p = servinfo; p != NULL; p = p->ai_next) { + memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *)); + memcpy(ina, &h->sin_addr, sizeof(ina)); + } + freeaddrinfo(servinfo); + return 1; +#else + struct hostent *he; + if ((he = gethostbyname(host)) == NULL) { + DBG(("gethostbyname(%s) failed: %s", host, strerror(mg_get_errno()))); + } else { + memcpy(ina, he->h_addr_list[0], sizeof(*ina)); + return 1; + } + return 0; +#endif /* MG_ENABLE_GETADDRINFO */ +} + +int mg_resolve(const char *host, char *buf, size_t n) { + struct in_addr ad; + return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0; +} +#endif /* MG_ENABLE_SYNC_RESOLVER */ + +MG_INTERNAL struct mg_connection *mg_create_connection_base( + struct mg_mgr *mgr, mg_event_handler_t callback, + struct mg_add_sock_opts opts) { + struct mg_connection *conn; + + if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) { + conn->sock = INVALID_SOCKET; + conn->handler = callback; + conn->mgr = mgr; + conn->last_io_time = (time_t) mg_time(); + conn->iface = + (opts.iface != NULL ? opts.iface : mgr->ifaces[MG_MAIN_IFACE]); + conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK; + conn->user_data = opts.user_data; + /* + * SIZE_MAX is defined as a long long constant in + * system headers on some platforms and so it + * doesn't compile with pedantic ansi flags. + */ + conn->recv_mbuf_limit = ~0; + } else { + MG_SET_PTRPTR(opts.error_string, "failed to create connection"); + } + + return conn; +} + +MG_INTERNAL struct mg_connection *mg_create_connection( + struct mg_mgr *mgr, mg_event_handler_t callback, + struct mg_add_sock_opts opts) { + struct mg_connection *conn = mg_create_connection_base(mgr, callback, opts); + + if (conn != NULL && !conn->iface->vtable->create_conn(conn)) { + MG_FREE(conn); + conn = NULL; + } + if (conn == NULL) { + MG_SET_PTRPTR(opts.error_string, "failed to init connection"); + } + + return conn; +} + +/* + * Address format: [PROTO://][HOST]:PORT + * + * HOST could be IPv4/IPv6 address or a host name. + * `host` is a destination buffer to hold parsed HOST part. Should be at least + * MG_MAX_HOST_LEN bytes long. + * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM + * + * Return: + * -1 on parse error + * 0 if HOST needs DNS lookup + * >0 length of the address string + */ +MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa, + int *proto, char *host, size_t host_len) { + unsigned int a, b, c, d, port = 0; + int ch, len = 0; +#if MG_ENABLE_IPV6 + char buf[100]; +#endif + + /* + * MacOS needs that. If we do not zero it, subsequent bind() will fail. + * Also, all-zeroes in the socket address means binding to all addresses + * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). + */ + memset(sa, 0, sizeof(*sa)); + sa->sin.sin_family = AF_INET; + + *proto = SOCK_STREAM; + + if (strncmp(str, "udp://", 6) == 0) { + str += 6; + *proto = SOCK_DGRAM; + } else if (strncmp(str, "tcp://", 6) == 0) { + str += 6; + } + + if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) { + /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */ + sa->sin.sin_addr.s_addr = + htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d); + sa->sin.sin_port = htons((uint16_t) port); +#if MG_ENABLE_IPV6 + } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 && + inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) { + /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */ + sa->sin6.sin6_family = AF_INET6; + sa->sin.sin_port = htons((uint16_t) port); +#endif +#if MG_ENABLE_ASYNC_RESOLVER + } else if (strlen(str) < host_len && + sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) { + sa->sin.sin_port = htons((uint16_t) port); + if (mg_resolve_from_hosts_file(host, sa) != 0) { + /* + * if resolving from hosts file failed and the host + * we are trying to resolve is `localhost` - we should + * try to resolve it using `gethostbyname` and do not try + * to resolve it via DNS server if gethostbyname has failed too + */ + if (mg_ncasecmp(host, "localhost", 9) != 0) { + return 0; + } + +#if MG_ENABLE_SYNC_RESOLVER + if (!mg_resolve2(host, &sa->sin.sin_addr)) { + return -1; + } +#else + return -1; +#endif + } +#endif + } else if (sscanf(str, ":%u%n", &port, &len) == 1 || + sscanf(str, "%u%n", &port, &len) == 1) { + /* If only port is specified, bind to IPv4, INADDR_ANY */ + sa->sin.sin_port = htons((uint16_t) port); + } else { + return -1; + } + + /* Required for MG_ENABLE_ASYNC_RESOLVER=0 */ + (void) host; + (void) host_len; + + ch = str[len]; /* Character that follows the address */ + return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1; +} + +#if MG_ENABLE_SSL +MG_INTERNAL void mg_ssl_handshake(struct mg_connection *nc) { + int err = 0; + int server_side = (nc->listener != NULL); + enum mg_ssl_if_result res; + if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) return; + res = mg_ssl_if_handshake(nc); + + if (res == MG_SSL_OK) { + nc->flags |= MG_F_SSL_HANDSHAKE_DONE; + nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE); + if (server_side) { + mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa); + } else { + mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err); + } + } else if (res == MG_SSL_WANT_READ) { + nc->flags |= MG_F_WANT_READ; + } else if (res == MG_SSL_WANT_WRITE) { + nc->flags |= MG_F_WANT_WRITE; + } else { + if (!server_side) { + err = res; + mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err); + } + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } +} +#endif /* MG_ENABLE_SSL */ + +struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc) { + struct mg_add_sock_opts opts; + struct mg_connection *nc; + memset(&opts, 0, sizeof(opts)); + nc = mg_create_connection(lc->mgr, lc->handler, opts); + if (nc == NULL) return NULL; + nc->listener = lc; + nc->proto_handler = lc->proto_handler; + nc->user_data = lc->user_data; + nc->recv_mbuf_limit = lc->recv_mbuf_limit; + nc->iface = lc->iface; + if (lc->flags & MG_F_SSL) nc->flags |= MG_F_SSL; + mg_add_conn(nc->mgr, nc); + LOG(LL_DEBUG, ("%p %p %d %d", lc, nc, nc->sock, (int) nc->flags)); + return nc; +} + +void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa, + size_t sa_len) { + LOG(LL_DEBUG, ("%p %s://%s:%hu", nc, (nc->flags & MG_F_UDP ? "udp" : "tcp"), + inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port))); + nc->sa = *sa; +#if MG_ENABLE_SSL + if (nc->listener->flags & MG_F_SSL) { + nc->flags |= MG_F_SSL; + if (mg_ssl_if_conn_accept(nc, nc->listener) == MG_SSL_OK) { + mg_ssl_handshake(nc); + } else { + mg_close_conn(nc); + } + } else +#endif + { + mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa); + } + (void) sa_len; +} + +void mg_send(struct mg_connection *nc, const void *buf, int len) { + nc->last_io_time = (time_t) mg_time(); + mbuf_append(&nc->send_mbuf, buf, len); +} + +static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len); +static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len); + +static int mg_do_recv(struct mg_connection *nc) { + int res = 0; + char *buf = NULL; + size_t len = (nc->flags & MG_F_UDP ? MG_UDP_IO_SIZE : MG_TCP_IO_SIZE); + if ((nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_CONNECTING)) || + ((nc->flags & MG_F_LISTENING) && !(nc->flags & MG_F_UDP))) { + return -1; + } + do { + len = recv_avail_size(nc, len); + if (len == 0) { + res = -2; + break; + } + if (nc->recv_mbuf.size < nc->recv_mbuf.len + len) { + mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.len + len); + } + buf = nc->recv_mbuf.buf + nc->recv_mbuf.len; + len = nc->recv_mbuf.size - nc->recv_mbuf.len; + if (nc->flags & MG_F_UDP) { + res = mg_recv_udp(nc, buf, len); + } else { + res = mg_recv_tcp(nc, buf, len); + } + } while (res > 0 && !(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_UDP))); + return res; +} + +void mg_if_can_recv_cb(struct mg_connection *nc) { + mg_do_recv(nc); +} + +static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len) { + int n = 0; +#if MG_ENABLE_SSL + if (nc->flags & MG_F_SSL) { + if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) { + n = mg_ssl_if_read(nc, buf, len); + DBG(("%p <- %d bytes (SSL)", nc, n)); + if (n < 0) { + if (n == MG_SSL_WANT_READ) { + nc->flags |= MG_F_WANT_READ; + n = 0; + } else { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } + } else if (n > 0) { + nc->flags &= ~MG_F_WANT_READ; + } + } else { + mg_ssl_handshake(nc); + } + } else +#endif + { + n = nc->iface->vtable->tcp_recv(nc, buf, len); + DBG(("%p <- %d bytes", nc, n)); + } + if (n > 0) { + nc->recv_mbuf.len += n; + nc->last_io_time = (time_t) mg_time(); +#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP + if (nc->mgr && nc->mgr->hexdump_file != NULL) { + mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV); + } +#endif + mbuf_trim(&nc->recv_mbuf); + mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n); + } else if (n < 0) { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } + mbuf_trim(&nc->recv_mbuf); + return n; +} + +static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len) { + int n = 0; + struct mg_connection *lc = nc; + union socket_address sa; + size_t sa_len = sizeof(sa); + n = nc->iface->vtable->udp_recv(lc, buf, len, &sa, &sa_len); + if (n < 0) { + lc->flags |= MG_F_CLOSE_IMMEDIATELY; + goto out; + } + if (nc->flags & MG_F_LISTENING) { + /* + * Do we have an existing connection for this source? + * This is very inefficient for long connection lists. + */ + lc = nc; + for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) { + if (memcmp(&nc->sa.sa, &sa.sa, sa_len) == 0 && nc->listener == lc) { + break; + } + } + if (nc == NULL) { + struct mg_add_sock_opts opts; + memset(&opts, 0, sizeof(opts)); + /* Create fake connection w/out sock initialization */ + nc = mg_create_connection_base(lc->mgr, lc->handler, opts); + if (nc != NULL) { + nc->sock = lc->sock; + nc->listener = lc; + nc->sa = sa; + nc->proto_handler = lc->proto_handler; + nc->user_data = lc->user_data; + nc->recv_mbuf_limit = lc->recv_mbuf_limit; + nc->flags = MG_F_UDP; + /* + * Long-lived UDP "connections" i.e. interactions that involve more + * than one request and response are rare, most are transactional: + * response is sent and the "connection" is closed. Or - should be. + * But users (including ourselves) tend to forget about that part, + * because UDP is connectionless and one does not think about + * processing a UDP request as handling a connection that needs to be + * closed. Thus, we begin with SEND_AND_CLOSE flag set, which should + * be a reasonable default for most use cases, but it is possible to + * turn it off the connection should be kept alive after processing. + */ + nc->flags |= MG_F_SEND_AND_CLOSE; + mg_add_conn(lc->mgr, nc); + mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa); + } + } + } + if (nc != NULL) { + DBG(("%p <- %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr), + ntohs(nc->sa.sin.sin_port))); + if (nc == lc) { + nc->recv_mbuf.len += n; + } else { + mbuf_append(&nc->recv_mbuf, buf, n); + } + mbuf_trim(&lc->recv_mbuf); + lc->last_io_time = nc->last_io_time = (time_t) mg_time(); +#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP + if (nc->mgr && nc->mgr->hexdump_file != NULL) { + mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV); + } +#endif + if (n != 0) { + mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n); + } + } + +out: + mbuf_free(&lc->recv_mbuf); + return n; +} + +void mg_if_can_send_cb(struct mg_connection *nc) { + int n = 0; + const char *buf = nc->send_mbuf.buf; + size_t len = nc->send_mbuf.len; + + if (nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_CONNECTING)) { + return; + } + if (!(nc->flags & MG_F_UDP)) { + if (nc->flags & MG_F_LISTENING) return; + if (len > MG_TCP_IO_SIZE) len = MG_TCP_IO_SIZE; + } +#if MG_ENABLE_SSL + if (nc->flags & MG_F_SSL) { + if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) { + if (len > 0) { + n = mg_ssl_if_write(nc, buf, len); + DBG(("%p -> %d bytes (SSL)", nc, n)); + } + if (n < 0) { + if (n == MG_SSL_WANT_WRITE) { + nc->flags |= MG_F_WANT_WRITE; + n = 0; + } else { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } + } else { + nc->flags &= ~MG_F_WANT_WRITE; + } + } else { + mg_ssl_handshake(nc); + } + } else +#endif + if (len > 0) { + if (nc->flags & MG_F_UDP) { + n = nc->iface->vtable->udp_send(nc, buf, len); + } else { + n = nc->iface->vtable->tcp_send(nc, buf, len); + } + DBG(("%p -> %d bytes", nc, n)); + } + +#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP + if (n > 0 && nc->mgr && nc->mgr->hexdump_file != NULL) { + mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_SEND); + } +#endif + if (n < 0) { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } else if (n > 0) { + nc->last_io_time = (time_t) mg_time(); + mbuf_remove(&nc->send_mbuf, n); + mbuf_trim(&nc->send_mbuf); + } + if (n != 0) mg_call(nc, NULL, nc->user_data, MG_EV_SEND, &n); +} + +/* + * Schedules an async connect for a resolved address and proto. + * Called from two places: `mg_connect_opt()` and from async resolver. + * When called from the async resolver, it must trigger `MG_EV_CONNECT` event + * with a failure flag to indicate connection failure. + */ +MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc, + int proto, + union socket_address *sa) { + LOG(LL_DEBUG, ("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp", + inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port))); + + nc->flags |= MG_F_CONNECTING; + if (proto == SOCK_DGRAM) { + nc->iface->vtable->connect_udp(nc); + } else { + nc->iface->vtable->connect_tcp(nc, sa); + } + mg_add_conn(nc->mgr, nc); + return nc; +} + +void mg_if_connect_cb(struct mg_connection *nc, int err) { + LOG(LL_DEBUG, + ("%p %s://%s:%hu -> %d", nc, (nc->flags & MG_F_UDP ? "udp" : "tcp"), + inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port), err)); + nc->flags &= ~MG_F_CONNECTING; + if (err != 0) { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } +#if MG_ENABLE_SSL + if (err == 0 && (nc->flags & MG_F_SSL)) { + mg_ssl_handshake(nc); + } else +#endif + { + mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err); + } +} + +#if MG_ENABLE_ASYNC_RESOLVER +/* + * Callback for the async resolver on mg_connect_opt() call. + * Main task of this function is to trigger MG_EV_CONNECT event with + * either failure (and dealloc the connection) + * or success (and proceed with connect() + */ +static void resolve_cb(struct mg_dns_message *msg, void *data, + enum mg_resolve_err e) { + struct mg_connection *nc = (struct mg_connection *) data; + int i; + int failure = -1; + + nc->flags &= ~MG_F_RESOLVING; + if (msg != NULL) { + /* + * Take the first DNS A answer and run... + */ + for (i = 0; i < msg->num_answers; i++) { + if (msg->answers[i].rtype == MG_DNS_A_RECORD) { + /* + * Async resolver guarantees that there is at least one answer. + * TODO(lsm): handle IPv6 answers too + */ + mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr, + 4); + mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM, + &nc->sa); + return; + } + } + } + + if (e == MG_RESOLVE_TIMEOUT) { + double now = mg_time(); + mg_call(nc, NULL, nc->user_data, MG_EV_TIMER, &now); + } + + /* + * If we get there was no MG_DNS_A_RECORD in the answer + */ + mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &failure); + mg_call(nc, NULL, nc->user_data, MG_EV_CLOSE, NULL); + mg_destroy_conn(nc, 1 /* destroy_if */); +} +#endif + +struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address, + MG_CB(mg_event_handler_t callback, + void *user_data)) { + struct mg_connect_opts opts; + memset(&opts, 0, sizeof(opts)); + return mg_connect_opt(mgr, address, MG_CB(callback, user_data), opts); +} + +struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address, + MG_CB(mg_event_handler_t callback, + void *user_data), + struct mg_connect_opts opts) { + struct mg_connection *nc = NULL; + int proto, rc; + struct mg_add_sock_opts add_sock_opts; + char host[MG_MAX_HOST_LEN]; + + MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts); + + if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) { + return NULL; + } + + if ((rc = mg_parse_address(address, &nc->sa, &proto, host, sizeof(host))) < + 0) { + /* Address is malformed */ + MG_SET_PTRPTR(opts.error_string, "cannot parse address"); + mg_destroy_conn(nc, 1 /* destroy_if */); + return NULL; + } + + nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK; + nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0; +#if MG_ENABLE_CALLBACK_USERDATA + nc->user_data = user_data; +#else + nc->user_data = opts.user_data; +#endif + +#if MG_ENABLE_SSL + LOG(LL_DEBUG, + ("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"), + (opts.ssl_key ? opts.ssl_key : "-"), + (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-"))); + + if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL || + opts.ssl_psk_identity != NULL) { + const char *err_msg = NULL; + struct mg_ssl_if_conn_params params; + if (nc->flags & MG_F_UDP) { + MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported"); + mg_destroy_conn(nc, 1 /* destroy_if */); + return NULL; + } + memset(¶ms, 0, sizeof(params)); + params.cert = opts.ssl_cert; + params.key = opts.ssl_key; + params.ca_cert = opts.ssl_ca_cert; + params.cipher_suites = opts.ssl_cipher_suites; + params.psk_identity = opts.ssl_psk_identity; + params.psk_key = opts.ssl_psk_key; + if (opts.ssl_ca_cert != NULL) { + if (opts.ssl_server_name != NULL) { + if (strcmp(opts.ssl_server_name, "*") != 0) { + params.server_name = opts.ssl_server_name; + } + } else if (rc == 0) { /* If it's a DNS name, use host. */ + params.server_name = host; + } + } + if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) { + MG_SET_PTRPTR(opts.error_string, err_msg); + mg_destroy_conn(nc, 1 /* destroy_if */); + return NULL; + } + nc->flags |= MG_F_SSL; + } +#endif /* MG_ENABLE_SSL */ + + if (rc == 0) { +#if MG_ENABLE_ASYNC_RESOLVER + /* + * DNS resolution is required for host. + * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb() + */ + struct mg_connection *dns_conn = NULL; + struct mg_resolve_async_opts o; + memset(&o, 0, sizeof(o)); + o.dns_conn = &dns_conn; + o.nameserver = opts.nameserver; + if (mg_resolve_async_opt(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc, + o) != 0) { + MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup"); + mg_destroy_conn(nc, 1 /* destroy_if */); + return NULL; + } + nc->priv_2 = dns_conn; + nc->flags |= MG_F_RESOLVING; + return nc; +#else + MG_SET_PTRPTR(opts.error_string, "Resolver is disabled"); + mg_destroy_conn(nc, 1 /* destroy_if */); + return NULL; +#endif + } else { + /* Address is parsed and resolved to IP. proceed with connect() */ + return mg_do_connect(nc, proto, &nc->sa); + } +} + +struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address, + MG_CB(mg_event_handler_t event_handler, + void *user_data)) { + struct mg_bind_opts opts; + memset(&opts, 0, sizeof(opts)); + return mg_bind_opt(srv, address, MG_CB(event_handler, user_data), opts); +} + +struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address, + MG_CB(mg_event_handler_t callback, + void *user_data), + struct mg_bind_opts opts) { + union socket_address sa; + struct mg_connection *nc = NULL; + int proto, rc; + struct mg_add_sock_opts add_sock_opts; + char host[MG_MAX_HOST_LEN]; + +#if MG_ENABLE_CALLBACK_USERDATA + opts.user_data = user_data; +#endif + + if (callback == NULL) { + MG_SET_PTRPTR(opts.error_string, "handler is required"); + return NULL; + } + + MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts); + + if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) { + MG_SET_PTRPTR(opts.error_string, "cannot parse address"); + return NULL; + } + + nc = mg_create_connection(mgr, callback, add_sock_opts); + if (nc == NULL) { + return NULL; + } + + nc->sa = sa; + nc->flags |= MG_F_LISTENING; + if (proto == SOCK_DGRAM) nc->flags |= MG_F_UDP; + +#if MG_ENABLE_SSL + DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"), + (opts.ssl_key ? opts.ssl_key : "-"), + (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-"))); + + if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) { + const char *err_msg = NULL; + struct mg_ssl_if_conn_params params; + if (nc->flags & MG_F_UDP) { + MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported"); + mg_destroy_conn(nc, 1 /* destroy_if */); + return NULL; + } + memset(¶ms, 0, sizeof(params)); + params.cert = opts.ssl_cert; + params.key = opts.ssl_key; + params.ca_cert = opts.ssl_ca_cert; + params.cipher_suites = opts.ssl_cipher_suites; + if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) { + MG_SET_PTRPTR(opts.error_string, err_msg); + mg_destroy_conn(nc, 1 /* destroy_if */); + return NULL; + } + nc->flags |= MG_F_SSL; + } +#endif /* MG_ENABLE_SSL */ + + if (nc->flags & MG_F_UDP) { + rc = nc->iface->vtable->listen_udp(nc, &nc->sa); + } else { + rc = nc->iface->vtable->listen_tcp(nc, &nc->sa); + } + if (rc != 0) { + DBG(("Failed to open listener: %d", rc)); + MG_SET_PTRPTR(opts.error_string, "failed to open listener"); + mg_destroy_conn(nc, 1 /* destroy_if */); + return NULL; + } + mg_add_conn(nc->mgr, nc); + + return nc; +} + +struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) { + return conn == NULL ? s->active_connections : conn->next; +} + +#if MG_ENABLE_BROADCAST +void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data, + size_t len) { + struct ctl_msg ctl_msg; + + /* + * Mongoose manager has a socketpair, `struct mg_mgr::ctl`, + * where `mg_broadcast()` pushes the message. + * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls + * specified callback for each connection. Thus the callback function executes + * in event manager thread. + */ + if (mgr->ctl[0] != INVALID_SOCKET && data != NULL && + len < sizeof(ctl_msg.message)) { + size_t dummy; + + ctl_msg.callback = cb; + memcpy(ctl_msg.message, data, len); + dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg, + offsetof(struct ctl_msg, message) + len, 0); + dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0); + (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */ + } +} +#endif /* MG_ENABLE_BROADCAST */ + +static int isbyte(int n) { + return n >= 0 && n <= 255; +} + +static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) { + int n, a, b, c, d, slash = 32, len = 0; + + if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 || + sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && + isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 && + slash < 33) { + len = n; + *net = + ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d; + *mask = slash ? 0xffffffffU << (32 - slash) : 0; + } + + return len; +} + +int mg_check_ip_acl(const char *acl, uint32_t remote_ip) { + int allowed, flag; + uint32_t net, mask; + struct mg_str vec; + + /* If any ACL is set, deny by default */ + allowed = (acl == NULL || *acl == '\0') ? '+' : '-'; + + while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) { + flag = vec.p[0]; + if ((flag != '+' && flag != '-') || + parse_net(&vec.p[1], &net, &mask) == 0) { + return -1; + } + + if (net == (remote_ip & mask)) { + allowed = flag; + } + } + + DBG(("%08x %c", (unsigned int) remote_ip, allowed)); + return allowed == '+'; +} + +/* Move data from one connection to another */ +void mg_forward(struct mg_connection *from, struct mg_connection *to) { + mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len); + mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len); +} + +double mg_set_timer(struct mg_connection *c, double timestamp) { + double result = c->ev_timer_time; + c->ev_timer_time = timestamp; + /* + * If this connection is resolving, it's not in the list of active + * connections, so not processed yet. It has a DNS resolver connection + * linked to it. Set up a timer for the DNS connection. + */ + DBG(("%p %p %d -> %lu", c, c->priv_2, (c->flags & MG_F_RESOLVING ? 1 : 0), + (unsigned long) timestamp)); + if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) { + mg_set_timer((struct mg_connection *) c->priv_2, timestamp); + } + return result; +} + +void mg_sock_set(struct mg_connection *nc, sock_t sock) { + if (sock != INVALID_SOCKET) { + nc->iface->vtable->sock_set(nc, sock); + } +} + +void mg_if_get_conn_addr(struct mg_connection *nc, int remote, + union socket_address *sa) { + nc->iface->vtable->get_conn_addr(nc, remote, sa); +} + +struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock, + MG_CB(mg_event_handler_t callback, + void *user_data), + struct mg_add_sock_opts opts) { +#if MG_ENABLE_CALLBACK_USERDATA + opts.user_data = user_data; +#endif + + struct mg_connection *nc = mg_create_connection_base(s, callback, opts); + if (nc != NULL) { + mg_sock_set(nc, sock); + mg_add_conn(nc->mgr, nc); + } + return nc; +} + +struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock, + MG_CB(mg_event_handler_t callback, + void *user_data)) { + struct mg_add_sock_opts opts; + memset(&opts, 0, sizeof(opts)); + return mg_add_sock_opt(s, sock, MG_CB(callback, user_data), opts); +} + +double mg_time(void) { + return cs_time(); +} +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_net_if_socket.h" +#endif +/* + * Copyright (c) 2014-2016 Cesanta Software Limited + * All rights reserved + */ + +#ifndef CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ +#define CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ + +/* Amalgamated: #include "mg_net_if.h" */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef MG_ENABLE_NET_IF_SOCKET +#define MG_ENABLE_NET_IF_SOCKET MG_NET_IF == MG_NET_IF_SOCKET +#endif + +extern const struct mg_iface_vtable mg_socket_iface_vtable; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_net_if_socks.h" +#endif +/* +* Copyright (c) 2014-2017 Cesanta Software Limited +* All rights reserved +*/ + +#ifndef CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ +#define CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ + +#if MG_ENABLE_SOCKS +/* Amalgamated: #include "mg_net_if.h" */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +extern const struct mg_iface_vtable mg_socks_iface_vtable; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* MG_ENABLE_SOCKS */ +#endif /* CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_net_if.c" +#endif +/* Amalgamated: #include "mg_net_if.h" */ +/* Amalgamated: #include "mg_internal.h" */ +/* Amalgamated: #include "mg_net_if_socket.h" */ + +extern const struct mg_iface_vtable mg_default_iface_vtable; + +const struct mg_iface_vtable *mg_ifaces[] = { + &mg_default_iface_vtable, +}; + +int mg_num_ifaces = (int) (sizeof(mg_ifaces) / sizeof(mg_ifaces[0])); + +struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable, + struct mg_mgr *mgr) { + struct mg_iface *iface = (struct mg_iface *) MG_CALLOC(1, sizeof(*iface)); + iface->mgr = mgr; + iface->data = NULL; + iface->vtable = vtable; + return iface; +} + +struct mg_iface *mg_find_iface(struct mg_mgr *mgr, + const struct mg_iface_vtable *vtable, + struct mg_iface *from) { + int i = 0; + if (from != NULL) { + for (i = 0; i < mgr->num_ifaces; i++) { + if (mgr->ifaces[i] == from) { + i++; + break; + } + } + } + + for (; i < mgr->num_ifaces; i++) { + if (mgr->ifaces[i]->vtable == vtable) { + return mgr->ifaces[i]; + } + } + return NULL; +} + +double mg_mgr_min_timer(const struct mg_mgr *mgr) { + double min_timer = 0; + struct mg_connection *nc; + for (nc = mgr->active_connections; nc != NULL; nc = nc->next) { + if (nc->ev_timer_time <= 0) continue; + if (min_timer == 0 || nc->ev_timer_time < min_timer) { + min_timer = nc->ev_timer_time; + } + } + return min_timer; +} +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_net_if_null.c" +#endif +/* + * Copyright (c) 2018 Cesanta Software Limited + * All rights reserved + * + * This software is dual-licensed: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. For the terms of this + * license, see . + * + * You are free to use this software under the terms of the GNU General + * Public License, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * Alternatively, you can license this software under a commercial + * license, as set out in . + */ + +static void mg_null_if_connect_tcp(struct mg_connection *c, + const union socket_address *sa) { + c->flags |= MG_F_CLOSE_IMMEDIATELY; + (void) sa; +} + +static void mg_null_if_connect_udp(struct mg_connection *c) { + c->flags |= MG_F_CLOSE_IMMEDIATELY; +} + +static int mg_null_if_listen_tcp(struct mg_connection *c, + union socket_address *sa) { + (void) c; + (void) sa; + return -1; +} + +static int mg_null_if_listen_udp(struct mg_connection *c, + union socket_address *sa) { + (void) c; + (void) sa; + return -1; +} + +static int mg_null_if_tcp_send(struct mg_connection *c, const void *buf, + size_t len) { + (void) c; + (void) buf; + (void) len; + return -1; +} + +static int mg_null_if_udp_send(struct mg_connection *c, const void *buf, + size_t len) { + (void) c; + (void) buf; + (void) len; + return -1; +} + +int mg_null_if_tcp_recv(struct mg_connection *c, void *buf, size_t len) { + (void) c; + (void) buf; + (void) len; + return -1; +} + +int mg_null_if_udp_recv(struct mg_connection *c, void *buf, size_t len, + union socket_address *sa, size_t *sa_len) { + (void) c; + (void) buf; + (void) len; + (void) sa; + (void) sa_len; + return -1; +} + +static int mg_null_if_create_conn(struct mg_connection *c) { + (void) c; + return 1; +} + +static void mg_null_if_destroy_conn(struct mg_connection *c) { + (void) c; +} + +static void mg_null_if_sock_set(struct mg_connection *c, sock_t sock) { + (void) c; + (void) sock; +} + +static void mg_null_if_init(struct mg_iface *iface) { + (void) iface; +} + +static void mg_null_if_free(struct mg_iface *iface) { + (void) iface; +} + +static void mg_null_if_add_conn(struct mg_connection *c) { + c->sock = INVALID_SOCKET; + c->flags |= MG_F_CLOSE_IMMEDIATELY; +} + +static void mg_null_if_remove_conn(struct mg_connection *c) { + (void) c; +} + +static time_t mg_null_if_poll(struct mg_iface *iface, int timeout_ms) { + struct mg_mgr *mgr = iface->mgr; + struct mg_connection *nc, *tmp; + double now = mg_time(); + /* We basically just run timers and poll. */ + for (nc = mgr->active_connections; nc != NULL; nc = tmp) { + tmp = nc->next; + mg_if_poll(nc, now); + } + (void) timeout_ms; + return (time_t) now; +} + +static void mg_null_if_get_conn_addr(struct mg_connection *c, int remote, + union socket_address *sa) { + (void) c; + (void) remote; + (void) sa; +} + +#define MG_NULL_IFACE_VTABLE \ + { \ + mg_null_if_init, mg_null_if_free, mg_null_if_add_conn, \ + mg_null_if_remove_conn, mg_null_if_poll, mg_null_if_listen_tcp, \ + mg_null_if_listen_udp, mg_null_if_connect_tcp, mg_null_if_connect_udp, \ + mg_null_if_tcp_send, mg_null_if_udp_send, mg_null_if_tcp_recv, \ + mg_null_if_udp_recv, mg_null_if_create_conn, mg_null_if_destroy_conn, \ + mg_null_if_sock_set, mg_null_if_get_conn_addr, \ + } + +const struct mg_iface_vtable mg_null_iface_vtable = MG_NULL_IFACE_VTABLE; + +#if MG_NET_IF == MG_NET_IF_NULL +const struct mg_iface_vtable mg_default_iface_vtable = MG_NULL_IFACE_VTABLE; +#endif /* MG_NET_IF == MG_NET_IF_NULL */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_net_if_socket.c" +#endif +/* + * Copyright (c) 2014-2016 Cesanta Software Limited + * All rights reserved + */ + +#if MG_ENABLE_NET_IF_SOCKET + +/* Amalgamated: #include "mg_net_if_socket.h" */ +/* Amalgamated: #include "mg_internal.h" */ +/* Amalgamated: #include "mg_util.h" */ + +static sock_t mg_open_listening_socket(union socket_address *sa, int type, + int proto); + +void mg_set_non_blocking_mode(sock_t sock) { +#ifdef _WIN32 + unsigned long on = 1; + ioctlsocket(sock, FIONBIO, &on); +#else + int flags = fcntl(sock, F_GETFL, 0); + fcntl(sock, F_SETFL, flags | O_NONBLOCK); +#endif +} + +static int mg_is_error(void) { + int err = mg_get_errno(); + return err != EINPROGRESS && err != EWOULDBLOCK +#ifndef WINCE + && err != EAGAIN && err != EINTR +#endif +#ifdef _WIN32 + && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK +#endif + ; +} + +void mg_socket_if_connect_tcp(struct mg_connection *nc, + const union socket_address *sa) { + int rc, proto = 0; + nc->sock = socket(AF_INET, SOCK_STREAM, proto); + if (nc->sock == INVALID_SOCKET) { + nc->err = mg_get_errno() ? mg_get_errno() : 1; + return; + } +#if !defined(MG_ESP8266) + mg_set_non_blocking_mode(nc->sock); +#endif + rc = connect(nc->sock, &sa->sa, sizeof(sa->sin)); + nc->err = rc < 0 && mg_is_error() ? mg_get_errno() : 0; + DBG(("%p sock %d rc %d errno %d err %d", nc, nc->sock, rc, mg_get_errno(), + nc->err)); +} + +void mg_socket_if_connect_udp(struct mg_connection *nc) { + nc->sock = socket(AF_INET, SOCK_DGRAM, 0); + if (nc->sock == INVALID_SOCKET) { + nc->err = mg_get_errno() ? mg_get_errno() : 1; + return; + } + if (nc->flags & MG_F_ENABLE_BROADCAST) { + int optval = 1; + if (setsockopt(nc->sock, SOL_SOCKET, SO_BROADCAST, (const char *) &optval, + sizeof(optval)) < 0) { + nc->err = mg_get_errno() ? mg_get_errno() : 1; + return; + } + } + nc->err = 0; +} + +int mg_socket_if_listen_tcp(struct mg_connection *nc, + union socket_address *sa) { + int proto = 0; + sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto); + if (sock == INVALID_SOCKET) { + return (mg_get_errno() ? mg_get_errno() : 1); + } + mg_sock_set(nc, sock); + return 0; +} + +static int mg_socket_if_listen_udp(struct mg_connection *nc, + union socket_address *sa) { + sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0); + if (sock == INVALID_SOCKET) return (mg_get_errno() ? mg_get_errno() : 1); + mg_sock_set(nc, sock); + return 0; +} + +static int mg_socket_if_tcp_send(struct mg_connection *nc, const void *buf, + size_t len) { + int n = (int) MG_SEND_FUNC(nc->sock, buf, len, 0); + if (n < 0 && !mg_is_error()) n = 0; + return n; +} + +static int mg_socket_if_udp_send(struct mg_connection *nc, const void *buf, + size_t len) { + int n = sendto(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin)); + if (n < 0 && !mg_is_error()) n = 0; + return n; +} + +static int mg_socket_if_tcp_recv(struct mg_connection *nc, void *buf, + size_t len) { + int n = (int) MG_RECV_FUNC(nc->sock, buf, len, 0); + if (n == 0) { + /* Orderly shutdown of the socket, try flushing output. */ + nc->flags |= MG_F_SEND_AND_CLOSE; + } else if (n < 0 && !mg_is_error()) { + n = 0; + } + return n; +} + +static int mg_socket_if_udp_recv(struct mg_connection *nc, void *buf, + size_t len, union socket_address *sa, + size_t *sa_len) { + socklen_t sa_len_st = *sa_len; + int n = recvfrom(nc->sock, buf, len, 0, &sa->sa, &sa_len_st); + *sa_len = sa_len_st; + if (n < 0 && !mg_is_error()) n = 0; + return n; +} + +int mg_socket_if_create_conn(struct mg_connection *nc) { + (void) nc; + return 1; +} + +void mg_socket_if_destroy_conn(struct mg_connection *nc) { + if (nc->sock == INVALID_SOCKET) return; + if (!(nc->flags & MG_F_UDP)) { + closesocket(nc->sock); + } else { + /* Only close outgoing UDP sockets or listeners. */ + if (nc->listener == NULL) closesocket(nc->sock); + } + nc->sock = INVALID_SOCKET; +} + +static int mg_accept_conn(struct mg_connection *lc) { + struct mg_connection *nc; + union socket_address sa; + socklen_t sa_len = sizeof(sa); + /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */ + sock_t sock = accept(lc->sock, &sa.sa, &sa_len); + if (sock == INVALID_SOCKET) { + if (mg_is_error()) { + DBG(("%p: failed to accept: %d", lc, mg_get_errno())); + } + return 0; + } + nc = mg_if_accept_new_conn(lc); + if (nc == NULL) { + closesocket(sock); + return 0; + } + DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr), + ntohs(sa.sin.sin_port))); + mg_sock_set(nc, sock); + mg_if_accept_tcp_cb(nc, &sa, sa_len); + return 1; +} + +/* 'sa' must be an initialized address to bind to */ +static sock_t mg_open_listening_socket(union socket_address *sa, int type, + int proto) { + socklen_t sa_len = + (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6); + sock_t sock = INVALID_SOCKET; +#if !MG_LWIP + int on = 1; +#endif + + if ((sock = socket(sa->sa.sa_family, type, proto)) != INVALID_SOCKET && +#if !MG_LWIP /* LWIP doesn't support either */ +#if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) && !defined(WINCE) + /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */ + !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on, + sizeof(on)) && +#endif + +#if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE) + /* + * SO_RESUSEADDR is not enabled on Windows because the semantics of + * SO_REUSEADDR on UNIX and Windows is different. On Windows, + * SO_REUSEADDR allows to bind a socket to a port without error even if + * the port is already open by another program. This is not the behavior + * SO_REUSEADDR was designed for, and leads to hard-to-track failure + * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless + * SO_EXCLUSIVEADDRUSE is supported and set on a socket. + */ + !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) && +#endif +#endif /* !MG_LWIP */ + + !bind(sock, &sa->sa, sa_len) && + (type == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) { +#if !MG_LWIP + mg_set_non_blocking_mode(sock); + /* In case port was set to 0, get the real port number */ + (void) getsockname(sock, &sa->sa, &sa_len); +#endif + } else if (sock != INVALID_SOCKET) { + closesocket(sock); + sock = INVALID_SOCKET; + } + + return sock; +} + +#define _MG_F_FD_CAN_READ 1 +#define _MG_F_FD_CAN_WRITE 1 << 1 +#define _MG_F_FD_ERROR 1 << 2 + +void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) { + int worth_logging = + fd_flags != 0 || (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE)); + if (worth_logging) { + DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, + fd_flags, nc->flags, (int) nc->recv_mbuf.len, + (int) nc->send_mbuf.len)); + } + + if (!mg_if_poll(nc, now)) return; + + if (nc->flags & MG_F_CONNECTING) { + if (fd_flags != 0) { + int err = 0; +#if !defined(MG_ESP8266) + if (!(nc->flags & MG_F_UDP)) { + socklen_t len = sizeof(err); + int ret = + getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len); + if (ret != 0) { + err = 1; + } else if (err == EAGAIN || err == EWOULDBLOCK) { + err = 0; + } + } +#else + /* + * On ESP8266 we use blocking connect. + */ + err = nc->err; +#endif + mg_if_connect_cb(nc, err); + } else if (nc->err != 0) { + mg_if_connect_cb(nc, nc->err); + } + } + + if (fd_flags & _MG_F_FD_CAN_READ) { + if (nc->flags & MG_F_UDP) { + mg_if_can_recv_cb(nc); + } else { + if (nc->flags & MG_F_LISTENING) { + /* + * We're not looping here, and accepting just one connection at + * a time. The reason is that eCos does not respect non-blocking + * flag on a listening socket and hangs in a loop. + */ + mg_accept_conn(nc); + } else { + mg_if_can_recv_cb(nc); + } + } + } + + if (fd_flags & _MG_F_FD_CAN_WRITE) mg_if_can_send_cb(nc); + + if (worth_logging) { + DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, + nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); + } +} + +#if MG_ENABLE_BROADCAST +static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) { + struct ctl_msg ctl_msg; + int len = + (int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0); + size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0); + DBG(("read %d from ctl socket", len)); + (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */ + if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) { + struct mg_connection *nc; + for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { + ctl_msg.callback(nc, MG_EV_POLL, + ctl_msg.message MG_UD_ARG(nc->user_data)); + } + } +} +#endif + +/* Associate a socket to a connection. */ +void mg_socket_if_sock_set(struct mg_connection *nc, sock_t sock) { + mg_set_non_blocking_mode(sock); + mg_set_close_on_exec(sock); + nc->sock = sock; + DBG(("%p %d", nc, sock)); +} + +void mg_socket_if_init(struct mg_iface *iface) { + (void) iface; + DBG(("%p using select()", iface->mgr)); +#if MG_ENABLE_BROADCAST + mg_socketpair(iface->mgr->ctl, SOCK_DGRAM); +#endif +} + +void mg_socket_if_free(struct mg_iface *iface) { + (void) iface; +} + +void mg_socket_if_add_conn(struct mg_connection *nc) { + (void) nc; +} + +void mg_socket_if_remove_conn(struct mg_connection *nc) { + (void) nc; +} + +void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) { + if (sock != INVALID_SOCKET +#ifdef __unix__ + && sock < (sock_t) FD_SETSIZE +#endif + ) { + FD_SET(sock, set); + if (*max_fd == INVALID_SOCKET || sock > *max_fd) { + *max_fd = sock; + } + } +} + +time_t mg_socket_if_poll(struct mg_iface *iface, int timeout_ms) { + struct mg_mgr *mgr = iface->mgr; + double now = mg_time(); + double min_timer; + struct mg_connection *nc, *tmp; + struct timeval tv; + fd_set read_set, write_set, err_set; + sock_t max_fd = INVALID_SOCKET; + int num_fds, num_ev, num_timers = 0; +#ifdef __unix__ + int try_dup = 1; +#endif + + FD_ZERO(&read_set); + FD_ZERO(&write_set); + FD_ZERO(&err_set); +#if MG_ENABLE_BROADCAST + mg_add_to_set(mgr->ctl[1], &read_set, &max_fd); +#endif + + /* + * Note: it is ok to have connections with sock == INVALID_SOCKET in the list, + * e.g. timer-only "connections". + */ + min_timer = 0; + for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) { + tmp = nc->next; + + if (nc->sock != INVALID_SOCKET) { + num_fds++; + +#ifdef __unix__ + /* A hack to make sure all our file descriptos fit into FD_SETSIZE. */ + if (nc->sock >= (sock_t) FD_SETSIZE && try_dup) { + int new_sock = dup(nc->sock); + if (new_sock >= 0) { + if (new_sock < (sock_t) FD_SETSIZE) { + closesocket(nc->sock); + DBG(("new sock %d -> %d", nc->sock, new_sock)); + nc->sock = new_sock; + } else { + closesocket(new_sock); + DBG(("new sock is still larger than FD_SETSIZE, disregard")); + try_dup = 0; + } + } else { + try_dup = 0; + } + } +#endif + + if (nc->recv_mbuf.len < nc->recv_mbuf_limit && + (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) { + mg_add_to_set(nc->sock, &read_set, &max_fd); + } + + if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) || + (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) { + mg_add_to_set(nc->sock, &write_set, &max_fd); + mg_add_to_set(nc->sock, &err_set, &max_fd); + } + } + + if (nc->ev_timer_time > 0) { + if (num_timers == 0 || nc->ev_timer_time < min_timer) { + min_timer = nc->ev_timer_time; + } + num_timers++; + } + } + + /* + * If there is a timer to be fired earlier than the requested timeout, + * adjust the timeout. + */ + if (num_timers > 0) { + double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */; + if (timer_timeout_ms < timeout_ms) { + timeout_ms = (int) timer_timeout_ms; + } + } + if (timeout_ms < 0) timeout_ms = 0; + + tv.tv_sec = timeout_ms / 1000; + tv.tv_usec = (timeout_ms % 1000) * 1000; + + num_ev = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv); + now = mg_time(); +#if 0 + DBG(("select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds, + timeout_ms)); +#endif + +#if MG_ENABLE_BROADCAST + if (num_ev > 0 && mgr->ctl[1] != INVALID_SOCKET && + FD_ISSET(mgr->ctl[1], &read_set)) { + mg_mgr_handle_ctl_sock(mgr); + } +#endif + + for (nc = mgr->active_connections; nc != NULL; nc = tmp) { + int fd_flags = 0; + if (nc->sock != INVALID_SOCKET) { + if (num_ev > 0) { + fd_flags = (FD_ISSET(nc->sock, &read_set) && + (!(nc->flags & MG_F_UDP) || nc->listener == NULL) + ? _MG_F_FD_CAN_READ + : 0) | + (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) | + (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0); + } +#if MG_LWIP + /* With LWIP socket emulation layer, we don't get write events for UDP */ + if ((nc->flags & MG_F_UDP) && nc->listener == NULL) { + fd_flags |= _MG_F_FD_CAN_WRITE; + } +#endif + } + tmp = nc->next; + mg_mgr_handle_conn(nc, fd_flags, now); + } + + return (time_t) now; +} + +#if MG_ENABLE_BROADCAST +MG_INTERNAL void mg_socketpair_close(sock_t *sock) { + while (1) { + if (closesocket(*sock) == -1 && errno == EINTR) continue; + break; + } + *sock = INVALID_SOCKET; +} + +MG_INTERNAL sock_t +mg_socketpair_accept(sock_t sock, union socket_address *sa, socklen_t sa_len) { + sock_t rc; + while (1) { + if ((rc = accept(sock, &sa->sa, &sa_len)) == INVALID_SOCKET && + errno == EINTR) + continue; + break; + } + return rc; +} + +int mg_socketpair(sock_t sp[2], int sock_type) { + union socket_address sa, sa2; + sock_t sock; + socklen_t len = sizeof(sa.sin); + int ret = 0; + + sock = sp[0] = sp[1] = INVALID_SOCKET; + + (void) memset(&sa, 0, sizeof(sa)); + sa.sin.sin_family = AF_INET; + sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */ + sa2 = sa; + + if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) { + } else if (bind(sock, &sa.sa, len) != 0) { + } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) { + } else if (getsockname(sock, &sa.sa, &len) != 0) { + } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) { + } else if (sock_type == SOCK_STREAM && connect(sp[0], &sa.sa, len) != 0) { + } else if (sock_type == SOCK_DGRAM && + (bind(sp[0], &sa2.sa, len) != 0 || + getsockname(sp[0], &sa2.sa, &len) != 0 || + connect(sp[0], &sa.sa, len) != 0 || + connect(sock, &sa2.sa, len) != 0)) { + } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock : mg_socketpair_accept( + sock, &sa, len))) == + INVALID_SOCKET) { + } else { + mg_set_close_on_exec(sp[0]); + mg_set_close_on_exec(sp[1]); + if (sock_type == SOCK_STREAM) mg_socketpair_close(&sock); + ret = 1; + } + + if (!ret) { + if (sp[0] != INVALID_SOCKET) mg_socketpair_close(&sp[0]); + if (sp[1] != INVALID_SOCKET) mg_socketpair_close(&sp[1]); + if (sock != INVALID_SOCKET) mg_socketpair_close(&sock); + } + + return ret; +} +#endif /* MG_ENABLE_BROADCAST */ + +static void mg_sock_get_addr(sock_t sock, int remote, + union socket_address *sa) { + socklen_t slen = sizeof(*sa); + memset(sa, 0, slen); + if (remote) { + getpeername(sock, &sa->sa, &slen); + } else { + getsockname(sock, &sa->sa, &slen); + } +} + +void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) { + union socket_address sa; + mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa); + mg_sock_addr_to_str(&sa, buf, len, flags); +} + +void mg_socket_if_get_conn_addr(struct mg_connection *nc, int remote, + union socket_address *sa) { + if ((nc->flags & MG_F_UDP) && remote) { + memcpy(sa, &nc->sa, sizeof(*sa)); + return; + } + mg_sock_get_addr(nc->sock, remote, sa); +} + +/* clang-format off */ +#define MG_SOCKET_IFACE_VTABLE \ + { \ + mg_socket_if_init, \ + mg_socket_if_free, \ + mg_socket_if_add_conn, \ + mg_socket_if_remove_conn, \ + mg_socket_if_poll, \ + mg_socket_if_listen_tcp, \ + mg_socket_if_listen_udp, \ + mg_socket_if_connect_tcp, \ + mg_socket_if_connect_udp, \ + mg_socket_if_tcp_send, \ + mg_socket_if_udp_send, \ + mg_socket_if_tcp_recv, \ + mg_socket_if_udp_recv, \ + mg_socket_if_create_conn, \ + mg_socket_if_destroy_conn, \ + mg_socket_if_sock_set, \ + mg_socket_if_get_conn_addr, \ + } +/* clang-format on */ + +const struct mg_iface_vtable mg_socket_iface_vtable = MG_SOCKET_IFACE_VTABLE; +#if MG_NET_IF == MG_NET_IF_SOCKET +const struct mg_iface_vtable mg_default_iface_vtable = MG_SOCKET_IFACE_VTABLE; +#endif + +#endif /* MG_ENABLE_NET_IF_SOCKET */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_net_if_socks.c" +#endif +/* + * Copyright (c) 2014-2016 Cesanta Software Limited + * All rights reserved + */ + +#if MG_ENABLE_SOCKS + +struct socksdata { + char *proxy_addr; /* HOST:PORT of the socks5 proxy server */ + struct mg_connection *s; /* Respective connection to the server */ + struct mg_connection *c; /* Connection to the client */ +}; + +static void socks_if_disband(struct socksdata *d) { + LOG(LL_DEBUG, ("disbanding proxy %p %p", d->c, d->s)); + if (d->c) { + d->c->flags |= MG_F_SEND_AND_CLOSE; + d->c->user_data = NULL; + d->c = NULL; + } + if (d->s) { + d->s->flags |= MG_F_SEND_AND_CLOSE; + d->s->user_data = NULL; + d->s = NULL; + } +} + +static void socks_if_relay(struct mg_connection *s) { + struct socksdata *d = (struct socksdata *) s->user_data; + if (d == NULL || d->c == NULL || !(s->flags & MG_SOCKS_CONNECT_DONE) || + d->s == NULL) { + return; + } + if (s->recv_mbuf.len > 0) mg_if_can_recv_cb(d->c); + if (d->c->send_mbuf.len > 0 && s->send_mbuf.len == 0) mg_if_can_send_cb(d->c); +} + +static void socks_if_handler(struct mg_connection *c, int ev, void *ev_data) { + struct socksdata *d = (struct socksdata *) c->user_data; + if (d == NULL) return; + if (ev == MG_EV_CONNECT) { + int res = *(int *) ev_data; + if (res == 0) { + /* Send handshake to the proxy server */ + unsigned char buf[] = {MG_SOCKS_VERSION, 1, MG_SOCKS_HANDSHAKE_NOAUTH}; + mg_send(d->s, buf, sizeof(buf)); + LOG(LL_DEBUG, ("Sent handshake to %s", d->proxy_addr)); + } else { + LOG(LL_ERROR, ("Cannot connect to %s: %d", d->proxy_addr, res)); + d->c->flags |= MG_F_CLOSE_IMMEDIATELY; + } + } else if (ev == MG_EV_CLOSE) { + socks_if_disband(d); + } else if (ev == MG_EV_RECV) { + /* Handle handshake reply */ + if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) { + /* TODO(lsm): process IPv6 too */ + unsigned char buf[10] = {MG_SOCKS_VERSION, MG_SOCKS_CMD_CONNECT, 0, + MG_SOCKS_ADDR_IPV4}; + if (c->recv_mbuf.len < 2) return; + if ((unsigned char) c->recv_mbuf.buf[1] == MG_SOCKS_HANDSHAKE_FAILURE) { + LOG(LL_ERROR, ("Server kicked us out")); + socks_if_disband(d); + return; + } + mbuf_remove(&c->recv_mbuf, 2); + c->flags |= MG_SOCKS_HANDSHAKE_DONE; + + /* Send connect request */ + memcpy(buf + 4, &d->c->sa.sin.sin_addr, 4); + memcpy(buf + 8, &d->c->sa.sin.sin_port, 2); + mg_send(c, buf, sizeof(buf)); + LOG(LL_DEBUG, ("%p Sent connect request", c)); + } + /* Process connect request */ + if ((c->flags & MG_SOCKS_HANDSHAKE_DONE) && + !(c->flags & MG_SOCKS_CONNECT_DONE)) { + if (c->recv_mbuf.len < 10) return; + if (c->recv_mbuf.buf[1] != MG_SOCKS_SUCCESS) { + LOG(LL_ERROR, ("Socks connection error: %d", c->recv_mbuf.buf[1])); + socks_if_disband(d); + return; + } + mbuf_remove(&c->recv_mbuf, 10); + c->flags |= MG_SOCKS_CONNECT_DONE; + LOG(LL_DEBUG, ("%p Connect done %p", c, d->c)); + mg_if_connect_cb(d->c, 0); + } + socks_if_relay(c); + } else if (ev == MG_EV_SEND || ev == MG_EV_POLL) { + socks_if_relay(c); + } +} + +static void mg_socks_if_connect_tcp(struct mg_connection *c, + const union socket_address *sa) { + struct socksdata *d = (struct socksdata *) c->iface->data; + d->c = c; + d->s = mg_connect(c->mgr, d->proxy_addr, socks_if_handler); + d->s->user_data = d; + LOG(LL_DEBUG, ("%p %s %p %p", c, d->proxy_addr, d, d->s)); + (void) sa; +} + +static void mg_socks_if_connect_udp(struct mg_connection *c) { + (void) c; +} + +static int mg_socks_if_listen_tcp(struct mg_connection *c, + union socket_address *sa) { + (void) c; + (void) sa; + return 0; +} + +static int mg_socks_if_listen_udp(struct mg_connection *c, + union socket_address *sa) { + (void) c; + (void) sa; + return -1; +} + +static int mg_socks_if_tcp_send(struct mg_connection *c, const void *buf, + size_t len) { + int res; + struct socksdata *d = (struct socksdata *) c->iface->data; + if (d->s == NULL) return -1; + res = (int) mbuf_append(&d->s->send_mbuf, buf, len); + DBG(("%p -> %d -> %p", c, res, d->s)); + return res; +} + +static int mg_socks_if_udp_send(struct mg_connection *c, const void *buf, + size_t len) { + (void) c; + (void) buf; + (void) len; + return -1; +} + +int mg_socks_if_tcp_recv(struct mg_connection *c, void *buf, size_t len) { + struct socksdata *d = (struct socksdata *) c->iface->data; + if (d->s == NULL) return -1; + if (len > d->s->recv_mbuf.len) len = d->s->recv_mbuf.len; + if (len > 0) { + memcpy(buf, d->s->recv_mbuf.buf, len); + mbuf_remove(&d->s->recv_mbuf, len); + } + DBG(("%p <- %d <- %p", c, (int) len, d->s)); + return len; +} + +int mg_socks_if_udp_recv(struct mg_connection *c, void *buf, size_t len, + union socket_address *sa, size_t *sa_len) { + (void) c; + (void) buf; + (void) len; + (void) sa; + (void) sa_len; + return -1; +} + +static int mg_socks_if_create_conn(struct mg_connection *c) { + (void) c; + return 1; +} + +static void mg_socks_if_destroy_conn(struct mg_connection *c) { + c->iface->vtable->free(c->iface); + MG_FREE(c->iface); + c->iface = NULL; + LOG(LL_DEBUG, ("%p", c)); +} + +static void mg_socks_if_sock_set(struct mg_connection *c, sock_t sock) { + (void) c; + (void) sock; +} + +static void mg_socks_if_init(struct mg_iface *iface) { + (void) iface; +} + +static void mg_socks_if_free(struct mg_iface *iface) { + struct socksdata *d = (struct socksdata *) iface->data; + LOG(LL_DEBUG, ("%p", iface)); + if (d != NULL) { + socks_if_disband(d); + MG_FREE(d->proxy_addr); + MG_FREE(d); + iface->data = NULL; + } +} + +static void mg_socks_if_add_conn(struct mg_connection *c) { + c->sock = INVALID_SOCKET; +} + +static void mg_socks_if_remove_conn(struct mg_connection *c) { + (void) c; +} + +static time_t mg_socks_if_poll(struct mg_iface *iface, int timeout_ms) { + LOG(LL_DEBUG, ("%p", iface)); + (void) iface; + (void) timeout_ms; + return (time_t) cs_time(); +} + +static void mg_socks_if_get_conn_addr(struct mg_connection *c, int remote, + union socket_address *sa) { + LOG(LL_DEBUG, ("%p", c)); + (void) c; + (void) remote; + (void) sa; +} + +const struct mg_iface_vtable mg_socks_iface_vtable = { + mg_socks_if_init, mg_socks_if_free, + mg_socks_if_add_conn, mg_socks_if_remove_conn, + mg_socks_if_poll, mg_socks_if_listen_tcp, + mg_socks_if_listen_udp, mg_socks_if_connect_tcp, + mg_socks_if_connect_udp, mg_socks_if_tcp_send, + mg_socks_if_udp_send, mg_socks_if_tcp_recv, + mg_socks_if_udp_recv, mg_socks_if_create_conn, + mg_socks_if_destroy_conn, mg_socks_if_sock_set, + mg_socks_if_get_conn_addr, +}; + +struct mg_iface *mg_socks_mk_iface(struct mg_mgr *mgr, const char *proxy_addr) { + struct mg_iface *iface = mg_if_create_iface(&mg_socks_iface_vtable, mgr); + iface->data = MG_CALLOC(1, sizeof(struct socksdata)); + ((struct socksdata *) iface->data)->proxy_addr = strdup(proxy_addr); + return iface; +} + +#endif +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_ssl_if_openssl.c" +#endif +/* + * Copyright (c) 2014-2016 Cesanta Software Limited + * All rights reserved + */ + +#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL + +#ifdef __APPLE__ +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + +#include +#ifndef KR_VERSION +#include +#endif + +struct mg_ssl_if_ctx { + SSL *ssl; + SSL_CTX *ssl_ctx; + struct mbuf psk; + size_t identity_len; +}; + +void mg_ssl_if_init() { + SSL_library_init(); +} + +enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, + struct mg_connection *lc) { + struct mg_ssl_if_ctx *ctx = + (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); + struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data; + nc->ssl_if_data = ctx; + if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR; + ctx->ssl_ctx = lc_ctx->ssl_ctx; + if ((ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) { + return MG_SSL_ERROR; + } + return MG_SSL_OK; +} + +static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert, + const char *key, const char **err_msg); +static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert); +static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl); +static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx, + const char *identity, + const char *key_str); + +enum mg_ssl_if_result mg_ssl_if_conn_init( + struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, + const char **err_msg) { + struct mg_ssl_if_ctx *ctx = + (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); + DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""), + (params->key ? params->key : ""), + (params->ca_cert ? params->ca_cert : ""))); + if (ctx == NULL) { + MG_SET_PTRPTR(err_msg, "Out of memory"); + return MG_SSL_ERROR; + } + nc->ssl_if_data = ctx; + if (nc->flags & MG_F_LISTENING) { + ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method()); + } else { + ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()); + } + if (ctx->ssl_ctx == NULL) { + MG_SET_PTRPTR(err_msg, "Failed to create SSL context"); + return MG_SSL_ERROR; + } + +#ifndef KR_VERSION + /* Disable deprecated protocols. */ + SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2); + SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv3); + SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_TLSv1); +#ifdef MG_SSL_OPENSSL_NO_COMPRESSION + SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_COMPRESSION); +#endif +#ifdef MG_SSL_OPENSSL_CIPHER_SERVER_PREFERENCE + SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); +#endif +#else +/* Krypton only supports TLSv1.2 anyway. */ +#endif + + if (params->cert != NULL && + mg_use_cert(ctx->ssl_ctx, params->cert, params->key, err_msg) != + MG_SSL_OK) { + return MG_SSL_ERROR; + } + + if (params->ca_cert != NULL && + mg_use_ca_cert(ctx->ssl_ctx, params->ca_cert) != MG_SSL_OK) { + MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert"); + return MG_SSL_ERROR; + } + + if (mg_set_cipher_list(ctx->ssl_ctx, params->cipher_suites) != MG_SSL_OK) { + MG_SET_PTRPTR(err_msg, "Invalid cipher suite list"); + return MG_SSL_ERROR; + } + + mbuf_init(&ctx->psk, 0); + if (mg_ssl_if_ossl_set_psk(ctx, params->psk_identity, params->psk_key) != + MG_SSL_OK) { + MG_SET_PTRPTR(err_msg, "Invalid PSK settings"); + return MG_SSL_ERROR; + } + + if (!(nc->flags & MG_F_LISTENING) && + (ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) { + MG_SET_PTRPTR(err_msg, "Failed to create SSL session"); + return MG_SSL_ERROR; + } + + if (params->server_name != NULL) { +#ifdef KR_VERSION + SSL_CTX_kr_set_verify_name(ctx->ssl_ctx, params->server_name); +#else + SSL_set_tlsext_host_name(ctx->ssl, params->server_name); +#endif + } + + nc->flags |= MG_F_SSL; + + return MG_SSL_OK; +} + +static enum mg_ssl_if_result mg_ssl_if_ssl_err(struct mg_connection *nc, + int res) { + struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; + int err = SSL_get_error(ctx->ssl, res); + if (err == SSL_ERROR_WANT_READ) return MG_SSL_WANT_READ; + if (err == SSL_ERROR_WANT_WRITE) return MG_SSL_WANT_WRITE; + DBG(("%p %p SSL error: %d %d", nc, ctx->ssl_ctx, res, err)); + nc->err = err; + return MG_SSL_ERROR; +} + +enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) { + struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; + int server_side = (nc->listener != NULL); + int res; + /* If descriptor is not yet set, do it now. */ + if (SSL_get_fd(ctx->ssl) < 0) { + if (SSL_set_fd(ctx->ssl, nc->sock) != 1) return MG_SSL_ERROR; + } + res = server_side ? SSL_accept(ctx->ssl) : SSL_connect(ctx->ssl); + if (res != 1) return mg_ssl_if_ssl_err(nc, res); + return MG_SSL_OK; +} + +int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) { + struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; + int n = SSL_read(ctx->ssl, buf, buf_size); + DBG(("%p %d -> %d", nc, (int) buf_size, n)); + if (n < 0) return mg_ssl_if_ssl_err(nc, n); + if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY; + return n; +} + +int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) { + struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; + int n = SSL_write(ctx->ssl, data, len); + DBG(("%p %d -> %d", nc, (int) len, n)); + if (n <= 0) return mg_ssl_if_ssl_err(nc, n); + return n; +} + +void mg_ssl_if_conn_close_notify(struct mg_connection *nc) { + struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; + if (ctx == NULL) return; + SSL_shutdown(ctx->ssl); +} + +void mg_ssl_if_conn_free(struct mg_connection *nc) { + struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; + if (ctx == NULL) return; + nc->ssl_if_data = NULL; + if (ctx->ssl != NULL) SSL_free(ctx->ssl); + if (ctx->ssl_ctx != NULL && nc->listener == NULL) SSL_CTX_free(ctx->ssl_ctx); + mbuf_free(&ctx->psk); + memset(ctx, 0, sizeof(*ctx)); + MG_FREE(ctx); +} + +/* + * Cipher suite options used for TLS negotiation. + * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations + */ +static const char mg_s_cipher_list[] = +#if defined(MG_SSL_CRYPTO_MODERN) + "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:" + "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:" + "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" + "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" + "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" + "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" + "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" + "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:" + "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK" +#elif defined(MG_SSL_CRYPTO_OLD) + "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:" + "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:" + "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" + "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" + "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" + "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" + "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" + "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:" + "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:" + "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:" + "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:" + "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA" +#else /* Default - intermediate. */ + "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:" + "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:" + "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" + "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" + "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" + "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" + "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" + "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:" + "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:" + "DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:" + "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA" +#endif + ; + +/* + * Default DH params for PFS cipher negotiation. This is a 2048-bit group. + * Will be used if none are provided by the user in the certificate file. + */ +#if !MG_DISABLE_PFS && !defined(KR_VERSION) +static const char mg_s_default_dh_params[] = + "\ +-----BEGIN DH PARAMETERS-----\n\ +MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\ +Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\ ++E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\ +ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\ +wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\ +9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\ +-----END DH PARAMETERS-----\n"; +#endif + +static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert) { + if (cert == NULL || strcmp(cert, "*") == 0) { + return MG_SSL_OK; + } + SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0); + return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? MG_SSL_OK + : MG_SSL_ERROR; +} + +static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert, + const char *key, + const char **err_msg) { + if (key == NULL) key = cert; + if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') { + return MG_SSL_OK; + } else if (SSL_CTX_use_certificate_file(ctx, cert, 1) == 0) { + MG_SET_PTRPTR(err_msg, "Invalid SSL cert"); + return MG_SSL_ERROR; + } else if (SSL_CTX_use_PrivateKey_file(ctx, key, 1) == 0) { + MG_SET_PTRPTR(err_msg, "Invalid SSL key"); + return MG_SSL_ERROR; + } else if (SSL_CTX_use_certificate_chain_file(ctx, cert) == 0) { + MG_SET_PTRPTR(err_msg, "Invalid CA bundle"); + return MG_SSL_ERROR; + } else { + SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); +#if !MG_DISABLE_PFS && !defined(KR_VERSION) + BIO *bio = NULL; + DH *dh = NULL; + + /* Try to read DH parameters from the cert/key file. */ + bio = BIO_new_file(cert, "r"); + if (bio != NULL) { + dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); + BIO_free(bio); + } + /* + * If there are no DH params in the file, fall back to hard-coded ones. + * Not ideal, but better than nothing. + */ + if (dh == NULL) { + bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1); + dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); + BIO_free(bio); + } + if (dh != NULL) { + SSL_CTX_set_tmp_dh(ctx, dh); + SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE); + DH_free(dh); + } +#if OPENSSL_VERSION_NUMBER > 0x10002000L + SSL_CTX_set_ecdh_auto(ctx, 1); +#endif +#endif + } + return MG_SSL_OK; +} + +static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl) { + return (SSL_CTX_set_cipher_list(ctx, cl ? cl : mg_s_cipher_list) == 1 + ? MG_SSL_OK + : MG_SSL_ERROR); +} + +#ifndef KR_VERSION +static unsigned int mg_ssl_if_ossl_psk_cb(SSL *ssl, const char *hint, + char *identity, + unsigned int max_identity_len, + unsigned char *psk, + unsigned int max_psk_len) { + struct mg_ssl_if_ctx *ctx = + (struct mg_ssl_if_ctx *) SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)); + size_t key_len = ctx->psk.len - ctx->identity_len - 1; + DBG(("hint: '%s'", (hint ? hint : ""))); + if (ctx->identity_len + 1 > max_identity_len) { + DBG(("identity too long")); + return 0; + } + if (key_len > max_psk_len) { + DBG(("key too long")); + return 0; + } + memcpy(identity, ctx->psk.buf, ctx->identity_len + 1); + memcpy(psk, ctx->psk.buf + ctx->identity_len + 1, key_len); + (void) ssl; + return key_len; +} + +static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx, + const char *identity, + const char *key_str) { + unsigned char key[32]; + size_t key_len; + size_t i = 0; + if (identity == NULL && key_str == NULL) return MG_SSL_OK; + if (identity == NULL || key_str == NULL) return MG_SSL_ERROR; + key_len = strlen(key_str); + if (key_len != 32 && key_len != 64) return MG_SSL_ERROR; + memset(key, 0, sizeof(key)); + key_len = 0; + for (i = 0; key_str[i] != '\0'; i++) { + unsigned char c; + char hc = tolower((int) key_str[i]); + if (hc >= '0' && hc <= '9') { + c = hc - '0'; + } else if (hc >= 'a' && hc <= 'f') { + c = hc - 'a' + 0xa; + } else { + return MG_SSL_ERROR; + } + key_len = i / 2; + key[key_len] <<= 4; + key[key_len] |= c; + } + key_len++; + DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len)); + ctx->identity_len = strlen(identity); + mbuf_append(&ctx->psk, identity, ctx->identity_len + 1); + mbuf_append(&ctx->psk, key, key_len); + SSL_CTX_set_psk_client_callback(ctx->ssl_ctx, mg_ssl_if_ossl_psk_cb); + SSL_CTX_set_app_data(ctx->ssl_ctx, ctx); + return MG_SSL_OK; +} +#else +static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx, + const char *identity, + const char *key_str) { + (void) ctx; + (void) identity; + (void) key_str; + /* Krypton does not support PSK. */ + return MG_SSL_ERROR; +} +#endif /* defined(KR_VERSION) */ + +const char *mg_set_ssl(struct mg_connection *nc, const char *cert, + const char *ca_cert) { + const char *err_msg = NULL; + struct mg_ssl_if_conn_params params; + memset(¶ms, 0, sizeof(params)); + params.cert = cert; + params.ca_cert = ca_cert; + if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) { + return err_msg; + } + return NULL; +} + +#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_ssl_if_mbedtls.c" +#endif +/* + * Copyright (c) 2014-2016 Cesanta Software Limited + * All rights reserved + */ + +#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS + +#include +#include +#include +#include +#include +#include +#include +#include + +static void mg_ssl_mbed_log(void *ctx, int level, const char *file, int line, + const char *str) { + enum cs_log_level cs_level; + switch (level) { + case 1: + cs_level = LL_ERROR; + break; + case 2: + cs_level = LL_INFO; + break; + case 3: + cs_level = LL_DEBUG; + break; + default: + cs_level = LL_VERBOSE_DEBUG; + } + /* mbedTLS passes strings with \n at the end, strip it. */ + LOG(cs_level, ("%p %.*s", ctx, (int) (strlen(str) - 1), str)); + (void) ctx; + (void) str; + (void) file; + (void) line; + (void) cs_level; +} + +struct mg_ssl_if_ctx { + mbedtls_ssl_config *conf; + mbedtls_ssl_context *ssl; + mbedtls_x509_crt *cert; + mbedtls_pk_context *key; + mbedtls_x509_crt *ca_cert; + struct mbuf cipher_suites; + size_t saved_len; +}; + +/* Must be provided by the platform. ctx is struct mg_connection. */ +extern int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len); + +void mg_ssl_if_init() { + LOG(LL_INFO, ("%s", MBEDTLS_VERSION_STRING_FULL)); +} + +enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, + struct mg_connection *lc) { + struct mg_ssl_if_ctx *ctx = + (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); + struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data; + nc->ssl_if_data = ctx; + if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR; + ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl)); + if (mbedtls_ssl_setup(ctx->ssl, lc_ctx->conf) != 0) { + return MG_SSL_ERROR; + } + return MG_SSL_OK; +} + +static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx, + const char *cert, const char *key, + const char **err_msg); +static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx, + const char *cert); +static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx, + const char *ciphers); +#ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED +static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx, + const char *identity, + const char *key); +#endif + +enum mg_ssl_if_result mg_ssl_if_conn_init( + struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, + const char **err_msg) { + struct mg_ssl_if_ctx *ctx = + (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); + DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""), + (params->key ? params->key : ""), + (params->ca_cert ? params->ca_cert : ""))); + + if (ctx == NULL) { + MG_SET_PTRPTR(err_msg, "Out of memory"); + return MG_SSL_ERROR; + } + nc->ssl_if_data = ctx; + ctx->conf = (mbedtls_ssl_config *) MG_CALLOC(1, sizeof(*ctx->conf)); + mbuf_init(&ctx->cipher_suites, 0); + mbedtls_ssl_config_init(ctx->conf); + mbedtls_ssl_conf_dbg(ctx->conf, mg_ssl_mbed_log, nc); + if (mbedtls_ssl_config_defaults( + ctx->conf, (nc->flags & MG_F_LISTENING ? MBEDTLS_SSL_IS_SERVER + : MBEDTLS_SSL_IS_CLIENT), + MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) { + MG_SET_PTRPTR(err_msg, "Failed to init SSL config"); + return MG_SSL_ERROR; + } + + /* TLS 1.2 and up */ + mbedtls_ssl_conf_min_version(ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3, + MBEDTLS_SSL_MINOR_VERSION_3); + mbedtls_ssl_conf_rng(ctx->conf, mg_ssl_if_mbed_random, nc); + + if (params->cert != NULL && + mg_use_cert(ctx, params->cert, params->key, err_msg) != MG_SSL_OK) { + return MG_SSL_ERROR; + } + + if (params->ca_cert != NULL && + mg_use_ca_cert(ctx, params->ca_cert) != MG_SSL_OK) { + MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert"); + return MG_SSL_ERROR; + } + + if (mg_set_cipher_list(ctx, params->cipher_suites) != MG_SSL_OK) { + MG_SET_PTRPTR(err_msg, "Invalid cipher suite list"); + return MG_SSL_ERROR; + } + +#ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED + if (mg_ssl_if_mbed_set_psk(ctx, params->psk_identity, params->psk_key) != + MG_SSL_OK) { + MG_SET_PTRPTR(err_msg, "Invalid PSK settings"); + return MG_SSL_ERROR; + } +#endif + + if (!(nc->flags & MG_F_LISTENING)) { + ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl)); + mbedtls_ssl_init(ctx->ssl); + if (mbedtls_ssl_setup(ctx->ssl, ctx->conf) != 0) { + MG_SET_PTRPTR(err_msg, "Failed to create SSL session"); + return MG_SSL_ERROR; + } + if (params->server_name != NULL && + mbedtls_ssl_set_hostname(ctx->ssl, params->server_name) != 0) { + return MG_SSL_ERROR; + } + } + +#ifdef MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN + if (mbedtls_ssl_conf_max_frag_len(ctx->conf, +#if MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 512 + MBEDTLS_SSL_MAX_FRAG_LEN_512 +#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 1024 + MBEDTLS_SSL_MAX_FRAG_LEN_1024 +#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 2048 + MBEDTLS_SSL_MAX_FRAG_LEN_2048 +#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 4096 + MBEDTLS_SSL_MAX_FRAG_LEN_4096 +#else +#error Invalid MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN +#endif + ) != 0) { + return MG_SSL_ERROR; + } +#endif + + nc->flags |= MG_F_SSL; + + return MG_SSL_OK; +} + +static int mg_ssl_if_mbed_send(void *ctx, const unsigned char *buf, + size_t len) { + struct mg_connection *nc = (struct mg_connection *) ctx; + int n = nc->iface->vtable->tcp_send(nc, buf, len); + if (n > 0) return n; + if (n == 0) return MBEDTLS_ERR_SSL_WANT_WRITE; + return MBEDTLS_ERR_NET_SEND_FAILED; +} + +static int mg_ssl_if_mbed_recv(void *ctx, unsigned char *buf, size_t len) { + struct mg_connection *nc = (struct mg_connection *) ctx; + int n = nc->iface->vtable->tcp_recv(nc, buf, len); + if (n > 0) return n; + if (n == 0) return MBEDTLS_ERR_SSL_WANT_READ; + return MBEDTLS_ERR_NET_RECV_FAILED; +} + +static enum mg_ssl_if_result mg_ssl_if_mbed_err(struct mg_connection *nc, + int ret) { + enum mg_ssl_if_result res = MG_SSL_OK; + if (ret == MBEDTLS_ERR_SSL_WANT_READ) { + res = MG_SSL_WANT_READ; + } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { + res = MG_SSL_WANT_WRITE; + } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { + LOG(LL_DEBUG, ("%p TLS connection closed by peer", nc)); + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + res = MG_SSL_OK; + } else { + LOG(LL_ERROR, ("%p mbedTLS error: -0x%04x", nc, -ret)); + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + res = MG_SSL_ERROR; + } + nc->err = ret; + return res; +} + +static void mg_ssl_if_mbed_free_certs_and_keys(struct mg_ssl_if_ctx *ctx) { + if (ctx->cert != NULL) { + mbedtls_x509_crt_free(ctx->cert); + MG_FREE(ctx->cert); + ctx->cert = NULL; + mbedtls_pk_free(ctx->key); + MG_FREE(ctx->key); + ctx->key = NULL; + } + if (ctx->ca_cert != NULL) { + mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL); +#ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK + if (ctx->conf->ca_chain_file != NULL) { + MG_FREE((void *) ctx->conf->ca_chain_file); + ctx->conf->ca_chain_file = NULL; + } +#endif + mbedtls_x509_crt_free(ctx->ca_cert); + MG_FREE(ctx->ca_cert); + ctx->ca_cert = NULL; + } +} + +enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) { + struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; + int err; + /* If bio is not yet set, do it now. */ + if (ctx->ssl->p_bio == NULL) { + mbedtls_ssl_set_bio(ctx->ssl, nc, mg_ssl_if_mbed_send, mg_ssl_if_mbed_recv, + NULL); + } + err = mbedtls_ssl_handshake(ctx->ssl); + if (err != 0) return mg_ssl_if_mbed_err(nc, err); +#ifdef MG_SSL_IF_MBEDTLS_FREE_CERTS + /* + * Free the peer certificate, we don't need it after handshake. + * Note that this effectively disables renegotiation. + */ + mbedtls_x509_crt_free(ctx->ssl->session->peer_cert); + mbedtls_free(ctx->ssl->session->peer_cert); + ctx->ssl->session->peer_cert = NULL; + /* On a client connection we can also free our own and CA certs. */ + if (nc->listener == NULL) { + if (ctx->conf->key_cert != NULL) { + /* Note that this assumes one key_cert entry, which matches our init. */ + MG_FREE(ctx->conf->key_cert); + ctx->conf->key_cert = NULL; + } + mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL); + mg_ssl_if_mbed_free_certs_and_keys(ctx); + } +#endif + return MG_SSL_OK; +} + +int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) { + struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; + int n = mbedtls_ssl_read(ctx->ssl, (unsigned char *) buf, len); + DBG(("%p %d -> %d", nc, (int) len, n)); + if (n < 0) return mg_ssl_if_mbed_err(nc, n); + if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY; + return n; +} + +int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) { + struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; + /* Per mbedTLS docs, if write returns WANT_READ or WANT_WRITE, the operation + * should be retried with the same data and length. + * Here we assume that the data being pushed will remain the same but the + * amount may grow between calls so we save the length that was used and + * retry. The assumption being that the data itself won't change and won't + * be removed. */ + size_t l = len; + if (ctx->saved_len > 0 && ctx->saved_len < l) l = ctx->saved_len; + int n = mbedtls_ssl_write(ctx->ssl, (const unsigned char *) buf, l); + DBG(("%p %d,%d,%d -> %d", nc, (int) len, (int) ctx->saved_len, (int) l, n)); + if (n < 0) { + if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE) { + ctx->saved_len = len; + } + return mg_ssl_if_mbed_err(nc, n); + } else if (n > 0) { + ctx->saved_len = 0; + } + return n; +} + +void mg_ssl_if_conn_close_notify(struct mg_connection *nc) { + struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; + if (ctx == NULL) return; + mbedtls_ssl_close_notify(ctx->ssl); +} + +void mg_ssl_if_conn_free(struct mg_connection *nc) { + struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; + if (ctx == NULL) return; + nc->ssl_if_data = NULL; + if (ctx->ssl != NULL) { + mbedtls_ssl_free(ctx->ssl); + MG_FREE(ctx->ssl); + } + mg_ssl_if_mbed_free_certs_and_keys(ctx); + if (ctx->conf != NULL) { + mbedtls_ssl_config_free(ctx->conf); + MG_FREE(ctx->conf); + } + mbuf_free(&ctx->cipher_suites); + memset(ctx, 0, sizeof(*ctx)); + MG_FREE(ctx); +} + +static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx, + const char *ca_cert) { + if (ca_cert == NULL || strcmp(ca_cert, "*") == 0) { + mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_NONE); + return MG_SSL_OK; + } + ctx->ca_cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->ca_cert)); + mbedtls_x509_crt_init(ctx->ca_cert); +#ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK + ca_cert = strdup(ca_cert); + mbedtls_ssl_conf_ca_chain_file(ctx->conf, ca_cert, NULL); +#else + if (mbedtls_x509_crt_parse_file(ctx->ca_cert, ca_cert) != 0) { + return MG_SSL_ERROR; + } + mbedtls_ssl_conf_ca_chain(ctx->conf, ctx->ca_cert, NULL); +#endif + mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED); + return MG_SSL_OK; +} + +static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx, + const char *cert, const char *key, + const char **err_msg) { + if (key == NULL) key = cert; + if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') { + return MG_SSL_OK; + } + ctx->cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->cert)); + mbedtls_x509_crt_init(ctx->cert); + ctx->key = (mbedtls_pk_context *) MG_CALLOC(1, sizeof(*ctx->key)); + mbedtls_pk_init(ctx->key); + if (mbedtls_x509_crt_parse_file(ctx->cert, cert) != 0) { + MG_SET_PTRPTR(err_msg, "Invalid SSL cert"); + return MG_SSL_ERROR; + } + if (mbedtls_pk_parse_keyfile(ctx->key, key, NULL) != 0) { + MG_SET_PTRPTR(err_msg, "Invalid SSL key"); + return MG_SSL_ERROR; + } + if (mbedtls_ssl_conf_own_cert(ctx->conf, ctx->cert, ctx->key) != 0) { + MG_SET_PTRPTR(err_msg, "Invalid SSL key or cert"); + return MG_SSL_ERROR; + } + return MG_SSL_OK; +} + +static const int mg_s_cipher_list[] = { +#if CS_PLATFORM != CS_P_ESP8266 + MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, + MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, + MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA, +#else + /* + * ECDHE is way too slow on ESP8266 w/o cryptochip, this sometimes results + * in WiFi STA deauths. Use weaker but faster cipher suites. Sad but true. + * Disable DHE completely because it's just hopelessly slow. + */ + MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, + MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, + MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, + MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA, +#endif /* CS_PLATFORM != CS_P_ESP8266 */ + 0, +}; + +/* + * Ciphers can be specified as a colon-separated list of cipher suite names. + * These can be found in + * https://github.com/ARMmbed/mbedtls/blob/development/library/ssl_ciphersuites.c#L267 + * E.g.: TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-CCM + */ +static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx, + const char *ciphers) { + if (ciphers != NULL) { + int l, id; + const char *s = ciphers, *e; + char tmp[50]; + while (s != NULL) { + e = strchr(s, ':'); + l = (e != NULL ? (e - s) : (int) strlen(s)); + strncpy(tmp, s, l); + tmp[l] = '\0'; + id = mbedtls_ssl_get_ciphersuite_id(tmp); + DBG(("%s -> %04x", tmp, id)); + if (id != 0) { + mbuf_append(&ctx->cipher_suites, &id, sizeof(id)); + } + s = (e != NULL ? e + 1 : NULL); + } + if (ctx->cipher_suites.len == 0) return MG_SSL_ERROR; + id = 0; + mbuf_append(&ctx->cipher_suites, &id, sizeof(id)); + mbuf_trim(&ctx->cipher_suites); + mbedtls_ssl_conf_ciphersuites(ctx->conf, + (const int *) ctx->cipher_suites.buf); + } else { + mbedtls_ssl_conf_ciphersuites(ctx->conf, mg_s_cipher_list); + } + return MG_SSL_OK; +} + +#ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED +static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx, + const char *identity, + const char *key_str) { + unsigned char key[32]; + size_t key_len; + if (identity == NULL && key_str == NULL) return MG_SSL_OK; + if (identity == NULL || key_str == NULL) return MG_SSL_ERROR; + key_len = strlen(key_str); + if (key_len != 32 && key_len != 64) return MG_SSL_ERROR; + size_t i = 0; + memset(key, 0, sizeof(key)); + key_len = 0; + for (i = 0; key_str[i] != '\0'; i++) { + unsigned char c; + char hc = tolower((int) key_str[i]); + if (hc >= '0' && hc <= '9') { + c = hc - '0'; + } else if (hc >= 'a' && hc <= 'f') { + c = hc - 'a' + 0xa; + } else { + return MG_SSL_ERROR; + } + key_len = i / 2; + key[key_len] <<= 4; + key[key_len] |= c; + } + key_len++; + DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len)); + /* mbedTLS makes copies of psk and identity. */ + if (mbedtls_ssl_conf_psk(ctx->conf, (const unsigned char *) key, key_len, + (const unsigned char *) identity, + strlen(identity)) != 0) { + return MG_SSL_ERROR; + } + return MG_SSL_OK; +} +#endif + +const char *mg_set_ssl(struct mg_connection *nc, const char *cert, + const char *ca_cert) { + const char *err_msg = NULL; + struct mg_ssl_if_conn_params params; + memset(¶ms, 0, sizeof(params)); + params.cert = cert; + params.ca_cert = ca_cert; + if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) { + return err_msg; + } + return NULL; +} + +/* Lazy RNG. Warning: it would be a bad idea to do this in production! */ +#ifdef MG_SSL_MBED_DUMMY_RANDOM +int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len) { + (void) ctx; + while (len--) *buf++ = rand(); + return 0; +} +#endif + +#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_uri.c" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +/* Amalgamated: #include "mg_internal.h" */ +/* Amalgamated: #include "mg_uri.h" */ + +/* + * scan string until encountering one of `seps`, keeping track of component + * boundaries in `res`. + * + * `p` will point to the char after the separator or it will be `end`. + */ +static void parse_uri_component(const char **p, const char *end, + const char *seps, struct mg_str *res) { + const char *q; + res->p = *p; + for (; *p < end; (*p)++) { + for (q = seps; *q != '\0'; q++) { + if (**p == *q) break; + } + if (*q != '\0') break; + } + res->len = (*p) - res->p; + if (*p < end) (*p)++; +} + +int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme, + struct mg_str *user_info, struct mg_str *host, + unsigned int *port, struct mg_str *path, struct mg_str *query, + struct mg_str *fragment) { + struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0}, + rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0}; + unsigned int rport = 0; + enum { + P_START, + P_SCHEME_OR_PORT, + P_USER_INFO, + P_HOST, + P_PORT, + P_REST + } state = P_START; + + const char *p = uri.p, *end = p + uri.len; + while (p < end) { + switch (state) { + case P_START: + /* + * expecting on of: + * - `scheme://xxxx` + * - `xxxx:port` + * - `[a:b:c]:port` + * - `xxxx/path` + */ + if (*p == '[') { + state = P_HOST; + break; + } + for (; p < end; p++) { + if (*p == ':') { + state = P_SCHEME_OR_PORT; + break; + } else if (*p == '/') { + state = P_REST; + break; + } + } + if (state == P_START || state == P_REST) { + rhost.p = uri.p; + rhost.len = p - uri.p; + } + break; + case P_SCHEME_OR_PORT: + if (end - p >= 3 && strncmp(p, "://", 3) == 0) { + rscheme.p = uri.p; + rscheme.len = p - uri.p; + state = P_USER_INFO; + p += 3; + } else { + rhost.p = uri.p; + rhost.len = p - uri.p; + state = P_PORT; + } + break; + case P_USER_INFO: + ruser_info.p = p; + for (; p < end; p++) { + if (*p == '@' || *p == '[' || *p == '/') { + break; + } + } + if (p == end || *p == '/' || *p == '[') { + /* backtrack and parse as host */ + p = ruser_info.p; + } + ruser_info.len = p - ruser_info.p; + state = P_HOST; + break; + case P_HOST: + if (*p == '@') p++; + rhost.p = p; + if (*p == '[') { + int found = 0; + for (; !found && p < end; p++) { + found = (*p == ']'); + } + if (!found) return -1; + } else { + for (; p < end; p++) { + if (*p == ':' || *p == '/') break; + } + } + rhost.len = p - rhost.p; + if (p < end) { + if (*p == ':') { + state = P_PORT; + break; + } else if (*p == '/') { + state = P_REST; + break; + } + } + break; + case P_PORT: + p++; + for (; p < end; p++) { + if (*p == '/') { + state = P_REST; + break; + } + rport *= 10; + rport += *p - '0'; + } + break; + case P_REST: + /* `p` points to separator. `path` includes the separator */ + parse_uri_component(&p, end, "?#", &rpath); + if (p < end && *(p - 1) == '?') { + parse_uri_component(&p, end, "#", &rquery); + } + parse_uri_component(&p, end, "", &rfragment); + break; + } + } + + if (scheme != 0) *scheme = rscheme; + if (user_info != 0) *user_info = ruser_info; + if (host != 0) *host = rhost; + if (port != 0) *port = rport; + if (path != 0) *path = rpath; + if (query != 0) *query = rquery; + if (fragment != 0) *fragment = rfragment; + + return 0; +} + +/* Normalize the URI path. Remove/resolve "." and "..". */ +int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out) { + const char *s = in->p, *se = s + in->len; + char *cp = (char *) out->p, *d; + + if (in->len == 0 || *s != '/') { + out->len = 0; + return 0; + } + + d = cp; + + while (s < se) { + const char *next = s; + struct mg_str component; + parse_uri_component(&next, se, "/", &component); + if (mg_vcmp(&component, ".") == 0) { + /* Yum. */ + } else if (mg_vcmp(&component, "..") == 0) { + /* Backtrack to previous slash. */ + if (d > cp + 1 && *(d - 1) == '/') d--; + while (d > cp && *(d - 1) != '/') d--; + } else { + memmove(d, s, next - s); + d += next - s; + } + s = next; + } + if (d == cp) *d++ = '/'; + + out->p = cp; + out->len = d - cp; + return 1; +} + +int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info, + const struct mg_str *host, unsigned int port, + const struct mg_str *path, const struct mg_str *query, + const struct mg_str *fragment, int normalize_path, + struct mg_str *uri) { + int result = -1; + struct mbuf out; + mbuf_init(&out, 0); + + if (scheme != NULL && scheme->len > 0) { + mbuf_append(&out, scheme->p, scheme->len); + mbuf_append(&out, "://", 3); + } + + if (user_info != NULL && user_info->len > 0) { + mbuf_append(&out, user_info->p, user_info->len); + mbuf_append(&out, "@", 1); + } + + if (host != NULL && host->len > 0) { + mbuf_append(&out, host->p, host->len); + } + + if (port != 0) { + char port_str[20]; + int port_str_len = sprintf(port_str, ":%u", port); + mbuf_append(&out, port_str, port_str_len); + } + + if (path != NULL && path->len > 0) { + if (normalize_path) { + struct mg_str npath = mg_strdup(*path); + if (npath.len != path->len) goto out; + if (!mg_normalize_uri_path(path, &npath)) { + free((void *) npath.p); + goto out; + } + mbuf_append(&out, npath.p, npath.len); + free((void *) npath.p); + } else { + mbuf_append(&out, path->p, path->len); + } + } else if (normalize_path) { + mbuf_append(&out, "/", 1); + } + + if (query != NULL && query->len > 0) { + mbuf_append(&out, "?", 1); + mbuf_append(&out, query->p, query->len); + } + + if (fragment != NULL && fragment->len > 0) { + mbuf_append(&out, "#", 1); + mbuf_append(&out, fragment->p, fragment->len); + } + + result = 0; + +out: + if (result == 0) { + uri->p = out.buf; + uri->len = out.len; + } else { + mbuf_free(&out); + uri->p = NULL; + uri->len = 0; + } + return result; +} +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_http.c" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +#if MG_ENABLE_HTTP + +/* Amalgamated: #include "common/cs_md5.h" */ +/* Amalgamated: #include "mg_internal.h" */ +/* Amalgamated: #include "mg_util.h" */ + +/* altbuf {{{ */ + +/* + * Alternate buffer: fills the client-provided buffer with data; and if it's + * not large enough, allocates another buffer (via mbuf), similar to asprintf. + */ +struct altbuf { + struct mbuf m; + char *user_buf; + size_t len; + size_t user_buf_size; +}; + +/* + * Initializes altbuf; `buf`, `buf_size` is the client-provided buffer. + */ +MG_INTERNAL void altbuf_init(struct altbuf *ab, char *buf, size_t buf_size) { + mbuf_init(&ab->m, 0); + ab->user_buf = buf; + ab->user_buf_size = buf_size; + ab->len = 0; +} + +/* + * Appends a single char to the altbuf. + */ +MG_INTERNAL void altbuf_append(struct altbuf *ab, char c) { + if (ab->len < ab->user_buf_size) { + /* The data fits into the original buffer */ + ab->user_buf[ab->len++] = c; + } else { + /* The data can't fit into the original buffer, so write it to mbuf. */ + + /* + * First of all, see if that's the first byte which overflows the original + * buffer: if so, copy the existing data from there to a newly allocated + * mbuf. + */ + if (ab->len > 0 && ab->m.len == 0) { + mbuf_append(&ab->m, ab->user_buf, ab->len); + } + + mbuf_append(&ab->m, &c, 1); + ab->len = ab->m.len; + } +} + +/* + * Resets any data previously appended to altbuf. + */ +MG_INTERNAL void altbuf_reset(struct altbuf *ab) { + mbuf_free(&ab->m); + ab->len = 0; +} + +/* + * Returns whether the additional buffer was allocated (and thus the data + * is in the mbuf, not the client-provided buffer) + */ +MG_INTERNAL int altbuf_reallocated(struct altbuf *ab) { + return ab->len > ab->user_buf_size; +} + +/* + * Returns the actual buffer with data, either the client-provided or a newly + * allocated one. If `trim` is non-zero, mbuf-backed buffer is trimmed first. + */ +MG_INTERNAL char *altbuf_get_buf(struct altbuf *ab, int trim) { + if (altbuf_reallocated(ab)) { + if (trim) { + mbuf_trim(&ab->m); + } + return ab->m.buf; + } else { + return ab->user_buf; + } +} + +/* }}} */ + +static const char *mg_version_header = "Mongoose/" MG_VERSION; + +enum mg_http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT }; + +struct mg_http_proto_data_file { + FILE *fp; /* Opened file. */ + int64_t cl; /* Content-Length. How many bytes to send. */ + int64_t sent; /* How many bytes have been already sent. */ + int keepalive; /* Keep connection open after sending. */ + enum mg_http_proto_data_type type; +}; + +#if MG_ENABLE_HTTP_CGI +struct mg_http_proto_data_cgi { + struct mg_connection *cgi_nc; +}; +#endif + +struct mg_http_proto_data_chuncked { + int64_t body_len; /* How many bytes of chunked body was reassembled. */ +}; + +struct mg_http_endpoint { + struct mg_http_endpoint *next; + struct mg_str uri_pattern; /* owned */ + char *auth_domain; /* owned */ + char *auth_file; /* owned */ + + mg_event_handler_t handler; +#if MG_ENABLE_CALLBACK_USERDATA + void *user_data; +#endif +}; + +enum mg_http_multipart_stream_state { + MPS_BEGIN, + MPS_WAITING_FOR_BOUNDARY, + MPS_WAITING_FOR_CHUNK, + MPS_GOT_BOUNDARY, + MPS_FINALIZE, + MPS_FINISHED +}; + +struct mg_http_multipart_stream { + const char *boundary; + int boundary_len; + const char *var_name; + const char *file_name; + void *user_data; + enum mg_http_multipart_stream_state state; + int processing_part; + int data_avail; +}; + +struct mg_reverse_proxy_data { + struct mg_connection *linked_conn; +}; + +struct mg_ws_proto_data { + /* + * Defragmented size of the frame so far. + * + * First byte of nc->recv_mbuf.buf is an op, the rest of the data is + * defragmented data. + */ + size_t reass_len; +}; + +struct mg_http_proto_data { +#if MG_ENABLE_FILESYSTEM + struct mg_http_proto_data_file file; +#endif +#if MG_ENABLE_HTTP_CGI + struct mg_http_proto_data_cgi cgi; +#endif +#if MG_ENABLE_HTTP_STREAMING_MULTIPART + struct mg_http_multipart_stream mp_stream; +#endif +#if MG_ENABLE_HTTP_WEBSOCKET + struct mg_ws_proto_data ws_data; +#endif + struct mg_http_proto_data_chuncked chunk; + struct mg_http_endpoint *endpoints; + mg_event_handler_t endpoint_handler; + struct mg_reverse_proxy_data reverse_proxy_data; + size_t rcvd; /* How many bytes we have received. */ +}; + +static void mg_http_conn_destructor(void *proto_data); +struct mg_connection *mg_connect_http_base( + struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), + struct mg_connect_opts opts, const char *scheme1, const char *scheme2, + const char *scheme_ssl1, const char *scheme_ssl2, const char *url, + struct mg_str *path, struct mg_str *user_info, struct mg_str *host); + +static struct mg_http_proto_data *mg_http_get_proto_data( + struct mg_connection *c) { + if (c->proto_data == NULL) { + c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data)); + c->proto_data_destructor = mg_http_conn_destructor; + } + + return (struct mg_http_proto_data *) c->proto_data; +} + +#if MG_ENABLE_HTTP_STREAMING_MULTIPART +static void mg_http_free_proto_data_mp_stream( + struct mg_http_multipart_stream *mp) { + MG_FREE((void *) mp->boundary); + MG_FREE((void *) mp->var_name); + MG_FREE((void *) mp->file_name); + memset(mp, 0, sizeof(*mp)); +} +#endif + +#if MG_ENABLE_FILESYSTEM +static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d) { + if (d != NULL) { + if (d->fp != NULL) { + fclose(d->fp); + } + memset(d, 0, sizeof(struct mg_http_proto_data_file)); + } +} +#endif + +static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep) { + struct mg_http_endpoint *current = *ep; + + while (current != NULL) { + struct mg_http_endpoint *tmp = current->next; + MG_FREE((void *) current->uri_pattern.p); + MG_FREE((void *) current->auth_domain); + MG_FREE((void *) current->auth_file); + MG_FREE(current); + current = tmp; + } + + ep = NULL; +} + +static void mg_http_free_reverse_proxy_data(struct mg_reverse_proxy_data *rpd) { + if (rpd->linked_conn != NULL) { + /* + * Connection has linked one, we have to unlink & close it + * since _this_ connection is going to die and + * it doesn't make sense to keep another one + */ + struct mg_http_proto_data *pd = mg_http_get_proto_data(rpd->linked_conn); + if (pd->reverse_proxy_data.linked_conn != NULL) { + pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE; + pd->reverse_proxy_data.linked_conn = NULL; + } + rpd->linked_conn = NULL; + } +} + +static void mg_http_conn_destructor(void *proto_data) { + struct mg_http_proto_data *pd = (struct mg_http_proto_data *) proto_data; +#if MG_ENABLE_FILESYSTEM + mg_http_free_proto_data_file(&pd->file); +#endif +#if MG_ENABLE_HTTP_CGI + mg_http_free_proto_data_cgi(&pd->cgi); +#endif +#if MG_ENABLE_HTTP_STREAMING_MULTIPART + mg_http_free_proto_data_mp_stream(&pd->mp_stream); +#endif + mg_http_free_proto_data_endpoints(&pd->endpoints); + mg_http_free_reverse_proxy_data(&pd->reverse_proxy_data); + MG_FREE(proto_data); +} + +#if MG_ENABLE_FILESYSTEM + +#define MIME_ENTRY(_ext, _type) \ + { _ext, sizeof(_ext) - 1, _type } +static const struct { + const char *extension; + size_t ext_len; + const char *mime_type; +} mg_static_builtin_mime_types[] = { + MIME_ENTRY("html", "text/html"), + MIME_ENTRY("html", "text/html"), + MIME_ENTRY("htm", "text/html"), + MIME_ENTRY("shtm", "text/html"), + MIME_ENTRY("shtml", "text/html"), + MIME_ENTRY("css", "text/css"), + MIME_ENTRY("js", "application/x-javascript"), + MIME_ENTRY("ico", "image/x-icon"), + MIME_ENTRY("gif", "image/gif"), + MIME_ENTRY("jpg", "image/jpeg"), + MIME_ENTRY("jpeg", "image/jpeg"), + MIME_ENTRY("png", "image/png"), + MIME_ENTRY("svg", "image/svg+xml"), + MIME_ENTRY("txt", "text/plain"), + MIME_ENTRY("torrent", "application/x-bittorrent"), + MIME_ENTRY("wav", "audio/x-wav"), + MIME_ENTRY("mp3", "audio/x-mp3"), + MIME_ENTRY("mid", "audio/mid"), + MIME_ENTRY("m3u", "audio/x-mpegurl"), + MIME_ENTRY("ogg", "application/ogg"), + MIME_ENTRY("ram", "audio/x-pn-realaudio"), + MIME_ENTRY("xml", "text/xml"), + MIME_ENTRY("ttf", "application/x-font-ttf"), + MIME_ENTRY("json", "application/json"), + MIME_ENTRY("xslt", "application/xml"), + MIME_ENTRY("xsl", "application/xml"), + MIME_ENTRY("ra", "audio/x-pn-realaudio"), + MIME_ENTRY("doc", "application/msword"), + MIME_ENTRY("exe", "application/octet-stream"), + MIME_ENTRY("zip", "application/x-zip-compressed"), + MIME_ENTRY("xls", "application/excel"), + MIME_ENTRY("tgz", "application/x-tar-gz"), + MIME_ENTRY("tar", "application/x-tar"), + MIME_ENTRY("gz", "application/x-gunzip"), + MIME_ENTRY("arj", "application/x-arj-compressed"), + MIME_ENTRY("rar", "application/x-rar-compressed"), + MIME_ENTRY("rtf", "application/rtf"), + MIME_ENTRY("pdf", "application/pdf"), + MIME_ENTRY("swf", "application/x-shockwave-flash"), + MIME_ENTRY("mpg", "video/mpeg"), + MIME_ENTRY("webm", "video/webm"), + MIME_ENTRY("mpeg", "video/mpeg"), + MIME_ENTRY("mov", "video/quicktime"), + MIME_ENTRY("mp4", "video/mp4"), + MIME_ENTRY("m4v", "video/x-m4v"), + MIME_ENTRY("asf", "video/x-ms-asf"), + MIME_ENTRY("avi", "video/x-msvideo"), + MIME_ENTRY("bmp", "image/bmp"), + {NULL, 0, NULL}}; + +static struct mg_str mg_get_mime_type(const char *path, const char *dflt, + const struct mg_serve_http_opts *opts) { + const char *ext, *overrides; + size_t i, path_len; + struct mg_str r, k, v; + + path_len = strlen(path); + + overrides = opts->custom_mime_types; + while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) { + ext = path + (path_len - k.len); + if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) { + return v; + } + } + + for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) { + ext = path + (path_len - mg_static_builtin_mime_types[i].ext_len); + if (path_len > mg_static_builtin_mime_types[i].ext_len && ext[-1] == '.' && + mg_casecmp(ext, mg_static_builtin_mime_types[i].extension) == 0) { + r.p = mg_static_builtin_mime_types[i].mime_type; + r.len = strlen(r.p); + return r; + } + } + + r.p = dflt; + r.len = strlen(r.p); + return r; +} +#endif + +/* + * Check whether full request is buffered. Return: + * -1 if request is malformed + * 0 if request is not yet fully buffered + * >0 actual request length, including last \r\n\r\n + */ +static int mg_http_get_request_len(const char *s, int buf_len) { + const unsigned char *buf = (unsigned char *) s; + int i; + + for (i = 0; i < buf_len; i++) { + if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) { + return -1; + } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') { + return i + 2; + } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' && + buf[i + 2] == '\n') { + return i + 3; + } + } + + return 0; +} + +static const char *mg_http_parse_headers(const char *s, const char *end, + int len, struct http_message *req) { + int i = 0; + while (i < (int) ARRAY_SIZE(req->header_names) - 1) { + struct mg_str *k = &req->header_names[i], *v = &req->header_values[i]; + + s = mg_skip(s, end, ": ", k); + s = mg_skip(s, end, "\r\n", v); + + while (v->len > 0 && v->p[v->len - 1] == ' ') { + v->len--; /* Trim trailing spaces in header value */ + } + + /* + * If header value is empty - skip it and go to next (if any). + * NOTE: Do not add it to headers_values because such addition changes API + * behaviour + */ + if (k->len != 0 && v->len == 0) { + continue; + } + + if (k->len == 0 || v->len == 0) { + k->p = v->p = NULL; + k->len = v->len = 0; + break; + } + + if (!mg_ncasecmp(k->p, "Content-Length", 14)) { + req->body.len = (size_t) to64(v->p); + req->message.len = len + req->body.len; + } + + i++; + } + + return s; +} + +int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) { + const char *end, *qs; + int len = mg_http_get_request_len(s, n); + + if (len <= 0) return len; + + memset(hm, 0, sizeof(*hm)); + hm->message.p = s; + hm->body.p = s + len; + hm->message.len = hm->body.len = (size_t) ~0; + end = s + len; + + /* Request is fully buffered. Skip leading whitespaces. */ + while (s < end && isspace(*(unsigned char *) s)) s++; + + if (is_req) { + /* Parse request line: method, URI, proto */ + s = mg_skip(s, end, " ", &hm->method); + s = mg_skip(s, end, " ", &hm->uri); + s = mg_skip(s, end, "\r\n", &hm->proto); + if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1; + + /* If URI contains '?' character, initialize query_string */ + if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) { + hm->query_string.p = qs + 1; + hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1); + hm->uri.len = qs - hm->uri.p; + } + } else { + s = mg_skip(s, end, " ", &hm->proto); + if (end - s < 4 || s[3] != ' ') return -1; + hm->resp_code = atoi(s); + if (hm->resp_code < 100 || hm->resp_code >= 600) return -1; + s += 4; + s = mg_skip(s, end, "\r\n", &hm->resp_status_msg); + } + + s = mg_http_parse_headers(s, end, len, hm); + + /* + * mg_parse_http() is used to parse both HTTP requests and HTTP + * responses. If HTTP response does not have Content-Length set, then + * body is read until socket is closed, i.e. body.len is infinite (~0). + * + * For HTTP requests though, according to + * http://tools.ietf.org/html/rfc7231#section-8.1.3, + * only POST and PUT methods have defined body semantics. + * Therefore, if Content-Length is not specified and methods are + * not one of PUT or POST, set body length to 0. + * + * So, + * if it is HTTP request, and Content-Length is not set, + * and method is not (PUT or POST) then reset body length to zero. + */ + if (hm->body.len == (size_t) ~0 && is_req && + mg_vcasecmp(&hm->method, "PUT") != 0 && + mg_vcasecmp(&hm->method, "POST") != 0) { + hm->body.len = 0; + hm->message.len = len; + } + + return len; +} + +struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) { + size_t i, len = strlen(name); + + for (i = 0; hm->header_names[i].len > 0; i++) { + struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i]; + if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len)) + return v; + } + + return NULL; +} + +#if MG_ENABLE_FILESYSTEM +static void mg_http_transfer_file_data(struct mg_connection *nc) { + struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); + char buf[MG_MAX_HTTP_SEND_MBUF]; + size_t n = 0, to_read = 0, left = (size_t)(pd->file.cl - pd->file.sent); + + if (pd->file.type == DATA_FILE) { + struct mbuf *io = &nc->send_mbuf; + if (io->len >= MG_MAX_HTTP_SEND_MBUF) { + to_read = 0; + } else { + to_read = MG_MAX_HTTP_SEND_MBUF - io->len; + } + if (to_read > left) { + to_read = left; + } + if (to_read > 0) { + n = mg_fread(buf, 1, to_read, pd->file.fp); + if (n > 0) { + mg_send(nc, buf, n); + pd->file.sent += n; + DBG(("%p sent %d (total %d)", nc, (int) n, (int) pd->file.sent)); + } + } else { + /* Rate-limited */ + } + if (pd->file.sent >= pd->file.cl) { + LOG(LL_DEBUG, ("%p done, %d bytes", nc, (int) pd->file.sent)); + if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE; + mg_http_free_proto_data_file(&pd->file); + } + } else if (pd->file.type == DATA_PUT) { + struct mbuf *io = &nc->recv_mbuf; + size_t to_write = left <= 0 ? 0 : left < io->len ? (size_t) left : io->len; + size_t n = mg_fwrite(io->buf, 1, to_write, pd->file.fp); + if (n > 0) { + mbuf_remove(io, n); + pd->file.sent += n; + } + if (n == 0 || pd->file.sent >= pd->file.cl) { + if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE; + mg_http_free_proto_data_file(&pd->file); + } + } +#if MG_ENABLE_HTTP_CGI + else if (pd->cgi.cgi_nc != NULL) { + /* This is POST data that needs to be forwarded to the CGI process */ + if (pd->cgi.cgi_nc != NULL) { + mg_forward(nc, pd->cgi.cgi_nc); + } else { + nc->flags |= MG_F_SEND_AND_CLOSE; + } + } +#endif +} +#endif /* MG_ENABLE_FILESYSTEM */ + +/* + * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or + * if it's incomplete. If the chunk is fully buffered, return total number of + * bytes in a chunk, and store data in `data`, `data_len`. + */ +static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data, + size_t *chunk_len) { + unsigned char *s = (unsigned char *) buf; + size_t n = 0; /* scanned chunk length */ + size_t i = 0; /* index in s */ + + /* Scan chunk length. That should be a hexadecimal number. */ + while (i < len && isxdigit(s[i])) { + n *= 16; + n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10; + i++; + if (i > 6) { + /* Chunk size is unreasonable. */ + return 0; + } + } + + /* Skip new line */ + if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') { + return 0; + } + i += 2; + + /* Record where the data is */ + *chunk_data = (char *) s + i; + *chunk_len = n; + + /* Skip data */ + i += n; + + /* Skip new line */ + if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') { + return 0; + } + return i + 2; +} + +MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc, + struct http_message *hm, char *buf, + size_t blen) { + struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); + char *data; + size_t i, n, data_len, body_len, zero_chunk_received = 0; + /* Find out piece of received data that is not yet reassembled */ + body_len = (size_t) pd->chunk.body_len; + assert(blen >= body_len); + + /* Traverse all fully buffered chunks */ + for (i = body_len; + (n = mg_http_parse_chunk(buf + i, blen - i, &data, &data_len)) > 0; + i += n) { + /* Collapse chunk data to the rest of HTTP body */ + memmove(buf + body_len, data, data_len); + body_len += data_len; + hm->body.len = body_len; + + if (data_len == 0) { + zero_chunk_received = 1; + i += n; + break; + } + } + + if (i > body_len) { + /* Shift unparsed content to the parsed body */ + assert(i <= blen); + memmove(buf + body_len, buf + i, blen - i); + memset(buf + body_len + blen - i, 0, i - body_len); + nc->recv_mbuf.len -= i - body_len; + pd->chunk.body_len = body_len; + + /* Send MG_EV_HTTP_CHUNK event */ + nc->flags &= ~MG_F_DELETE_CHUNK; + mg_call(nc, nc->handler, nc->user_data, MG_EV_HTTP_CHUNK, hm); + + /* Delete processed data if user set MG_F_DELETE_CHUNK flag */ + if (nc->flags & MG_F_DELETE_CHUNK) { + memset(buf, 0, body_len); + memmove(buf, buf + body_len, blen - i); + nc->recv_mbuf.len -= body_len; + hm->body.len = 0; + pd->chunk.body_len = 0; + } + + if (zero_chunk_received) { + /* Total message size is len(body) + len(headers) */ + hm->message.len = + (size_t) pd->chunk.body_len + blen - i + (hm->body.p - hm->message.p); + } + } + + return body_len; +} + +struct mg_http_endpoint *mg_http_get_endpoint_handler(struct mg_connection *nc, + struct mg_str *uri_path) { + struct mg_http_proto_data *pd; + struct mg_http_endpoint *ret = NULL; + int matched, matched_max = 0; + struct mg_http_endpoint *ep; + + if (nc == NULL) { + return NULL; + } + + pd = mg_http_get_proto_data(nc); + + ep = pd->endpoints; + while (ep != NULL) { + if ((matched = mg_match_prefix_n(ep->uri_pattern, *uri_path)) > 0) { + if (matched > matched_max) { + /* Looking for the longest suitable handler */ + ret = ep; + matched_max = matched; + } + } + + ep = ep->next; + } + + return ret; +} + +#if MG_ENABLE_HTTP_STREAMING_MULTIPART +static void mg_http_multipart_continue(struct mg_connection *nc); + +static void mg_http_multipart_begin(struct mg_connection *nc, + struct http_message *hm, int req_len); + +#endif + +static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev, + struct http_message *hm); + +static void deliver_chunk(struct mg_connection *c, struct http_message *hm, + int req_len) { + /* Incomplete message received. Send MG_EV_HTTP_CHUNK event */ + hm->body.len = c->recv_mbuf.len - req_len; + c->flags &= ~MG_F_DELETE_CHUNK; + mg_call(c, c->handler, c->user_data, MG_EV_HTTP_CHUNK, hm); + /* Delete processed data if user set MG_F_DELETE_CHUNK flag */ + if (c->flags & MG_F_DELETE_CHUNK) c->recv_mbuf.len = req_len; +} + +/* + * lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here) + * If a big structure is declared in a big function, lx106 gcc will make it + * even bigger (round up to 4k, from 700 bytes of actual size). + */ +#ifdef __xtensa__ +static void mg_http_handler2(struct mg_connection *nc, int ev, + void *ev_data MG_UD_ARG(void *user_data), + struct http_message *hm) __attribute__((noinline)); + +void mg_http_handler(struct mg_connection *nc, int ev, + void *ev_data MG_UD_ARG(void *user_data)) { + struct http_message hm; + mg_http_handler2(nc, ev, ev_data MG_UD_ARG(user_data), &hm); +} + +static void mg_http_handler2(struct mg_connection *nc, int ev, + void *ev_data MG_UD_ARG(void *user_data), + struct http_message *hm) { +#else /* !__XTENSA__ */ +void mg_http_handler(struct mg_connection *nc, int ev, + void *ev_data MG_UD_ARG(void *user_data)) { + struct http_message shm, *hm = &shm; +#endif /* __XTENSA__ */ + struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); + struct mbuf *io = &nc->recv_mbuf; + int req_len; + const int is_req = (nc->listener != NULL); +#if MG_ENABLE_HTTP_WEBSOCKET + struct mg_str *vec; +#endif + if (ev == MG_EV_CLOSE) { +#if MG_ENABLE_HTTP_CGI + /* Close associated CGI forwarder connection */ + if (pd->cgi.cgi_nc != NULL) { + pd->cgi.cgi_nc->user_data = NULL; + pd->cgi.cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } +#endif +#if MG_ENABLE_HTTP_STREAMING_MULTIPART + if (pd->mp_stream.boundary != NULL) { + /* + * Multipart message is in progress, but connection is closed. + * Finish part and request with an error flag. + */ + struct mg_http_multipart_part mp; + memset(&mp, 0, sizeof(mp)); + mp.status = -1; + mp.var_name = pd->mp_stream.var_name; + mp.file_name = pd->mp_stream.file_name; + mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler), + nc->user_data, MG_EV_HTTP_PART_END, &mp); + mp.var_name = NULL; + mp.file_name = NULL; + mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler), + nc->user_data, MG_EV_HTTP_MULTIPART_REQUEST_END, &mp); + } else +#endif + if (io->len > 0 && + (req_len = mg_parse_http(io->buf, io->len, hm, is_req)) > 0) { + /* + * For HTTP messages without Content-Length, always send HTTP message + * before MG_EV_CLOSE message. + */ + int ev2 = is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY; + hm->message.len = io->len; + hm->body.len = io->buf + io->len - hm->body.p; + deliver_chunk(nc, hm, req_len); + mg_http_call_endpoint_handler(nc, ev2, hm); + } + pd->rcvd = 0; + if (pd->endpoint_handler != NULL && pd->endpoint_handler != nc->handler) { + mg_call(nc, pd->endpoint_handler, nc->user_data, ev, NULL); + } + } + +#if MG_ENABLE_FILESYSTEM + if (pd->file.fp != NULL) { + mg_http_transfer_file_data(nc); + } +#endif + + mg_call(nc, nc->handler, nc->user_data, ev, ev_data); + +#if MG_ENABLE_HTTP_STREAMING_MULTIPART + if (pd->mp_stream.boundary != NULL && + (ev == MG_EV_RECV || ev == MG_EV_POLL)) { + if (ev == MG_EV_RECV) { + pd->rcvd += *(int *) ev_data; + mg_http_multipart_continue(nc); + } else if (pd->mp_stream.data_avail) { + /* Try re-delivering the data. */ + mg_http_multipart_continue(nc); + } + return; + } +#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ + + if (ev == MG_EV_RECV) { + struct mg_str *s; + pd->rcvd += *(int *) ev_data; + + again: + req_len = mg_parse_http(io->buf, io->len, hm, is_req); + + if (req_len > 0 && + (s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL && + mg_vcasecmp(s, "chunked") == 0) { + mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len); + } + +#if MG_ENABLE_HTTP_STREAMING_MULTIPART + if (req_len > 0 && (s = mg_get_http_header(hm, "Content-Type")) != NULL && + s->len >= 9 && strncmp(s->p, "multipart", 9) == 0) { + mg_http_multipart_begin(nc, hm, req_len); + mg_http_multipart_continue(nc); + return; + } +#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ + + /* TODO(alashkin): refactor this ifelseifelseifelseifelse */ + if ((req_len < 0 || + (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE))) { + DBG(("invalid request")); + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } else if (req_len == 0) { + /* Do nothing, request is not yet fully buffered */ + } +#if MG_ENABLE_HTTP_WEBSOCKET + else if (nc->listener == NULL && (nc->flags & MG_F_IS_WEBSOCKET)) { + /* We're websocket client, got handshake response from server. */ + DBG(("%p WebSocket upgrade code %d", nc, hm->resp_code)); + if (hm->resp_code == 101 && + mg_get_http_header(hm, "Sec-WebSocket-Accept")) { + /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */ + mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE, + hm); + mbuf_remove(io, req_len); + nc->proto_handler = mg_ws_handler; + mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data)); + } else { + mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE, + hm); + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + mbuf_remove(io, req_len); + } + } else if (nc->listener != NULL && + (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) { + struct mg_http_endpoint *ep; + + /* This is a websocket request. Switch protocol handlers. */ + mbuf_remove(io, req_len); + nc->proto_handler = mg_ws_handler; + nc->flags |= MG_F_IS_WEBSOCKET; + + /* + * If we have a handler set up with mg_register_http_endpoint(), + * deliver subsequent websocket events to this handler after the + * protocol switch. + */ + ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri); + if (ep != NULL) { + nc->handler = ep->handler; +#if MG_ENABLE_CALLBACK_USERDATA + nc->user_data = ep->user_data; +#endif + } + + /* Send handshake */ + mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST, + hm); + if (!(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_SEND_AND_CLOSE))) { + if (nc->send_mbuf.len == 0) { + mg_ws_handshake(nc, vec, hm); + } + mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE, + hm); + mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data)); + } + } +#endif /* MG_ENABLE_HTTP_WEBSOCKET */ + else if (hm->message.len > pd->rcvd) { + /* Not yet received all HTTP body, deliver MG_EV_HTTP_CHUNK */ + deliver_chunk(nc, hm, req_len); + if (nc->recv_mbuf_limit > 0 && nc->recv_mbuf.len >= nc->recv_mbuf_limit) { + LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit " + "%lu bytes, and not drained, closing", + nc, (unsigned long) nc->recv_mbuf.len, + (unsigned long) nc->recv_mbuf_limit)); + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } + } else { + /* We did receive all HTTP body. */ + int request_done = 1; + int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY; + char addr[32]; + mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), + MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); + DBG(("%p %s %.*s %.*s", nc, addr, (int) hm->method.len, hm->method.p, + (int) hm->uri.len, hm->uri.p)); + deliver_chunk(nc, hm, req_len); + /* Whole HTTP message is fully buffered, call event handler */ + mg_http_call_endpoint_handler(nc, trigger_ev, hm); + mbuf_remove(io, hm->message.len); + pd->rcvd -= hm->message.len; +#if MG_ENABLE_FILESYSTEM + /* We don't have a generic mechanism of communicating that we are done + * responding to a request (should probably add one). But if we are + * serving + * a file, we are definitely not done. */ + if (pd->file.fp != NULL) request_done = 0; +#endif +#if MG_ENABLE_HTTP_CGI + /* If this is a CGI request, we are not done either. */ + if (pd->cgi.cgi_nc != NULL) request_done = 0; +#endif + if (request_done) { + /* This request is done but we may receive another on this connection. + */ + mg_http_conn_destructor(pd); + nc->proto_data = NULL; + if (io->len > 0) { + /* We already have data for the next one, restart parsing. */ + pd = mg_http_get_proto_data(nc); + pd->rcvd = io->len; + goto again; + } + } + } + } +} + +static size_t mg_get_line_len(const char *buf, size_t buf_len) { + size_t len = 0; + while (len < buf_len && buf[len] != '\n') len++; + return len == buf_len ? 0 : len + 1; +} + +#if MG_ENABLE_HTTP_STREAMING_MULTIPART +static void mg_http_multipart_begin(struct mg_connection *nc, + struct http_message *hm, int req_len) { + struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); + struct mg_str *ct; + struct mbuf *io = &nc->recv_mbuf; + + char boundary_buf[100]; + char *boundary = boundary_buf; + int boundary_len; + + ct = mg_get_http_header(hm, "Content-Type"); + if (ct == NULL) { + /* We need more data - or it isn't multipart mesage */ + goto exit_mp; + } + + /* Content-type should start with "multipart" */ + if (ct->len < 9 || strncmp(ct->p, "multipart", 9) != 0) { + goto exit_mp; + } + + boundary_len = + mg_http_parse_header2(ct, "boundary", &boundary, sizeof(boundary_buf)); + if (boundary_len == 0) { + /* + * Content type is multipart, but there is no boundary, + * probably malformed request + */ + nc->flags = MG_F_CLOSE_IMMEDIATELY; + DBG(("invalid request")); + goto exit_mp; + } + + /* If we reach this place - that is multipart request */ + + if (pd->mp_stream.boundary != NULL) { + /* + * Another streaming request was in progress, + * looks like protocol error + */ + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } else { + struct mg_http_endpoint *ep = NULL; + pd->mp_stream.state = MPS_BEGIN; + pd->mp_stream.boundary = strdup(boundary); + pd->mp_stream.boundary_len = strlen(boundary); + pd->mp_stream.var_name = pd->mp_stream.file_name = NULL; + pd->endpoint_handler = nc->handler; + + ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri); + if (ep != NULL) { + pd->endpoint_handler = ep->handler; + } + + mg_http_call_endpoint_handler(nc, MG_EV_HTTP_MULTIPART_REQUEST, hm); + + mbuf_remove(io, req_len); + } +exit_mp: + if (boundary != boundary_buf) MG_FREE(boundary); +} + +#define CONTENT_DISPOSITION "Content-Disposition: " + +static size_t mg_http_multipart_call_handler(struct mg_connection *c, int ev, + const char *data, + size_t data_len) { + struct mg_http_multipart_part mp; + struct mg_http_proto_data *pd = mg_http_get_proto_data(c); + memset(&mp, 0, sizeof(mp)); + + mp.var_name = pd->mp_stream.var_name; + mp.file_name = pd->mp_stream.file_name; + mp.user_data = pd->mp_stream.user_data; + mp.data.p = data; + mp.data.len = data_len; + mp.num_data_consumed = data_len; + mg_call(c, pd->endpoint_handler, c->user_data, ev, &mp); + pd->mp_stream.user_data = mp.user_data; + pd->mp_stream.data_avail = (mp.num_data_consumed != data_len); + return mp.num_data_consumed; +} + +static int mg_http_multipart_finalize(struct mg_connection *c) { + struct mg_http_proto_data *pd = mg_http_get_proto_data(c); + + mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0); + MG_FREE((void *) pd->mp_stream.file_name); + pd->mp_stream.file_name = NULL; + MG_FREE((void *) pd->mp_stream.var_name); + pd->mp_stream.var_name = NULL; + mg_http_multipart_call_handler(c, MG_EV_HTTP_MULTIPART_REQUEST_END, NULL, 0); + mg_http_free_proto_data_mp_stream(&pd->mp_stream); + pd->mp_stream.state = MPS_FINISHED; + + return 1; +} + +static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) { + const char *boundary; + struct mbuf *io = &c->recv_mbuf; + struct mg_http_proto_data *pd = mg_http_get_proto_data(c); + + if (pd->mp_stream.boundary == NULL) { + pd->mp_stream.state = MPS_FINALIZE; + DBG(("Invalid request: boundary not initialized")); + return 0; + } + + if ((int) io->len < pd->mp_stream.boundary_len + 2) { + return 0; + } + + boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len); + if (boundary != NULL) { + const char *boundary_end = (boundary + pd->mp_stream.boundary_len); + if (io->len - (boundary_end - io->buf) < 4) { + return 0; + } + if (strncmp(boundary_end, "--\r\n", 4) == 0) { + pd->mp_stream.state = MPS_FINALIZE; + mbuf_remove(io, (boundary_end - io->buf) + 4); + } else { + pd->mp_stream.state = MPS_GOT_BOUNDARY; + } + } else { + return 0; + } + + return 1; +} + +static void mg_http_parse_header_internal(struct mg_str *hdr, + const char *var_name, + struct altbuf *ab); + +static int mg_http_multipart_process_boundary(struct mg_connection *c) { + int data_size; + const char *boundary, *block_begin; + struct mbuf *io = &c->recv_mbuf; + struct mg_http_proto_data *pd = mg_http_get_proto_data(c); + struct altbuf ab_file_name, ab_var_name; + int line_len; + boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len); + block_begin = boundary + pd->mp_stream.boundary_len + 2; + data_size = io->len - (block_begin - io->buf); + + altbuf_init(&ab_file_name, NULL, 0); + altbuf_init(&ab_var_name, NULL, 0); + + while (data_size > 0 && + (line_len = mg_get_line_len(block_begin, data_size)) != 0) { + if (line_len > (int) sizeof(CONTENT_DISPOSITION) && + mg_ncasecmp(block_begin, CONTENT_DISPOSITION, + sizeof(CONTENT_DISPOSITION) - 1) == 0) { + struct mg_str header; + + header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1; + header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1; + + altbuf_reset(&ab_var_name); + mg_http_parse_header_internal(&header, "name", &ab_var_name); + + altbuf_reset(&ab_file_name); + mg_http_parse_header_internal(&header, "filename", &ab_file_name); + + block_begin += line_len; + data_size -= line_len; + + continue; + } + + if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) { + mbuf_remove(io, block_begin - io->buf + 2); + + if (pd->mp_stream.processing_part != 0) { + mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0); + } + + /* Reserve 2 bytes for "\r\n" in file_name and var_name */ + altbuf_append(&ab_file_name, '\0'); + altbuf_append(&ab_file_name, '\0'); + altbuf_append(&ab_var_name, '\0'); + altbuf_append(&ab_var_name, '\0'); + + MG_FREE((void *) pd->mp_stream.file_name); + pd->mp_stream.file_name = altbuf_get_buf(&ab_file_name, 1 /* trim */); + MG_FREE((void *) pd->mp_stream.var_name); + pd->mp_stream.var_name = altbuf_get_buf(&ab_var_name, 1 /* trim */); + + mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_BEGIN, NULL, 0); + pd->mp_stream.state = MPS_WAITING_FOR_CHUNK; + pd->mp_stream.processing_part++; + return 1; + } + + block_begin += line_len; + } + + pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY; + + altbuf_reset(&ab_var_name); + altbuf_reset(&ab_file_name); + + return 0; +} + +static int mg_http_multipart_continue_wait_for_chunk(struct mg_connection *c) { + struct mg_http_proto_data *pd = mg_http_get_proto_data(c); + struct mbuf *io = &c->recv_mbuf; + + const char *boundary; + if ((int) io->len < pd->mp_stream.boundary_len + 6 /* \r\n, --, -- */) { + return 0; + } + + boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len); + if (boundary == NULL) { + int data_len = (io->len - (pd->mp_stream.boundary_len + 6)); + if (data_len > 0) { + size_t consumed = mg_http_multipart_call_handler( + c, MG_EV_HTTP_PART_DATA, io->buf, (size_t) data_len); + mbuf_remove(io, consumed); + } + return 0; + } else if (boundary != NULL) { + size_t data_len = ((size_t)(boundary - io->buf) - 4); + size_t consumed = mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, + io->buf, data_len); + mbuf_remove(io, consumed); + if (consumed == data_len) { + mbuf_remove(io, 4); + pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY; + return 1; + } else { + return 0; + } + } else { + return 0; + } +} + +static void mg_http_multipart_continue(struct mg_connection *c) { + struct mg_http_proto_data *pd = mg_http_get_proto_data(c); + while (1) { + switch (pd->mp_stream.state) { + case MPS_BEGIN: { + pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY; + break; + } + case MPS_WAITING_FOR_BOUNDARY: { + if (mg_http_multipart_wait_for_boundary(c) == 0) { + return; + } + break; + } + case MPS_GOT_BOUNDARY: { + if (mg_http_multipart_process_boundary(c) == 0) { + return; + } + break; + } + case MPS_WAITING_FOR_CHUNK: { + if (mg_http_multipart_continue_wait_for_chunk(c) == 0) { + return; + } + break; + } + case MPS_FINALIZE: { + if (mg_http_multipart_finalize(c) == 0) { + return; + } + break; + } + case MPS_FINISHED: { + return; + } + } + } +} + +struct file_upload_state { + char *lfn; + size_t num_recd; + FILE *fp; +}; + +#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ + +void mg_set_protocol_http_websocket(struct mg_connection *nc) { + nc->proto_handler = mg_http_handler; +} + +const char *mg_status_message(int status_code) { + switch (status_code) { + case 206: + return "Partial Content"; + case 301: + return "Moved"; + case 302: + return "Found"; + case 400: + return "Bad Request"; + case 401: + return "Unauthorized"; + case 403: + return "Forbidden"; + case 404: + return "Not Found"; + case 416: + return "Requested Range Not Satisfiable"; + case 418: + return "I'm a teapot"; + case 500: + return "Internal Server Error"; + case 502: + return "Bad Gateway"; + case 503: + return "Service Unavailable"; + +#if MG_ENABLE_EXTRA_ERRORS_DESC + case 100: + return "Continue"; + case 101: + return "Switching Protocols"; + case 102: + return "Processing"; + case 200: + return "OK"; + case 201: + return "Created"; + case 202: + return "Accepted"; + case 203: + return "Non-Authoritative Information"; + case 204: + return "No Content"; + case 205: + return "Reset Content"; + case 207: + return "Multi-Status"; + case 208: + return "Already Reported"; + case 226: + return "IM Used"; + case 300: + return "Multiple Choices"; + case 303: + return "See Other"; + case 304: + return "Not Modified"; + case 305: + return "Use Proxy"; + case 306: + return "Switch Proxy"; + case 307: + return "Temporary Redirect"; + case 308: + return "Permanent Redirect"; + case 402: + return "Payment Required"; + case 405: + return "Method Not Allowed"; + case 406: + return "Not Acceptable"; + case 407: + return "Proxy Authentication Required"; + case 408: + return "Request Timeout"; + case 409: + return "Conflict"; + case 410: + return "Gone"; + case 411: + return "Length Required"; + case 412: + return "Precondition Failed"; + case 413: + return "Payload Too Large"; + case 414: + return "URI Too Long"; + case 415: + return "Unsupported Media Type"; + case 417: + return "Expectation Failed"; + case 422: + return "Unprocessable Entity"; + case 423: + return "Locked"; + case 424: + return "Failed Dependency"; + case 426: + return "Upgrade Required"; + case 428: + return "Precondition Required"; + case 429: + return "Too Many Requests"; + case 431: + return "Request Header Fields Too Large"; + case 451: + return "Unavailable For Legal Reasons"; + case 501: + return "Not Implemented"; + case 504: + return "Gateway Timeout"; + case 505: + return "HTTP Version Not Supported"; + case 506: + return "Variant Also Negotiates"; + case 507: + return "Insufficient Storage"; + case 508: + return "Loop Detected"; + case 510: + return "Not Extended"; + case 511: + return "Network Authentication Required"; +#endif /* MG_ENABLE_EXTRA_ERRORS_DESC */ + + default: + return "OK"; + } +} + +void mg_send_response_line_s(struct mg_connection *nc, int status_code, + const struct mg_str extra_headers) { + mg_printf(nc, "HTTP/1.1 %d %s\r\n", status_code, + mg_status_message(status_code)); +#ifndef MG_HIDE_SERVER_INFO + mg_printf(nc, "Server: %s\r\n", mg_version_header); +#endif + if (extra_headers.len > 0) { + mg_printf(nc, "%.*s\r\n", (int) extra_headers.len, extra_headers.p); + } +} + +void mg_send_response_line(struct mg_connection *nc, int status_code, + const char *extra_headers) { + mg_send_response_line_s(nc, status_code, mg_mk_str(extra_headers)); +} + +void mg_http_send_redirect(struct mg_connection *nc, int status_code, + const struct mg_str location, + const struct mg_str extra_headers) { + char bbody[100], *pbody = bbody; + int bl = mg_asprintf(&pbody, sizeof(bbody), + "

Moved here.\r\n", + (int) location.len, location.p); + char bhead[150], *phead = bhead; + mg_asprintf(&phead, sizeof(bhead), + "Location: %.*s\r\n" + "Content-Type: text/html\r\n" + "Content-Length: %d\r\n" + "Cache-Control: no-cache\r\n" + "%.*s%s", + (int) location.len, location.p, bl, (int) extra_headers.len, + extra_headers.p, (extra_headers.len > 0 ? "\r\n" : "")); + mg_send_response_line(nc, status_code, phead); + if (phead != bhead) MG_FREE(phead); + mg_send(nc, pbody, bl); + if (pbody != bbody) MG_FREE(pbody); +} + +void mg_send_head(struct mg_connection *c, int status_code, + int64_t content_length, const char *extra_headers) { + mg_send_response_line(c, status_code, extra_headers); + if (content_length < 0) { + mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n"); + } else { + mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length); + } + mg_send(c, "\r\n", 2); +} + +void mg_http_send_error(struct mg_connection *nc, int code, + const char *reason) { + if (!reason) reason = mg_status_message(code); + LOG(LL_DEBUG, ("%p %d %s", nc, code, reason)); + mg_send_head(nc, code, strlen(reason), + "Content-Type: text/plain\r\nConnection: close"); + mg_send(nc, reason, strlen(reason)); + nc->flags |= MG_F_SEND_AND_CLOSE; +} + +#if MG_ENABLE_FILESYSTEM +static void mg_http_construct_etag(char *buf, size_t buf_len, + const cs_stat_t *st) { + snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime, + (int64_t) st->st_size); +} + +#ifndef WINCE +static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) { + strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t)); +} +#else +/* Look wince_lib.c for WindowsCE implementation */ +static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t); +#endif + +static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a, + int64_t *b) { + /* + * There is no snscanf. Headers are not guaranteed to be NUL-terminated, + * so we have this. Ugh. + */ + int result; + char *p = (char *) MG_MALLOC(header->len + 1); + if (p == NULL) return 0; + memcpy(p, header->p, header->len); + p[header->len] = '\0'; + result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b); + MG_FREE(p); + return result; +} + +void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm, + const char *path, const struct mg_str mime_type, + const struct mg_str extra_headers) { + struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); + cs_stat_t st; + LOG(LL_DEBUG, ("%p [%s] %.*s", nc, path, (int) mime_type.len, mime_type.p)); + if (mg_stat(path, &st) != 0 || (pd->file.fp = mg_fopen(path, "rb")) == NULL) { + int code, err = mg_get_errno(); + switch (err) { + case EACCES: + code = 403; + break; + case ENOENT: + code = 404; + break; + default: + code = 500; + }; + mg_http_send_error(nc, code, "Open failed"); + } else { + char etag[50], current_time[50], last_modified[50], range[70]; + time_t t = (time_t) mg_time(); + int64_t r1 = 0, r2 = 0, cl = st.st_size; + struct mg_str *range_hdr = mg_get_http_header(hm, "Range"); + int n, status_code = 200; + + /* Handle Range header */ + range[0] = '\0'; + if (range_hdr != NULL && + (n = mg_http_parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 && + r2 >= 0) { + /* If range is specified like "400-", set second limit to content len */ + if (n == 1) { + r2 = cl - 1; + } + if (r1 > r2 || r2 >= cl) { + status_code = 416; + cl = 0; + snprintf(range, sizeof(range), + "Content-Range: bytes */%" INT64_FMT "\r\n", + (int64_t) st.st_size); + } else { + status_code = 206; + cl = r2 - r1 + 1; + snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT + "-%" INT64_FMT "/%" INT64_FMT "\r\n", + r1, r1 + cl - 1, (int64_t) st.st_size); +#if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \ + _XOPEN_SOURCE >= 600 + fseeko(pd->file.fp, r1, SEEK_SET); +#else + fseek(pd->file.fp, (long) r1, SEEK_SET); +#endif + } + } + +#if !MG_DISABLE_HTTP_KEEP_ALIVE + { + struct mg_str *conn_hdr = mg_get_http_header(hm, "Connection"); + if (conn_hdr != NULL) { + pd->file.keepalive = (mg_vcasecmp(conn_hdr, "keep-alive") == 0); + } else { + pd->file.keepalive = (mg_vcmp(&hm->proto, "HTTP/1.1") == 0); + } + } +#endif + + mg_http_construct_etag(etag, sizeof(etag), &st); + mg_gmt_time_string(current_time, sizeof(current_time), &t); + mg_gmt_time_string(last_modified, sizeof(last_modified), &st.st_mtime); + /* + * Content length casted to size_t because: + * 1) that's the maximum buffer size anyway + * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last + * position + * TODO(mkm): fix ESP8266 RTOS SDK + */ + mg_send_response_line_s(nc, status_code, extra_headers); + mg_printf(nc, + "Date: %s\r\n" + "Last-Modified: %s\r\n" + "Accept-Ranges: bytes\r\n" + "Content-Type: %.*s\r\n" + "Connection: %s\r\n" + "Content-Length: %" SIZE_T_FMT + "\r\n" + "%sEtag: %s\r\n\r\n", + current_time, last_modified, (int) mime_type.len, mime_type.p, + (pd->file.keepalive ? "keep-alive" : "close"), (size_t) cl, range, + etag); + + pd->file.cl = cl; + pd->file.type = DATA_FILE; + mg_http_transfer_file_data(nc); + } +} + +static void mg_http_serve_file2(struct mg_connection *nc, const char *path, + struct http_message *hm, + struct mg_serve_http_opts *opts) { +#if MG_ENABLE_HTTP_SSI + if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) { + mg_handle_ssi_request(nc, hm, path, opts); + return; + } +#endif + mg_http_serve_file(nc, hm, path, mg_get_mime_type(path, "text/plain", opts), + mg_mk_str(opts->extra_headers)); +} + +#endif + +int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, + int is_form_url_encoded) { + int i, j, a, b; +#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') + + for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) { + if (src[i] == '%') { + if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) && + isxdigit(*(const unsigned char *) (src + i + 2))) { + a = tolower(*(const unsigned char *) (src + i + 1)); + b = tolower(*(const unsigned char *) (src + i + 2)); + dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b)); + i += 2; + } else { + return -1; + } + } else if (is_form_url_encoded && src[i] == '+') { + dst[j] = ' '; + } else { + dst[j] = src[i]; + } + } + + dst[j] = '\0'; /* Null-terminate the destination */ + + return i >= src_len ? j : -1; +} + +int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst, + size_t dst_len) { + const char *p, *e, *s; + size_t name_len; + int len; + + /* + * According to the documentation function returns negative + * value in case of error. For debug purposes it returns: + * -1 - src is wrong (NUUL) + * -2 - dst is wrong (NULL) + * -3 - failed to decode url or dst is to small + * -4 - name does not exist + */ + if (dst == NULL || dst_len == 0) { + len = -2; + } else if (buf->p == NULL || name == NULL || buf->len == 0) { + len = -1; + dst[0] = '\0'; + } else { + name_len = strlen(name); + e = buf->p + buf->len; + len = -4; + dst[0] = '\0'; + + for (p = buf->p; p + name_len < e; p++) { + if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' && + !mg_ncasecmp(name, p, name_len)) { + p += name_len + 1; + s = (const char *) memchr(p, '&', (size_t)(e - p)); + if (s == NULL) { + s = e; + } + len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1); + /* -1 means: failed to decode or dst is too small */ + if (len == -1) { + len = -3; + } + break; + } + } + } + + return len; +} + +void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) { + char chunk_size[50]; + int n; + + n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len); + mg_send(nc, chunk_size, n); + mg_send(nc, buf, len); + mg_send(nc, "\r\n", 2); +} + +void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) { + char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; + int len; + va_list ap; + + va_start(ap, fmt); + len = mg_avprintf(&buf, sizeof(mem), fmt, ap); + va_end(ap); + + if (len >= 0) { + mg_send_http_chunk(nc, buf, len); + } + + /* LCOV_EXCL_START */ + if (buf != mem && buf != NULL) { + MG_FREE(buf); + } + /* LCOV_EXCL_STOP */ +} + +void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) { + char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; + int i, j, len; + va_list ap; + + va_start(ap, fmt); + len = mg_avprintf(&buf, sizeof(mem), fmt, ap); + va_end(ap); + + if (len >= 0) { + for (i = j = 0; i < len; i++) { + if (buf[i] == '<' || buf[i] == '>') { + mg_send(nc, buf + j, i - j); + mg_send(nc, buf[i] == '<' ? "<" : ">", 4); + j = i + 1; + } + } + mg_send(nc, buf + j, i - j); + } + + /* LCOV_EXCL_START */ + if (buf != mem && buf != NULL) { + MG_FREE(buf); + } + /* LCOV_EXCL_STOP */ +} + +static void mg_http_parse_header_internal(struct mg_str *hdr, + const char *var_name, + struct altbuf *ab) { + int ch = ' ', ch1 = ',', ch2 = ';', n = strlen(var_name); + const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL; + + /* Find where variable starts */ + for (s = hdr->p; s != NULL && s + n < end; s++) { + if ((s == hdr->p || s[-1] == ch || s[-1] == ch1 || s[-1] == ';') && + s[n] == '=' && !strncmp(s, var_name, n)) + break; + } + + if (s != NULL && &s[n + 1] < end) { + s += n + 1; + if (*s == '"' || *s == '\'') { + ch = ch1 = ch2 = *s++; + } + p = s; + while (p < end && p[0] != ch && p[0] != ch1 && p[0] != ch2) { + if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++; + altbuf_append(ab, *p++); + } + + if (ch != ' ' && *p != ch) { + altbuf_reset(ab); + } + } + + /* If there is some data, append a NUL. */ + if (ab->len > 0) { + altbuf_append(ab, '\0'); + } +} + +int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf, + size_t buf_size) { + struct altbuf ab; + altbuf_init(&ab, *buf, buf_size); + if (hdr == NULL) return 0; + if (*buf != NULL && buf_size > 0) *buf[0] = '\0'; + + mg_http_parse_header_internal(hdr, var_name, &ab); + + /* + * Get a (trimmed) buffer, and return a len without a NUL byte which might + * have been added. + */ + *buf = altbuf_get_buf(&ab, 1 /* trim */); + return ab.len > 0 ? ab.len - 1 : 0; +} + +int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf, + size_t buf_size) { + char *buf2 = buf; + + int len = mg_http_parse_header2(hdr, var_name, &buf2, buf_size); + + if (buf2 != buf) { + /* Buffer was not enough and was reallocated: free it and just return 0 */ + MG_FREE(buf2); + return 0; + } + + return len; +} + +int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len, + char *pass, size_t pass_len) { + struct mg_str *hdr = mg_get_http_header(hm, "Authorization"); + if (hdr == NULL) return -1; + return mg_parse_http_basic_auth(hdr, user, user_len, pass, pass_len); +} + +int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len, + char *pass, size_t pass_len) { + char *buf = NULL; + char fmt[64]; + int res = 0; + + if (mg_strncmp(*hdr, mg_mk_str("Basic "), 6) != 0) return -1; + + buf = (char *) MG_MALLOC(hdr->len); + cs_base64_decode((unsigned char *) hdr->p + 6, hdr->len, buf, NULL); + + /* e.g. "%123[^:]:%321[^\n]" */ + snprintf(fmt, sizeof(fmt), "%%%" SIZE_T_FMT "[^:]:%%%" SIZE_T_FMT "[^\n]", + user_len - 1, pass_len - 1); + if (sscanf(buf, fmt, user, pass) == 0) { + res = -1; + } + + MG_FREE(buf); + return res; +} + +#if MG_ENABLE_FILESYSTEM +static int mg_is_file_hidden(const char *path, + const struct mg_serve_http_opts *opts, + int exclude_specials) { + const char *p1 = opts->per_directory_auth_file; + const char *p2 = opts->hidden_file_pattern; + + /* Strip directory path from the file name */ + const char *pdir = strrchr(path, DIRSEP); + if (pdir != NULL) { + path = pdir + 1; + } + + return (exclude_specials && (!strcmp(path, ".") || !strcmp(path, ".."))) || + (p1 != NULL && mg_match_prefix(p1, strlen(p1), path) == strlen(p1)) || + (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0); +} + +#if !MG_DISABLE_HTTP_DIGEST_AUTH + +#ifndef MG_EXT_MD5 +void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[], + const size_t *msg_lens, uint8_t *digest) { + size_t i; + cs_md5_ctx md5_ctx; + cs_md5_init(&md5_ctx); + for (i = 0; i < num_msgs; i++) { + cs_md5_update(&md5_ctx, msgs[i], msg_lens[i]); + } + cs_md5_final(digest, &md5_ctx); +} +#else +extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[], + const size_t *msg_lens, uint8_t *digest); +#endif + +void cs_md5(char buf[33], ...) { + unsigned char hash[16]; + const uint8_t *msgs[20], *p; + size_t msg_lens[20]; + size_t num_msgs = 0; + va_list ap; + + va_start(ap, buf); + while ((p = va_arg(ap, const unsigned char *) ) != NULL) { + msgs[num_msgs] = p; + msg_lens[num_msgs] = va_arg(ap, size_t); + num_msgs++; + } + va_end(ap); + + mg_hash_md5_v(num_msgs, msgs, msg_lens, hash); + cs_to_hex(buf, hash, sizeof(hash)); +} + +static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri, + size_t uri_len, const char *ha1, size_t ha1_len, + const char *nonce, size_t nonce_len, const char *nc, + size_t nc_len, const char *cnonce, size_t cnonce_len, + const char *qop, size_t qop_len, char *resp) { + static const char colon[] = ":"; + static const size_t one = 1; + char ha2[33]; + cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL); + cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc, + nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len, + colon, one, ha2, sizeof(ha2) - 1, NULL); +} + +int mg_http_create_digest_auth_header(char *buf, size_t buf_len, + const char *method, const char *uri, + const char *auth_domain, const char *user, + const char *passwd, const char *nonce) { + static const char colon[] = ":", qop[] = "auth"; + static const size_t one = 1; + char ha1[33], resp[33], cnonce[40]; + + snprintf(cnonce, sizeof(cnonce), "%lx", (unsigned long) mg_time()); + cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain, + (size_t) strlen(auth_domain), colon, one, passwd, + (size_t) strlen(passwd), NULL); + mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1, + nonce, strlen(nonce), "1", one, cnonce, strlen(cnonce), qop, + sizeof(qop) - 1, resp); + return snprintf(buf, buf_len, + "Authorization: Digest username=\"%s\"," + "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s," + "nonce=%s,response=%s\r\n", + user, auth_domain, uri, qop, cnonce, nonce, resp); +} + +/* + * Check for authentication timeout. + * Clients send time stamp encoded in nonce. Make sure it is not too old, + * to prevent replay attacks. + * Assumption: nonce is a hexadecimal number of seconds since 1970. + */ +static int mg_check_nonce(const char *nonce) { + unsigned long now = (unsigned long) mg_time(); + unsigned long val = (unsigned long) strtoul(nonce, NULL, 16); + return (now >= val) && (now - val < 60 * 60); +} + +int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain, + FILE *fp) { + int ret = 0; + struct mg_str *hdr; + char username_buf[50], cnonce_buf[64], response_buf[40], uri_buf[200], + qop_buf[20], nc_buf[20], nonce_buf[16]; + + char *username = username_buf, *cnonce = cnonce_buf, *response = response_buf, + *uri = uri_buf, *qop = qop_buf, *nc = nc_buf, *nonce = nonce_buf; + + /* Parse "Authorization:" header, fail fast on parse error */ + if (hm == NULL || fp == NULL || + (hdr = mg_get_http_header(hm, "Authorization")) == NULL || + mg_http_parse_header2(hdr, "username", &username, sizeof(username_buf)) == + 0 || + mg_http_parse_header2(hdr, "cnonce", &cnonce, sizeof(cnonce_buf)) == 0 || + mg_http_parse_header2(hdr, "response", &response, sizeof(response_buf)) == + 0 || + mg_http_parse_header2(hdr, "uri", &uri, sizeof(uri_buf)) == 0 || + mg_http_parse_header2(hdr, "qop", &qop, sizeof(qop_buf)) == 0 || + mg_http_parse_header2(hdr, "nc", &nc, sizeof(nc_buf)) == 0 || + mg_http_parse_header2(hdr, "nonce", &nonce, sizeof(nonce_buf)) == 0 || + mg_check_nonce(nonce) == 0) { + ret = 0; + goto clean; + } + + /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */ + + ret = mg_check_digest_auth( + hm->method, + mg_mk_str_n( + hm->uri.p, + hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0)), + mg_mk_str(username), mg_mk_str(cnonce), mg_mk_str(response), + mg_mk_str(qop), mg_mk_str(nc), mg_mk_str(nonce), mg_mk_str(auth_domain), + fp); + +clean: + if (username != username_buf) MG_FREE(username); + if (cnonce != cnonce_buf) MG_FREE(cnonce); + if (response != response_buf) MG_FREE(response); + if (uri != uri_buf) MG_FREE(uri); + if (qop != qop_buf) MG_FREE(qop); + if (nc != nc_buf) MG_FREE(nc); + if (nonce != nonce_buf) MG_FREE(nonce); + + return ret; +} + +int mg_check_digest_auth(struct mg_str method, struct mg_str uri, + struct mg_str username, struct mg_str cnonce, + struct mg_str response, struct mg_str qop, + struct mg_str nc, struct mg_str nonce, + struct mg_str auth_domain, FILE *fp) { + char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)]; + char exp_resp[33]; + + /* + * Read passwords file line by line. If should have htdigest format, + * i.e. each line should be a colon-separated sequence: + * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD + */ + while (fgets(buf, sizeof(buf), fp) != NULL) { + if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 && + mg_vcmp(&username, f_user) == 0 && + mg_vcmp(&auth_domain, f_domain) == 0) { + /* Username and domain matched, check the password */ + mg_mkmd5resp(method.p, method.len, uri.p, uri.len, f_ha1, strlen(f_ha1), + nonce.p, nonce.len, nc.p, nc.len, cnonce.p, cnonce.len, + qop.p, qop.len, exp_resp); + LOG(LL_DEBUG, ("%.*s %s %.*s %s", (int) username.len, username.p, + f_domain, (int) response.len, response.p, exp_resp)); + return mg_ncasecmp(response.p, exp_resp, strlen(exp_resp)) == 0; + } + } + + /* None of the entries in the passwords file matched - return failure */ + return 0; +} + +int mg_http_is_authorized(struct http_message *hm, struct mg_str path, + const char *domain, const char *passwords_file, + int flags) { + char buf[MG_MAX_PATH]; + const char *p; + FILE *fp; + int authorized = 1; + + if (domain != NULL && passwords_file != NULL) { + if (flags & MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE) { + fp = mg_fopen(passwords_file, "r"); + } else if (flags & MG_AUTH_FLAG_IS_DIRECTORY) { + snprintf(buf, sizeof(buf), "%.*s%c%s", (int) path.len, path.p, DIRSEP, + passwords_file); + fp = mg_fopen(buf, "r"); + } else { + p = strrchr(path.p, DIRSEP); + if (p == NULL) p = path.p; + snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path.p), path.p, DIRSEP, + passwords_file); + fp = mg_fopen(buf, "r"); + } + + if (fp != NULL) { + authorized = mg_http_check_digest_auth(hm, domain, fp); + fclose(fp); + } else if (!(flags & MG_AUTH_FLAG_ALLOW_MISSING_FILE)) { + authorized = 0; + } + } + + LOG(LL_DEBUG, ("%.*s %s %x %d", (int) path.len, path.p, + passwords_file ? passwords_file : "", flags, authorized)); + return authorized; +} +#else +int mg_http_is_authorized(struct http_message *hm, const struct mg_str path, + const char *domain, const char *passwords_file, + int flags) { + (void) hm; + (void) path; + (void) domain; + (void) passwords_file; + (void) flags; + return 1; +} +#endif + +#if MG_ENABLE_DIRECTORY_LISTING +static void mg_escape(const char *src, char *dst, size_t dst_len) { + size_t n = 0; + while (*src != '\0' && n + 5 < dst_len) { + unsigned char ch = *(unsigned char *) src++; + if (ch == '<') { + n += snprintf(dst + n, dst_len - n, "%s", "<"); + } else { + dst[n++] = ch; + } + } + dst[n] = '\0'; +} + +static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name, + cs_stat_t *stp) { + char size[64], mod[64], path[MG_MAX_PATH]; + int64_t fsize = stp->st_size; + int is_dir = S_ISDIR(stp->st_mode); + const char *slash = is_dir ? "/" : ""; + struct mg_str href; + + if (is_dir) { + snprintf(size, sizeof(size), "%s", "[DIRECTORY]"); + } else { + /* + * We use (double) cast below because MSVC 6 compiler cannot + * convert unsigned __int64 to double. + */ + if (fsize < 1024) { + snprintf(size, sizeof(size), "%d", (int) fsize); + } else if (fsize < 0x100000) { + snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0); + } else if (fsize < 0x40000000) { + snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576); + } else { + snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824); + } + } + strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime)); + mg_escape(file_name, path, sizeof(path)); + href = mg_url_encode(mg_mk_str(file_name)); + mg_printf_http_chunk(nc, + "%s%s" + "%s%s\n", + href.p, slash, path, slash, mod, is_dir ? -1 : fsize, + size); + free((void *) href.p); +} + +static void mg_scan_directory(struct mg_connection *nc, const char *dir, + const struct mg_serve_http_opts *opts, + void (*func)(struct mg_connection *, const char *, + cs_stat_t *)) { + char path[MG_MAX_PATH + 1]; + cs_stat_t st; + struct dirent *dp; + DIR *dirp; + + LOG(LL_DEBUG, ("%p [%s]", nc, dir)); + if ((dirp = (opendir(dir))) != NULL) { + while ((dp = readdir(dirp)) != NULL) { + /* Do not show current dir and hidden files */ + if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) { + continue; + } + snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name); + if (mg_stat(path, &st) == 0) { + func(nc, (const char *) dp->d_name, &st); + } + } + closedir(dirp); + } else { + LOG(LL_DEBUG, ("%p opendir(%s) -> %d", nc, dir, mg_get_errno())); + } +} + +static void mg_send_directory_listing(struct mg_connection *nc, const char *dir, + struct http_message *hm, + struct mg_serve_http_opts *opts) { + static const char *sort_js_code = + ""; + + mg_send_response_line(nc, 200, opts->extra_headers); + mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked", + "Content-Type", "text/html; charset=utf-8"); + + mg_printf_http_chunk( + nc, + "Index of %.*s%s%s" + "\n" + "

Index of %.*s

\n" + "" + "\n" + "\n" + "", + (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2, + (int) hm->uri.len, hm->uri.p); + mg_scan_directory(nc, dir, opts, mg_print_dir_entry); + mg_printf_http_chunk(nc, + "\n" + "
Name" + "Modified" + "Size


\n" + "
%s
\n" + "", + mg_version_header); + mg_send_http_chunk(nc, "", 0); + /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */ + nc->flags |= MG_F_SEND_AND_CLOSE; +} +#endif /* MG_ENABLE_DIRECTORY_LISTING */ + +/* + * Given a directory path, find one of the files specified in the + * comma-separated list of index files `list`. + * First found index file wins. If an index file is found, then gets + * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`. + * If index file is not found, then `path` and `stp` remain unchanged. + */ +MG_INTERNAL void mg_find_index_file(const char *path, const char *list, + char **index_file, cs_stat_t *stp) { + struct mg_str vec; + size_t path_len = strlen(path); + int found = 0; + *index_file = NULL; + + /* Traverse index files list. For each entry, append it to the given */ + /* path and see if the file exists. If it exists, break the loop */ + while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) { + cs_stat_t st; + size_t len = path_len + 1 + vec.len + 1; + *index_file = (char *) MG_REALLOC(*index_file, len); + if (*index_file == NULL) break; + snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p); + + /* Does it exist? Is it a file? */ + if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) { + /* Yes it does, break the loop */ + *stp = st; + found = 1; + break; + } + } + if (!found) { + MG_FREE(*index_file); + *index_file = NULL; + } + LOG(LL_DEBUG, ("[%s] [%s]", path, (*index_file ? *index_file : ""))); +} + +#if MG_ENABLE_HTTP_URL_REWRITES +static int mg_http_send_port_based_redirect( + struct mg_connection *c, struct http_message *hm, + const struct mg_serve_http_opts *opts) { + const char *rewrites = opts->url_rewrites; + struct mg_str a, b; + char local_port[20] = {'%'}; + + mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1, + MG_SOCK_STRINGIFY_PORT); + + while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { + if (mg_vcmp(&a, local_port) == 0) { + mg_send_response_line(c, 301, NULL); + mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n", + (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1), + hm->uri.p); + return 1; + } + } + + return 0; +} + +static void mg_reverse_proxy_handler(struct mg_connection *nc, int ev, + void *ev_data MG_UD_ARG(void *user_data)) { + struct http_message *hm = (struct http_message *) ev_data; + struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); + + if (pd == NULL || pd->reverse_proxy_data.linked_conn == NULL) { + DBG(("%p: upstream closed", nc)); + return; + } + + switch (ev) { + case MG_EV_CONNECT: + if (*(int *) ev_data != 0) { + mg_http_send_error(pd->reverse_proxy_data.linked_conn, 502, NULL); + } + break; + /* TODO(mkm): handle streaming */ + case MG_EV_HTTP_REPLY: + mg_send(pd->reverse_proxy_data.linked_conn, hm->message.p, + hm->message.len); + pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE; + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + break; + case MG_EV_CLOSE: + pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE; + break; + } + +#if MG_ENABLE_CALLBACK_USERDATA + (void) user_data; +#endif +} + +void mg_http_reverse_proxy(struct mg_connection *nc, + const struct http_message *hm, struct mg_str mount, + struct mg_str upstream) { + struct mg_connection *be; + char burl[256], *purl = burl; + int i; + const char *error; + struct mg_connect_opts opts; + struct mg_str path = MG_NULL_STR, user_info = MG_NULL_STR, host = MG_NULL_STR; + memset(&opts, 0, sizeof(opts)); + opts.error_string = &error; + + mg_asprintf(&purl, sizeof(burl), "%.*s%.*s", (int) upstream.len, upstream.p, + (int) (hm->uri.len - mount.len), hm->uri.p + mount.len); + + be = mg_connect_http_base(nc->mgr, MG_CB(mg_reverse_proxy_handler, NULL), + opts, "http", NULL, "https", NULL, purl, &path, + &user_info, &host); + LOG(LL_DEBUG, ("Proxying %.*s to %s (rule: %.*s)", (int) hm->uri.len, + hm->uri.p, purl, (int) mount.len, mount.p)); + + if (be == NULL) { + LOG(LL_ERROR, ("Error connecting to %s: %s", purl, error)); + mg_http_send_error(nc, 502, NULL); + goto cleanup; + } + + /* link connections to each other, they must live and die together */ + mg_http_get_proto_data(be)->reverse_proxy_data.linked_conn = nc; + mg_http_get_proto_data(nc)->reverse_proxy_data.linked_conn = be; + + /* send request upstream */ + mg_printf(be, "%.*s %.*s HTTP/1.1\r\n", (int) hm->method.len, hm->method.p, + (int) path.len, path.p); + + mg_printf(be, "Host: %.*s\r\n", (int) host.len, host.p); + for (i = 0; i < MG_MAX_HTTP_HEADERS && hm->header_names[i].len > 0; i++) { + struct mg_str hn = hm->header_names[i]; + struct mg_str hv = hm->header_values[i]; + + /* we rewrite the host header */ + if (mg_vcasecmp(&hn, "Host") == 0) continue; + /* + * Don't pass chunked transfer encoding to the client because hm->body is + * already dechunked when we arrive here. + */ + if (mg_vcasecmp(&hn, "Transfer-encoding") == 0 && + mg_vcasecmp(&hv, "chunked") == 0) { + mg_printf(be, "Content-Length: %" SIZE_T_FMT "\r\n", hm->body.len); + continue; + } + /* We don't support proxying Expect: 100-continue. */ + if (mg_vcasecmp(&hn, "Expect") == 0 && + mg_vcasecmp(&hv, "100-continue") == 0) { + continue; + } + + mg_printf(be, "%.*s: %.*s\r\n", (int) hn.len, hn.p, (int) hv.len, hv.p); + } + + mg_send(be, "\r\n", 2); + mg_send(be, hm->body.p, hm->body.len); + +cleanup: + if (purl != burl) MG_FREE(purl); +} + +static int mg_http_handle_forwarding(struct mg_connection *nc, + struct http_message *hm, + const struct mg_serve_http_opts *opts) { + const char *rewrites = opts->url_rewrites; + struct mg_str a, b; + struct mg_str p1 = MG_MK_STR("http://"), p2 = MG_MK_STR("https://"); + + while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { + if (mg_strncmp(a, hm->uri, a.len) == 0) { + if (mg_strncmp(b, p1, p1.len) == 0 || mg_strncmp(b, p2, p2.len) == 0) { + mg_http_reverse_proxy(nc, hm, a, b); + return 1; + } + } + } + + return 0; +} +#endif /* MG_ENABLE_FILESYSTEM */ + +MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm, + const struct mg_serve_http_opts *opts, + char **local_path, + struct mg_str *remainder) { + int ok = 1; + const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len; + struct mg_str root = {NULL, 0}; + const char *file_uri_start = cp; + *local_path = NULL; + remainder->p = NULL; + remainder->len = 0; + + { /* 1. Determine which root to use. */ + +#if MG_ENABLE_HTTP_URL_REWRITES + const char *rewrites = opts->url_rewrites; +#else + const char *rewrites = ""; +#endif + struct mg_str *hh = mg_get_http_header(hm, "Host"); + struct mg_str a, b; + /* Check rewrites first. */ + while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { + if (a.len > 1 && a.p[0] == '@') { + /* Host rewrite. */ + if (hh != NULL && hh->len == a.len - 1 && + mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) { + root = b; + break; + } + } else { + /* Regular rewrite, URI=directory */ + size_t match_len = mg_match_prefix_n(a, hm->uri); + if (match_len > 0) { + file_uri_start = hm->uri.p + match_len; + if (*file_uri_start == '/' || file_uri_start == cp_end) { + /* Match ended at component boundary, ok. */ + } else if (*(file_uri_start - 1) == '/') { + /* Pattern ends with '/', backtrack. */ + file_uri_start--; + } else { + /* No match: must fall on the component boundary. */ + continue; + } + root = b; + break; + } + } + } + /* If no rewrite rules matched, use DAV or regular document root. */ + if (root.p == NULL) { +#if MG_ENABLE_HTTP_WEBDAV + if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) { + root.p = opts->dav_document_root; + root.len = strlen(opts->dav_document_root); + } else +#endif + { + root.p = opts->document_root; + root.len = strlen(opts->document_root); + } + } + assert(root.p != NULL && root.len > 0); + } + + { /* 2. Find where in the canonical URI path the local path ends. */ + const char *u = file_uri_start + 1; + char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1); + char *lp_end = lp + root.len + hm->uri.len + 1; + char *p = lp, *ps; + int exists = 1; + if (lp == NULL) { + ok = 0; + goto out; + } + memcpy(p, root.p, root.len); + p += root.len; + if (*(p - 1) == DIRSEP) p--; + *p = '\0'; + ps = p; + + /* Chop off URI path components one by one and build local path. */ + while (u <= cp_end) { + const char *next = u; + struct mg_str component; + if (exists) { + cs_stat_t st; + exists = (mg_stat(lp, &st) == 0); + if (exists && S_ISREG(st.st_mode)) { + /* We found the terminal, the rest of the URI (if any) is path_info. + */ + if (*(u - 1) == '/') u--; + break; + } + } + if (u >= cp_end) break; + parse_uri_component((const char **) &next, cp_end, "/", &component); + if (component.len > 0) { + int len; + memmove(p + 1, component.p, component.len); + len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0); + if (len <= 0) { + ok = 0; + break; + } + component.p = p + 1; + component.len = len; + if (mg_vcmp(&component, ".") == 0) { + /* Yum. */ + } else if (mg_vcmp(&component, "..") == 0) { + while (p > ps && *p != DIRSEP) p--; + *p = '\0'; + } else { + size_t i; +#ifdef _WIN32 + /* On Windows, make sure it's valid Unicode (no funny stuff). */ + wchar_t buf[MG_MAX_PATH * 2]; + if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) { + DBG(("[%.*s] smells funny", (int) component.len, component.p)); + ok = 0; + break; + } +#endif + *p++ = DIRSEP; + /* No NULs and DIRSEPs in the component (percent-encoded). */ + for (i = 0; i < component.len; i++, p++) { + if (*p == '\0' || *p == DIRSEP +#ifdef _WIN32 + /* On Windows, "/" is also accepted, so check for that too. */ + || + *p == '/' +#endif + ) { + ok = 0; + break; + } + } + } + } + u = next; + } + if (ok) { + *local_path = lp; + if (u > cp_end) u = cp_end; + remainder->p = u; + remainder->len = cp_end - u; + } else { + MG_FREE(lp); + } + } + +out: + LOG(LL_DEBUG, + ("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p, + *local_path ? *local_path : "", (int) remainder->len, remainder->p)); + return ok; +} + +static int mg_get_month_index(const char *s) { + static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; + size_t i; + + for (i = 0; i < ARRAY_SIZE(month_names); i++) + if (!strcmp(s, month_names[i])) return (int) i; + + return -1; +} + +static int mg_num_leap_years(int year) { + return year / 4 - year / 100 + year / 400; +} + +/* Parse UTC date-time string, and return the corresponding time_t value. */ +MG_INTERNAL time_t mg_parse_date_string(const char *datetime) { + static const unsigned short days_before_month[] = { + 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; + char month_str[32]; + int second, minute, hour, day, month, year, leap_days, days; + time_t result = (time_t) 0; + + if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour, + &minute, &second) == 6) || + (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour, + &minute, &second) == 6) || + (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year, + &hour, &minute, &second) == 6) || + (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour, + &minute, &second) == 6)) && + year > 1970 && (month = mg_get_month_index(month_str)) != -1) { + leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970); + year -= 1970; + days = year * 365 + days_before_month[month] + (day - 1) + leap_days; + result = days * 24 * 3600 + hour * 3600 + minute * 60 + second; + } + + return result; +} + +MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) { + struct mg_str *hdr; + if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) { + char etag[64]; + mg_http_construct_etag(etag, sizeof(etag), st); + return mg_vcasecmp(hdr, etag) == 0; + } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) { + return st->st_mtime <= mg_parse_date_string(hdr->p); + } else { + return 0; + } +} + +void mg_http_send_digest_auth_request(struct mg_connection *c, + const char *domain) { + mg_printf(c, + "HTTP/1.1 401 Unauthorized\r\n" + "WWW-Authenticate: Digest qop=\"auth\", " + "realm=\"%s\", nonce=\"%lx\"\r\n" + "Content-Length: 0\r\n\r\n", + domain, (unsigned long) mg_time()); +} + +static void mg_http_send_options(struct mg_connection *nc, + struct mg_serve_http_opts *opts) { + mg_send_response_line(nc, 200, opts->extra_headers); + mg_printf(nc, "%s", + "Allow: GET, POST, HEAD, CONNECT, OPTIONS" +#if MG_ENABLE_HTTP_WEBDAV + ", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2" +#endif + "\r\n\r\n"); + nc->flags |= MG_F_SEND_AND_CLOSE; +} + +static int mg_is_creation_request(const struct http_message *hm) { + return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0; +} + +MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path, + const struct mg_str *path_info, + struct http_message *hm, + struct mg_serve_http_opts *opts) { + int exists, is_directory, is_cgi; +#if MG_ENABLE_HTTP_WEBDAV + int is_dav = mg_is_dav_request(&hm->method); +#else + int is_dav = 0; +#endif + char *index_file = NULL; + cs_stat_t st; + + exists = (mg_stat(path, &st) == 0); + is_directory = exists && S_ISDIR(st.st_mode); + + if (is_directory) + mg_find_index_file(path, opts->index_files, &index_file, &st); + + is_cgi = + (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern), + index_file ? index_file : path) > 0); + + LOG(LL_DEBUG, + ("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc, + (int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav, + is_cgi, index_file ? index_file : "")); + + if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) { + mg_printf(nc, + "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n" + "Content-Length: 0\r\n\r\n", + (int) hm->uri.len, hm->uri.p); + MG_FREE(index_file); + return; + } + + /* If we have path_info, the only way to handle it is CGI. */ + if (path_info->len > 0 && !is_cgi) { + mg_http_send_error(nc, 501, NULL); + MG_FREE(index_file); + return; + } + + if (is_dav && opts->dav_document_root == NULL) { + mg_http_send_error(nc, 501, NULL); + } else if (!mg_http_is_authorized( + hm, mg_mk_str(path), opts->auth_domain, opts->global_auth_file, + ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | + MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE | + MG_AUTH_FLAG_ALLOW_MISSING_FILE)) || + !mg_http_is_authorized( + hm, mg_mk_str(path), opts->auth_domain, + opts->per_directory_auth_file, + ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | + MG_AUTH_FLAG_ALLOW_MISSING_FILE))) { + mg_http_send_digest_auth_request(nc, opts->auth_domain); + } else if (is_cgi) { +#if MG_ENABLE_HTTP_CGI + mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts); +#else + mg_http_send_error(nc, 501, NULL); +#endif /* MG_ENABLE_HTTP_CGI */ + } else if ((!exists || + mg_is_file_hidden(path, opts, 0 /* specials are ok */)) && + !mg_is_creation_request(hm)) { + mg_http_send_error(nc, 404, NULL); +#if MG_ENABLE_HTTP_WEBDAV + } else if (!mg_vcmp(&hm->method, "PROPFIND")) { + mg_handle_propfind(nc, path, &st, hm, opts); +#if !MG_DISABLE_DAV_AUTH + } else if (is_dav && + (opts->dav_auth_file == NULL || + (strcmp(opts->dav_auth_file, "-") != 0 && + !mg_http_is_authorized( + hm, mg_mk_str(path), opts->auth_domain, opts->dav_auth_file, + ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | + MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE | + MG_AUTH_FLAG_ALLOW_MISSING_FILE))))) { + mg_http_send_digest_auth_request(nc, opts->auth_domain); +#endif + } else if (!mg_vcmp(&hm->method, "MKCOL")) { + mg_handle_mkcol(nc, path, hm); + } else if (!mg_vcmp(&hm->method, "DELETE")) { + mg_handle_delete(nc, opts, path); + } else if (!mg_vcmp(&hm->method, "PUT")) { + mg_handle_put(nc, path, hm); + } else if (!mg_vcmp(&hm->method, "MOVE")) { + mg_handle_move(nc, opts, path, hm); +#if MG_ENABLE_FAKE_DAVLOCK + } else if (!mg_vcmp(&hm->method, "LOCK")) { + mg_handle_lock(nc, path); +#endif +#endif /* MG_ENABLE_HTTP_WEBDAV */ + } else if (!mg_vcmp(&hm->method, "OPTIONS")) { + mg_http_send_options(nc, opts); + } else if (is_directory && index_file == NULL) { +#if MG_ENABLE_DIRECTORY_LISTING + if (strcmp(opts->enable_directory_listing, "yes") == 0) { + mg_send_directory_listing(nc, path, hm, opts); + } else { + mg_http_send_error(nc, 403, NULL); + } +#else + mg_http_send_error(nc, 501, NULL); +#endif + } else if (mg_is_not_modified(hm, &st)) { + mg_http_send_error(nc, 304, "Not Modified"); + } else { + mg_http_serve_file2(nc, index_file ? index_file : path, hm, opts); + } + MG_FREE(index_file); +} + +void mg_serve_http(struct mg_connection *nc, struct http_message *hm, + struct mg_serve_http_opts opts) { + char *path = NULL; + struct mg_str *hdr, path_info; + uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr); + + if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) { + /* Not allowed to connect */ + mg_http_send_error(nc, 403, NULL); + nc->flags |= MG_F_SEND_AND_CLOSE; + return; + } + +#if MG_ENABLE_HTTP_URL_REWRITES + if (mg_http_handle_forwarding(nc, hm, &opts)) { + return; + } + + if (mg_http_send_port_based_redirect(nc, hm, &opts)) { + return; + } +#endif + + if (opts.document_root == NULL) { + opts.document_root = "."; + } + if (opts.per_directory_auth_file == NULL) { + opts.per_directory_auth_file = ".htpasswd"; + } + if (opts.enable_directory_listing == NULL) { + opts.enable_directory_listing = "yes"; + } + if (opts.cgi_file_pattern == NULL) { + opts.cgi_file_pattern = "**.cgi$|**.php$"; + } + if (opts.ssi_pattern == NULL) { + opts.ssi_pattern = "**.shtml$|**.shtm$"; + } + if (opts.index_files == NULL) { + opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php"; + } + /* Normalize path - resolve "." and ".." (in-place). */ + if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) { + mg_http_send_error(nc, 400, NULL); + return; + } + if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) { + mg_http_send_error(nc, 404, NULL); + return; + } + mg_send_http_file(nc, path, &path_info, hm, &opts); + + MG_FREE(path); + path = NULL; + + /* Close connection for non-keep-alive requests */ + if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 || + ((hdr = mg_get_http_header(hm, "Connection")) != NULL && + mg_vcmp(hdr, "keep-alive") != 0)) { +#if 0 + nc->flags |= MG_F_SEND_AND_CLOSE; +#endif + } +} + +#if MG_ENABLE_HTTP_STREAMING_MULTIPART +void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data, + mg_fu_fname_fn local_name_fn + MG_UD_ARG(void *user_data)) { + switch (ev) { + case MG_EV_HTTP_PART_BEGIN: { + struct mg_http_multipart_part *mp = + (struct mg_http_multipart_part *) ev_data; + struct file_upload_state *fus; + struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name)); + mp->user_data = NULL; + if (lfn.p == NULL || lfn.len == 0) { + LOG(LL_ERROR, ("%p Not allowed to upload %s", nc, mp->file_name)); + mg_printf(nc, + "HTTP/1.1 403 Not Allowed\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n\r\n" + "Not allowed to upload %s\r\n", + mp->file_name); + nc->flags |= MG_F_SEND_AND_CLOSE; + return; + } + fus = (struct file_upload_state *) MG_CALLOC(1, sizeof(*fus)); + if (fus == NULL) { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + return; + } + fus->lfn = (char *) MG_MALLOC(lfn.len + 1); + memcpy(fus->lfn, lfn.p, lfn.len); + fus->lfn[lfn.len] = '\0'; + if (lfn.p != mp->file_name) MG_FREE((char *) lfn.p); + LOG(LL_DEBUG, + ("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn)); + fus->fp = mg_fopen(fus->lfn, "wb"); + if (fus->fp == NULL) { + mg_printf(nc, + "HTTP/1.1 500 Internal Server Error\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n\r\n"); + LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, mg_get_errno())); + mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, mg_get_errno()); + /* Do not close the connection just yet, discard remainder of the data. + * This is because at the time of writing some browsers (Chrome) fail to + * render response before all the data is sent. */ + } + mp->user_data = (void *) fus; + break; + } + case MG_EV_HTTP_PART_DATA: { + struct mg_http_multipart_part *mp = + (struct mg_http_multipart_part *) ev_data; + struct file_upload_state *fus = + (struct file_upload_state *) mp->user_data; + if (fus == NULL || fus->fp == NULL) break; + if (mg_fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) { + LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn, + mg_get_errno(), (int) fus->num_recd)); + if (mg_get_errno() == ENOSPC +#ifdef SPIFFS_ERR_FULL + || mg_get_errno() == SPIFFS_ERR_FULL +#endif + ) { + mg_printf(nc, + "HTTP/1.1 413 Payload Too Large\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n\r\n"); + mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n", + fus->lfn, (int) fus->num_recd); + } else { + mg_printf(nc, + "HTTP/1.1 500 Internal Server Error\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n\r\n"); + mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name, + mg_get_errno(), (int) fus->num_recd); + } + fclose(fus->fp); + remove(fus->lfn); + fus->fp = NULL; + /* Do not close the connection just yet, discard remainder of the data. + * This is because at the time of writing some browsers (Chrome) fail to + * render response before all the data is sent. */ + return; + } + fus->num_recd += mp->data.len; + LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", nc, (int) mp->data.len, + (int) fus->num_recd)); + break; + } + case MG_EV_HTTP_PART_END: { + struct mg_http_multipart_part *mp = + (struct mg_http_multipart_part *) ev_data; + struct file_upload_state *fus = + (struct file_upload_state *) mp->user_data; + if (fus == NULL) break; + if (mp->status >= 0 && fus->fp != NULL) { + LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", nc, mp->file_name, + fus->lfn, (int) fus->num_recd)); + } else { + LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn)); + /* + * mp->status < 0 means connection was terminated, so no reason to send + * HTTP reply + */ + } + if (fus->fp != NULL) fclose(fus->fp); + MG_FREE(fus->lfn); + MG_FREE(fus); + mp->user_data = NULL; + /* Don't close the connection yet, there may be more files to come. */ + break; + } + case MG_EV_HTTP_MULTIPART_REQUEST_END: { + mg_printf(nc, + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n\r\n" + "Ok.\r\n"); + nc->flags |= MG_F_SEND_AND_CLOSE; + break; + } + } + +#if MG_ENABLE_CALLBACK_USERDATA + (void) user_data; +#endif +} + +#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ +#endif /* MG_ENABLE_FILESYSTEM */ + +struct mg_connection *mg_connect_http_base( + struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), + struct mg_connect_opts opts, const char *scheme1, const char *scheme2, + const char *scheme_ssl1, const char *scheme_ssl2, const char *url, + struct mg_str *path, struct mg_str *user_info, struct mg_str *host) { + struct mg_connection *nc = NULL; + unsigned int port_i = 0; + int use_ssl = 0; + struct mg_str scheme, query, fragment; + char conn_addr_buf[2]; + char *conn_addr = conn_addr_buf; + + if (mg_parse_uri(mg_mk_str(url), &scheme, user_info, host, &port_i, path, + &query, &fragment) != 0) { + MG_SET_PTRPTR(opts.error_string, "cannot parse url"); + goto out; + } + + /* If query is present, do not strip it. Pass to the caller. */ + if (query.len > 0) path->len += query.len + 1; + + if (scheme.len == 0 || mg_vcmp(&scheme, scheme1) == 0 || + (scheme2 != NULL && mg_vcmp(&scheme, scheme2) == 0)) { + use_ssl = 0; + if (port_i == 0) port_i = 80; + } else if (mg_vcmp(&scheme, scheme_ssl1) == 0 || + (scheme2 != NULL && mg_vcmp(&scheme, scheme_ssl2) == 0)) { + use_ssl = 1; + if (port_i == 0) port_i = 443; + } else { + goto out; + } + + mg_asprintf(&conn_addr, sizeof(conn_addr_buf), "tcp://%.*s:%u", + (int) host->len, host->p, port_i); + if (conn_addr == NULL) goto out; + + LOG(LL_DEBUG, ("%s use_ssl? %d %s", url, use_ssl, conn_addr)); + if (use_ssl) { +#if MG_ENABLE_SSL + /* + * Schema requires SSL, but no SSL parameters were provided in opts. + * In order to maintain backward compatibility, use a faux-SSL with no + * verification. + */ + if (opts.ssl_ca_cert == NULL) { + opts.ssl_ca_cert = "*"; + } +#else + MG_SET_PTRPTR(opts.error_string, "ssl is disabled"); + goto out; +#endif + } + + if ((nc = mg_connect_opt(mgr, conn_addr, MG_CB(ev_handler, user_data), + opts)) != NULL) { + mg_set_protocol_http_websocket(nc); + } + +out: + if (conn_addr != NULL && conn_addr != conn_addr_buf) MG_FREE(conn_addr); + return nc; +} + +struct mg_connection *mg_connect_http_opt( + struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), + struct mg_connect_opts opts, const char *url, const char *extra_headers, + const char *post_data) { + struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR; + struct mg_str host = MG_NULL_STR, path = MG_NULL_STR; + struct mbuf auth; + struct mg_connection *nc = + mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http", + NULL, "https", NULL, url, &path, &user, &host); + + if (nc == NULL) { + return NULL; + } + + mbuf_init(&auth, 0); + if (user.len > 0) { + mg_basic_auth_header(user, null_str, &auth); + } + + if (post_data == NULL) post_data = ""; + if (extra_headers == NULL) extra_headers = ""; + if (path.len == 0) path = mg_mk_str("/"); + if (host.len == 0) host = mg_mk_str(""); + + mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT + "\r\n%.*s%s\r\n%s", + (post_data[0] == '\0' ? "GET" : "POST"), (int) path.len, path.p, + (int) (path.p - host.p), host.p, strlen(post_data), (int) auth.len, + (auth.buf == NULL ? "" : auth.buf), extra_headers, post_data); + + mbuf_free(&auth); + return nc; +} + +struct mg_connection *mg_connect_http( + struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), + const char *url, const char *extra_headers, const char *post_data) { + struct mg_connect_opts opts; + memset(&opts, 0, sizeof(opts)); + return mg_connect_http_opt(mgr, MG_CB(ev_handler, user_data), opts, url, + extra_headers, post_data); +} + +size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name, + size_t var_name_len, char *file_name, + size_t file_name_len, const char **data, + size_t *data_len) { + static const char cd[] = "Content-Disposition: "; + size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1; + int shl; + + if (buf == NULL || buf_len <= 0) return 0; + if ((shl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0; + hl = shl; + if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0; + + /* Get boundary length */ + bl = mg_get_line_len(buf, buf_len); + + /* Loop through headers, fetch variable name and file name */ + var_name[0] = file_name[0] = '\0'; + for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) { + if (mg_ncasecmp(cd, buf + n, cdl) == 0) { + struct mg_str header; + header.p = buf + n + cdl; + header.len = ll - (cdl + 2); + { + char *var_name2 = var_name; + mg_http_parse_header2(&header, "name", &var_name2, var_name_len); + /* TODO: handle reallocated buffer correctly */ + if (var_name2 != var_name) { + MG_FREE(var_name2); + var_name[0] = '\0'; + } + } + { + char *file_name2 = file_name; + mg_http_parse_header2(&header, "filename", &file_name2, file_name_len); + /* TODO: handle reallocated buffer correctly */ + if (file_name2 != file_name) { + MG_FREE(file_name2); + file_name[0] = '\0'; + } + } + } + } + + /* Scan through the body, search for terminating boundary */ + for (pos = hl; pos + (bl - 2) < buf_len; pos++) { + if (buf[pos] == '-' && !strncmp(buf, &buf[pos], bl - 2)) { + if (data_len != NULL) *data_len = (pos - 2) - hl; + if (data != NULL) *data = buf + hl; + return pos; + } + } + + return 0; +} + +void mg_register_http_endpoint_opt(struct mg_connection *nc, + const char *uri_path, + mg_event_handler_t handler, + struct mg_http_endpoint_opts opts) { + struct mg_http_proto_data *pd = NULL; + struct mg_http_endpoint *new_ep = NULL; + + if (nc == NULL) return; + new_ep = (struct mg_http_endpoint *) MG_CALLOC(1, sizeof(*new_ep)); + if (new_ep == NULL) return; + + pd = mg_http_get_proto_data(nc); + new_ep->uri_pattern = mg_strdup(mg_mk_str(uri_path)); + if (opts.auth_domain != NULL && opts.auth_file != NULL) { + new_ep->auth_domain = strdup(opts.auth_domain); + new_ep->auth_file = strdup(opts.auth_file); + } + new_ep->handler = handler; +#if MG_ENABLE_CALLBACK_USERDATA + new_ep->user_data = opts.user_data; +#endif + new_ep->next = pd->endpoints; + pd->endpoints = new_ep; +} + +static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev, + struct http_message *hm) { + struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); + void *user_data = nc->user_data; + + if (ev == MG_EV_HTTP_REQUEST +#if MG_ENABLE_HTTP_STREAMING_MULTIPART + || ev == MG_EV_HTTP_MULTIPART_REQUEST +#endif + ) { + struct mg_http_endpoint *ep = + mg_http_get_endpoint_handler(nc->listener, &hm->uri); + if (ep != NULL) { +#if MG_ENABLE_FILESYSTEM && !MG_DISABLE_HTTP_DIGEST_AUTH + if (!mg_http_is_authorized(hm, hm->uri, ep->auth_domain, ep->auth_file, + MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE)) { + mg_http_send_digest_auth_request(nc, ep->auth_domain); + return; + } +#endif + pd->endpoint_handler = ep->handler; +#if MG_ENABLE_CALLBACK_USERDATA + user_data = ep->user_data; +#endif + } + } + mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler, + user_data, ev, hm); +} + +void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path, + MG_CB(mg_event_handler_t handler, + void *user_data)) { + struct mg_http_endpoint_opts opts; + memset(&opts, 0, sizeof(opts)); +#if MG_ENABLE_CALLBACK_USERDATA + opts.user_data = user_data; +#endif + mg_register_http_endpoint_opt(nc, uri_path, handler, opts); +} + +#endif /* MG_ENABLE_HTTP */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_http_cgi.c" +#endif +/* + * Copyright (c) 2014-2016 Cesanta Software Limited + * All rights reserved + */ + +#ifndef _WIN32 +#include +#endif + +#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI + +#ifndef MG_MAX_CGI_ENVIR_VARS +#define MG_MAX_CGI_ENVIR_VARS 64 +#endif + +#ifndef MG_ENV_EXPORT_TO_CGI +#define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI" +#endif + +#define MG_F_HTTP_CGI_PARSE_HEADERS MG_F_USER_1 + +/* + * This structure helps to create an environment for the spawned CGI program. + * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings, + * last element must be NULL. + * However, on Windows there is a requirement that all these VARIABLE=VALUE\0 + * strings must reside in a contiguous buffer. The end of the buffer is + * marked by two '\0' characters. + * We satisfy both worlds: we create an envp array (which is vars), all + * entries are actually pointers inside buf. + */ +struct mg_cgi_env_block { + struct mg_connection *nc; + char buf[MG_CGI_ENVIRONMENT_SIZE]; /* Environment buffer */ + const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */ + int len; /* Space taken */ + int nvars; /* Number of variables in envp[] */ +}; + +#ifdef _WIN32 +struct mg_threadparam { + sock_t s; + HANDLE hPipe; +}; + +static int mg_wait_until_ready(sock_t sock, int for_read) { + fd_set set; + FD_ZERO(&set); + FD_SET(sock, &set); + return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1; +} + +static void *mg_push_to_stdin(void *arg) { + struct mg_threadparam *tp = (struct mg_threadparam *) arg; + int n, sent, stop = 0; + DWORD k; + char buf[BUFSIZ]; + + while (!stop && mg_wait_until_ready(tp->s, 1) && + (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) { + if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue; + for (sent = 0; !stop && sent < n; sent += k) { + if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1; + } + } + DBG(("%s", "FORWARED EVERYTHING TO CGI")); + CloseHandle(tp->hPipe); + MG_FREE(tp); + return NULL; +} + +static void *mg_pull_from_stdout(void *arg) { + struct mg_threadparam *tp = (struct mg_threadparam *) arg; + int k = 0, stop = 0; + DWORD n, sent; + char buf[BUFSIZ]; + + while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) { + for (sent = 0; !stop && sent < n; sent += k) { + if (mg_wait_until_ready(tp->s, 0) && + (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) + stop = 1; + } + } + DBG(("%s", "EOF FROM CGI")); + CloseHandle(tp->hPipe); + shutdown(tp->s, 2); // Without this, IO thread may get truncated data + closesocket(tp->s); + MG_FREE(tp); + return NULL; +} + +static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe, + void *(*func)(void *)) { + struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp)); + if (tp != NULL) { + tp->s = sock; + tp->hPipe = hPipe; + mg_start_thread(func, tp); + } +} + +static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) { + wchar_t buf[MG_MAX_PATH], buf2[MG_MAX_PATH]; + to_wchar(utf8_path, buf, ARRAY_SIZE(buf)); + GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL); + WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0); +} + +static int mg_start_process(const char *interp, const char *cmd, + const char *env, const char *envp[], + const char *dir, sock_t sock) { + STARTUPINFOW si; + PROCESS_INFORMATION pi; + HANDLE a[2], b[2], me = GetCurrentProcess(); + wchar_t wcmd[MG_MAX_PATH], full_dir[MG_MAX_PATH]; + char buf[MG_MAX_PATH], buf2[MG_MAX_PATH], buf5[MG_MAX_PATH], + buf4[MG_MAX_PATH], cmdline[MG_MAX_PATH]; + DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS; + FILE *fp; + + memset(&si, 0, sizeof(si)); + memset(&pi, 0, sizeof(pi)); + + si.cb = sizeof(si); + si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; + si.wShowWindow = SW_HIDE; + si.hStdError = GetStdHandle(STD_ERROR_HANDLE); + + CreatePipe(&a[0], &a[1], NULL, 0); + CreatePipe(&b[0], &b[1], NULL, 0); + DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags); + DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags); + + if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) { + buf[0] = buf[1] = '\0'; + fgets(buf, sizeof(buf), fp); + buf[sizeof(buf) - 1] = '\0'; + if (buf[0] == '#' && buf[1] == '!') { + interp = buf + 2; + /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */ + while (*interp != '\0' && isspace(*(unsigned char *) interp)) { + interp++; + } + } + fclose(fp); + } + + snprintf(buf, sizeof(buf), "%s/%s", dir, cmd); + mg_abs_path(buf, buf2, ARRAY_SIZE(buf2)); + + mg_abs_path(dir, buf5, ARRAY_SIZE(buf5)); + to_wchar(dir, full_dir, ARRAY_SIZE(full_dir)); + + if (interp != NULL) { + mg_abs_path(interp, buf4, ARRAY_SIZE(buf4)); + snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2); + } else { + snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2); + } + to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd)); + + if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP, + (void *) env, full_dir, &si, &pi) != 0) { + mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin); + mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout); + + CloseHandle(si.hStdOutput); + CloseHandle(si.hStdInput); + + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + } else { + CloseHandle(a[1]); + CloseHandle(b[0]); + closesocket(sock); + } + DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess)); + + /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */ + (void) envp; + return (pi.hProcess != NULL); +} +#else +static int mg_start_process(const char *interp, const char *cmd, + const char *env, const char *envp[], + const char *dir, sock_t sock) { + char buf[500]; + pid_t pid = fork(); + (void) env; + + if (pid == 0) { + /* + * In Linux `chdir` declared with `warn_unused_result` attribute + * To shutup compiler we have yo use result in some way + */ + int tmp = chdir(dir); + (void) tmp; + (void) dup2(sock, 0); + (void) dup2(sock, 1); + closesocket(sock); + + /* + * After exec, all signal handlers are restored to their default values, + * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's + * implementation, SIGCHLD's handler will leave unchanged after exec + * if it was set to be ignored. Restore it to default action. + */ + signal(SIGCHLD, SIG_DFL); + + if (interp == NULL) { + execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */ + } else { + execle(interp, interp, cmd, (char *) 0, envp); + } + snprintf(buf, sizeof(buf), + "Status: 500\r\n\r\n" + "500 Server Error: %s%s%s: %s", + interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd, + strerror(errno)); + send(1, buf, strlen(buf), 0); + _exit(EXIT_FAILURE); /* exec call failed */ + } + + return (pid != 0); +} +#endif /* _WIN32 */ + +/* + * Append VARIABLE=VALUE\0 string to the buffer, and add a respective + * pointer into the vars array. + */ +static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) { + int n, space; + char *added = block->buf + block->len; + va_list ap; + + /* Calculate how much space is left in the buffer */ + space = sizeof(block->buf) - (block->len + 2); + if (space > 0) { + /* Copy VARIABLE=VALUE\0 string into the free space */ + va_start(ap, fmt); + n = vsnprintf(added, (size_t) space, fmt, ap); + va_end(ap); + + /* Make sure we do not overflow buffer and the envp array */ + if (n > 0 && n + 1 < space && + block->nvars < (int) ARRAY_SIZE(block->vars) - 2) { + /* Append a pointer to the added string into the envp array */ + block->vars[block->nvars++] = added; + /* Bump up used length counter. Include \0 terminator */ + block->len += n + 1; + } + } + + return added; +} + +static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) { + const char *s; + if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s); +} + +static void mg_prepare_cgi_environment(struct mg_connection *nc, + const char *prog, + const struct mg_str *path_info, + const struct http_message *hm, + const struct mg_serve_http_opts *opts, + struct mg_cgi_env_block *blk) { + const char *s; + struct mg_str *h; + char *p; + size_t i; + char buf[100]; + size_t path_info_len = path_info != NULL ? path_info->len : 0; + + blk->len = blk->nvars = 0; + blk->nc = nc; + + if ((s = getenv("SERVER_NAME")) != NULL) { + mg_addenv(blk, "SERVER_NAME=%s", s); + } else { + mg_sock_to_str(nc->sock, buf, sizeof(buf), 3); + mg_addenv(blk, "SERVER_NAME=%s", buf); + } + mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root); + mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root); + mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION); + + /* Prepare the environment block */ + mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1"); + mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1"); + mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */ + + mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p); + + mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p, + hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len, + hm->query_string.p); + + mg_conn_addr_to_str(nc, buf, sizeof(buf), + MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP); + mg_addenv(blk, "REMOTE_ADDR=%s", buf); + mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT); + mg_addenv(blk, "SERVER_PORT=%s", buf); + + s = hm->uri.p + hm->uri.len - path_info_len - 1; + if (*s == '/') { + const char *base_name = strrchr(prog, DIRSEP); + mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p, + (base_name != NULL ? base_name + 1 : prog)); + } else { + mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p); + } + mg_addenv(blk, "SCRIPT_FILENAME=%s", prog); + + if (path_info != NULL && path_info->len > 0) { + mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p); + /* Not really translated... */ + mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p); + } + +#if MG_ENABLE_SSL + mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off")); +#else + mg_addenv(blk, "HTTPS=off"); +#endif + + if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) != + NULL) { + mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p); + } + + if (hm->query_string.len > 0) { + mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len, + hm->query_string.p); + } + + if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) != + NULL) { + mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p); + } + + mg_addenv2(blk, "PATH"); + mg_addenv2(blk, "TMP"); + mg_addenv2(blk, "TEMP"); + mg_addenv2(blk, "TMPDIR"); + mg_addenv2(blk, "PERLLIB"); + mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI); + +#ifdef _WIN32 + mg_addenv2(blk, "COMSPEC"); + mg_addenv2(blk, "SYSTEMROOT"); + mg_addenv2(blk, "SystemDrive"); + mg_addenv2(blk, "ProgramFiles"); + mg_addenv2(blk, "ProgramFiles(x86)"); + mg_addenv2(blk, "CommonProgramFiles(x86)"); +#else + mg_addenv2(blk, "LD_LIBRARY_PATH"); +#endif /* _WIN32 */ + + /* Add all headers as HTTP_* variables */ + for (i = 0; hm->header_names[i].len > 0; i++) { + p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len, + hm->header_names[i].p, (int) hm->header_values[i].len, + hm->header_values[i].p); + + /* Convert variable name into uppercase, and change - to _ */ + for (; *p != '=' && *p != '\0'; p++) { + if (*p == '-') *p = '_'; + *p = (char) toupper(*(unsigned char *) p); + } + } + + blk->vars[blk->nvars++] = NULL; + blk->buf[blk->len++] = '\0'; +} + +static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev, + void *ev_data MG_UD_ARG(void *user_data)) { +#if !MG_ENABLE_CALLBACK_USERDATA + void *user_data = cgi_nc->user_data; +#endif + struct mg_connection *nc = (struct mg_connection *) user_data; + (void) ev_data; + + if (nc == NULL) { + /* The corresponding network connection was closed. */ + cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; + return; + } + + switch (ev) { + case MG_EV_RECV: + /* + * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n" + * It outputs headers, then body. Headers might include "Status" + * header, which changes CODE, and it might include "Location" header + * which changes CODE to 302. + * + * Therefore we do not send the output from the CGI script to the user + * until all CGI headers are received. + * + * Here we parse the output from the CGI script, and if all headers has + * been received, send appropriate reply line, and forward all + * received headers to the client. + */ + if (nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS) { + struct mbuf *io = &cgi_nc->recv_mbuf; + int len = mg_http_get_request_len(io->buf, io->len); + + if (len == 0) break; + if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) { + cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; + mg_http_send_error(nc, 500, "Bad headers"); + } else { + struct http_message hm; + struct mg_str *h; + mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm); + if (mg_get_http_header(&hm, "Location") != NULL) { + mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n"); + } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) { + mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p); + } else { + mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n"); + } + } + nc->flags &= ~MG_F_HTTP_CGI_PARSE_HEADERS; + } + if (!(nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS)) { + mg_forward(cgi_nc, nc); + } + break; + case MG_EV_CLOSE: + DBG(("%p CLOSE", cgi_nc)); + mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi); + nc->flags |= MG_F_SEND_AND_CLOSE; + break; + } +} + +MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog, + const struct mg_str *path_info, + const struct http_message *hm, + const struct mg_serve_http_opts *opts) { + struct mg_cgi_env_block blk; + char dir[MG_MAX_PATH]; + const char *p; + sock_t fds[2]; + + DBG(("%p [%s]", nc, prog)); + mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk); + /* + * CGI must be executed in its own directory. 'dir' must point to the + * directory containing executable program, 'p' must point to the + * executable program name relative to 'dir'. + */ + if ((p = strrchr(prog, DIRSEP)) == NULL) { + snprintf(dir, sizeof(dir), "%s", "."); + } else { + snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog); + prog = p + 1; + } + + if (!mg_socketpair(fds, SOCK_STREAM)) { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + return; + } + +#ifndef _WIN32 + struct sigaction sa; + + sigemptyset(&sa.sa_mask); + sa.sa_handler = SIG_IGN; + sa.sa_flags = 0; + sigaction(SIGCHLD, &sa, NULL); +#endif + + if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir, + fds[1]) != 0) { + struct mg_connection *cgi_nc = + mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler MG_UD_ARG(nc)); + struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc); + cgi_pd->cgi.cgi_nc = cgi_nc; +#if !MG_ENABLE_CALLBACK_USERDATA + cgi_pd->cgi.cgi_nc->user_data = nc; +#endif + nc->flags |= MG_F_HTTP_CGI_PARSE_HEADERS; + /* Push POST data to the CGI */ + if (hm->body.len > 0) { + mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, hm->body.len); + } + mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len); + } else { + closesocket(fds[0]); + mg_http_send_error(nc, 500, "CGI failure"); + } + +#ifndef _WIN32 + closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */ +#endif +} + +MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) { + if (d == NULL) return; + if (d->cgi_nc != NULL) { + d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; + d->cgi_nc->user_data = NULL; + } + memset(d, 0, sizeof(*d)); +} + +#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_http_ssi.c" +#endif +/* + * Copyright (c) 2014-2016 Cesanta Software Limited + * All rights reserved + */ + +#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM + +static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm, + const char *path, FILE *fp, int include_level, + const struct mg_serve_http_opts *opts); + +static void mg_send_file_data(struct mg_connection *nc, FILE *fp) { + char buf[BUFSIZ]; + size_t n; + while ((n = mg_fread(buf, 1, sizeof(buf), fp)) > 0) { + mg_send(nc, buf, n); + } +} + +static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm, + const char *ssi, char *tag, int include_level, + const struct mg_serve_http_opts *opts) { + char file_name[MG_MAX_PATH], path[MG_MAX_PATH], *p; + FILE *fp; + + /* + * sscanf() is safe here, since send_ssi_file() also uses buffer + * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN. + */ + if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) { + /* File name is relative to the webserver root */ + snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name); + } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) { + /* + * File name is relative to the webserver working directory + * or it is absolute system path + */ + snprintf(path, sizeof(path), "%s", file_name); + } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 || + sscanf(tag, " \"%[^\"]\"", file_name) == 1) { + /* File name is relative to the currect document */ + snprintf(path, sizeof(path), "%s", ssi); + if ((p = strrchr(path, DIRSEP)) != NULL) { + p[1] = '\0'; + } + snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name); + } else { + mg_printf(nc, "Bad SSI #include: [%s]", tag); + return; + } + + if ((fp = mg_fopen(path, "rb")) == NULL) { + mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path, + strerror(mg_get_errno())); + } else { + mg_set_close_on_exec((sock_t) fileno(fp)); + if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > + 0) { + mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts); + } else { + mg_send_file_data(nc, fp); + } + fclose(fp); + } +} + +#if MG_ENABLE_HTTP_SSI_EXEC +static void do_ssi_exec(struct mg_connection *nc, char *tag) { + char cmd[BUFSIZ]; + FILE *fp; + + if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) { + mg_printf(nc, "Bad SSI #exec: [%s]", tag); + } else if ((fp = popen(cmd, "r")) == NULL) { + mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno())); + } else { + mg_send_file_data(nc, fp); + pclose(fp); + } +} +#endif /* MG_ENABLE_HTTP_SSI_EXEC */ + +/* + * SSI directive has the following format: + * + */ +static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm, + const char *path, FILE *fp, int include_level, + const struct mg_serve_http_opts *opts) { + static const struct mg_str btag = MG_MK_STR(" */ + buf[i--] = '\0'; + while (i > 0 && buf[i] == ' ') { + buf[i--] = '\0'; + } + + /* Handle known SSI directives */ + if (strncmp(p, d_include.p, d_include.len) == 0) { + mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level, + opts); + } else if (strncmp(p, d_call.p, d_call.len) == 0) { + struct mg_ssi_call_ctx cctx; + memset(&cctx, 0, sizeof(cctx)); + cctx.req = hm; + cctx.file = mg_mk_str(path); + cctx.arg = mg_mk_str(p + d_call.len + 1); + mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL, + (void *) cctx.arg.p); /* NUL added above */ + mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL_CTX, &cctx); +#if MG_ENABLE_HTTP_SSI_EXEC + } else if (strncmp(p, d_exec.p, d_exec.len) == 0) { + do_ssi_exec(nc, p + d_exec.len + 1); +#endif + } else { + /* Silently ignore unknown SSI directive. */ + } + len = 0; + } else if (ch == '<') { + in_ssi_tag = 1; + if (len > 0) { + mg_send(nc, buf, (size_t) len); + } + len = 0; + buf[len++] = ch & 0xff; + } else if (in_ssi_tag) { + if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) { + /* Not an SSI tag */ + in_ssi_tag = 0; + } else if (len == (int) sizeof(buf) - 2) { + mg_printf(nc, "%s: SSI tag is too large", path); + len = 0; + } + buf[len++] = ch & 0xff; + } else { + buf[len++] = ch & 0xff; + if (len == (int) sizeof(buf)) { + mg_send(nc, buf, (size_t) len); + len = 0; + } + } + } + + /* Send the rest of buffered data */ + if (len > 0) { + mg_send(nc, buf, (size_t) len); + } +} + +MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc, + struct http_message *hm, + const char *path, + const struct mg_serve_http_opts *opts) { + FILE *fp; + struct mg_str mime_type; + DBG(("%p %s", nc, path)); + + if ((fp = mg_fopen(path, "rb")) == NULL) { + mg_http_send_error(nc, 404, NULL); + } else { + mg_set_close_on_exec((sock_t) fileno(fp)); + + mime_type = mg_get_mime_type(path, "text/plain", opts); + mg_send_response_line(nc, 200, opts->extra_headers); + mg_printf(nc, + "Content-Type: %.*s\r\n" + "Connection: close\r\n\r\n", + (int) mime_type.len, mime_type.p); + mg_send_ssi_file(nc, hm, path, fp, 0, opts); + fclose(fp); + nc->flags |= MG_F_SEND_AND_CLOSE; + } +} + +#endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_http_webdav.c" +#endif +/* + * Copyright (c) 2014-2016 Cesanta Software Limited + * All rights reserved + */ + +#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV + +MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) { + static const char *methods[] = { + "PUT", + "DELETE", + "MKCOL", + "PROPFIND", + "MOVE" +#if MG_ENABLE_FAKE_DAVLOCK + , + "LOCK", + "UNLOCK" +#endif + }; + size_t i; + + for (i = 0; i < ARRAY_SIZE(methods); i++) { + if (mg_vcmp(s, methods[i]) == 0) { + return 1; + } + } + + return 0; +} + +static int mg_mkdir(const char *path, uint32_t mode) { +#ifndef _WIN32 + return mkdir(path, mode); +#else + (void) mode; + return _mkdir(path); +#endif +} + +static void mg_print_props(struct mg_connection *nc, const char *name, + cs_stat_t *stp) { + char mtime[64]; + time_t t = stp->st_mtime; /* store in local variable for NDK compile */ + struct mg_str name_esc = mg_url_encode(mg_mk_str(name)); + mg_gmt_time_string(mtime, sizeof(mtime), &t); + mg_printf(nc, + "" + "%s" + "" + "" + "%s" + "%" INT64_FMT + "" + "%s" + "" + "HTTP/1.1 200 OK" + "" + "\n", + name_esc.p, S_ISDIR(stp->st_mode) ? "" : "", + (int64_t) stp->st_size, mtime); + free((void *) name_esc.p); +} + +MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path, + cs_stat_t *stp, struct http_message *hm, + struct mg_serve_http_opts *opts) { + static const char header[] = + "HTTP/1.1 207 Multi-Status\r\n" + "Connection: close\r\n" + "Content-Type: text/xml; charset=utf-8\r\n\r\n" + "" + "\n"; + static const char footer[] = "\n"; + const struct mg_str *depth = mg_get_http_header(hm, "Depth"); + + /* Print properties for the requested resource itself */ + if (S_ISDIR(stp->st_mode) && + strcmp(opts->enable_directory_listing, "yes") != 0) { + mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n"); + } else { + char uri[MG_MAX_PATH]; + mg_send(nc, header, sizeof(header) - 1); + snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p); + mg_print_props(nc, uri, stp); + if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) { + mg_scan_directory(nc, path, opts, mg_print_props); + } + mg_send(nc, footer, sizeof(footer) - 1); + nc->flags |= MG_F_SEND_AND_CLOSE; + } +} + +#if MG_ENABLE_FAKE_DAVLOCK +/* + * Windows explorer (probably there are another WebDav clients like it) + * requires LOCK support in webdav. W/out this, it still works, but fails + * to save file: shows error message and offers "Save As". + * "Save as" works, but this message is very annoying. + * This is fake lock, which doesn't lock something, just returns LOCK token, + * UNLOCK always answers "OK". + * With this fake LOCK Windows Explorer looks happy and saves file. + * NOTE: that is not DAV LOCK imlementation, it is just a way to shut up + * Windows native DAV client. This is why FAKE LOCK is not enabed by default + */ +MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) { + static const char *reply = + "HTTP/1.1 207 Multi-Status\r\n" + "Connection: close\r\n" + "Content-Type: text/xml; charset=utf-8\r\n\r\n" + "" + "\n" + "\n" + "\n" + "\n" + "\n" + "opaquelocktoken:%s%u" + "" + "" + "\n" + "" + "\n"; + mg_printf(nc, reply, path, (unsigned int) mg_time()); + nc->flags |= MG_F_SEND_AND_CLOSE; +} +#endif + +MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path, + struct http_message *hm) { + int status_code = 500; + if (hm->body.len != (size_t) ~0 && hm->body.len > 0) { + status_code = 415; + } else if (!mg_mkdir(path, 0755)) { + status_code = 201; + } else if (errno == EEXIST) { + status_code = 405; + } else if (errno == EACCES) { + status_code = 403; + } else if (errno == ENOENT) { + status_code = 409; + } else { + status_code = 500; + } + mg_http_send_error(nc, status_code, NULL); +} + +static int mg_remove_directory(const struct mg_serve_http_opts *opts, + const char *dir) { + char path[MG_MAX_PATH]; + struct dirent *dp; + cs_stat_t st; + DIR *dirp; + + if ((dirp = opendir(dir)) == NULL) return 0; + + while ((dp = readdir(dirp)) != NULL) { + if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) { + continue; + } + snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name); + mg_stat(path, &st); + if (S_ISDIR(st.st_mode)) { + mg_remove_directory(opts, path); + } else { + remove(path); + } + } + closedir(dirp); + rmdir(dir); + + return 1; +} + +MG_INTERNAL void mg_handle_move(struct mg_connection *c, + const struct mg_serve_http_opts *opts, + const char *path, struct http_message *hm) { + const struct mg_str *dest = mg_get_http_header(hm, "Destination"); + if (dest == NULL) { + mg_http_send_error(c, 411, NULL); + } else { + const char *p = (char *) memchr(dest->p, '/', dest->len); + if (p != NULL && p[1] == '/' && + (p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) { + char buf[MG_MAX_PATH]; + snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root, + (int) (dest->p + dest->len - p), p); + if (rename(path, buf) == 0) { + mg_http_send_error(c, 200, NULL); + } else { + mg_http_send_error(c, 418, NULL); + } + } else { + mg_http_send_error(c, 500, NULL); + } + } +} + +MG_INTERNAL void mg_handle_delete(struct mg_connection *nc, + const struct mg_serve_http_opts *opts, + const char *path) { + cs_stat_t st; + if (mg_stat(path, &st) != 0) { + mg_http_send_error(nc, 404, NULL); + } else if (S_ISDIR(st.st_mode)) { + mg_remove_directory(opts, path); + mg_http_send_error(nc, 204, NULL); + } else if (remove(path) == 0) { + mg_http_send_error(nc, 204, NULL); + } else { + mg_http_send_error(nc, 423, NULL); + } +} + +/* Return -1 on error, 1 on success. */ +static int mg_create_itermediate_directories(const char *path) { + const char *s; + + /* Create intermediate directories if they do not exist */ + for (s = path + 1; *s != '\0'; s++) { + if (*s == '/') { + char buf[MG_MAX_PATH]; + cs_stat_t st; + snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path); + buf[sizeof(buf) - 1] = '\0'; + if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) { + return -1; + } + } + } + + return 1; +} + +MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path, + struct http_message *hm) { + struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); + cs_stat_t st; + const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length"); + int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201; + + mg_http_free_proto_data_file(&pd->file); + if ((rc = mg_create_itermediate_directories(path)) == 0) { + mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code); + } else if (rc == -1) { + mg_http_send_error(nc, 500, NULL); + } else if (cl_hdr == NULL) { + mg_http_send_error(nc, 411, NULL); + } else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) { + mg_http_send_error(nc, 500, NULL); + } else { + const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range"); + int64_t r1 = 0, r2 = 0; + pd->file.type = DATA_PUT; + mg_set_close_on_exec((sock_t) fileno(pd->file.fp)); + pd->file.cl = to64(cl_hdr->p); + if (range_hdr != NULL && + mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) { + status_code = 206; + fseeko(pd->file.fp, r1, SEEK_SET); + pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1; + } + mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code); + /* Remove HTTP request from the mbuf, leave only payload */ + mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len); + mg_http_transfer_file_data(nc); + } +} + +#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_http_websocket.c" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET + +/* Amalgamated: #include "common/cs_sha1.h" */ + +#ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS +#define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5 +#endif + +#define FLAGS_MASK_FIN (1 << 7) +#define FLAGS_MASK_OP 0x0f + +static int mg_is_ws_fragment(unsigned char flags) { + return (flags & FLAGS_MASK_FIN) == 0 || + (flags & FLAGS_MASK_OP) == WEBSOCKET_OP_CONTINUE; +} + +static int mg_is_ws_first_fragment(unsigned char flags) { + return (flags & FLAGS_MASK_FIN) == 0 && + (flags & FLAGS_MASK_OP) != WEBSOCKET_OP_CONTINUE; +} + +static int mg_is_ws_control_frame(unsigned char flags) { + unsigned char op = (flags & FLAGS_MASK_OP); + return op == WEBSOCKET_OP_CLOSE || op == WEBSOCKET_OP_PING || + op == WEBSOCKET_OP_PONG; +} + +static void mg_handle_incoming_websocket_frame(struct mg_connection *nc, + struct websocket_message *wsm) { + if (wsm->flags & 0x8) { + mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm); + } else { + mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_FRAME, wsm); + } +} + +static struct mg_ws_proto_data *mg_ws_get_proto_data(struct mg_connection *nc) { + struct mg_http_proto_data *htd = mg_http_get_proto_data(nc); + return (htd != NULL ? &htd->ws_data : NULL); +} + +/* + * Sends a Close websocket frame with the given data, and closes the underlying + * connection. If `len` is ~0, strlen(data) is used. + */ +static void mg_ws_close(struct mg_connection *nc, const void *data, + size_t len) { + if ((int) len == ~0) { + len = strlen((const char *) data); + } + mg_send_websocket_frame(nc, WEBSOCKET_OP_CLOSE, data, len); + nc->flags |= MG_F_SEND_AND_CLOSE; +} + +static int mg_deliver_websocket_data(struct mg_connection *nc) { + /* Using unsigned char *, cause of integer arithmetic below */ + uint64_t i, data_len = 0, frame_len = 0, new_data_len = nc->recv_mbuf.len, + len, mask_len = 0, header_len = 0; + struct mg_ws_proto_data *wsd = mg_ws_get_proto_data(nc); + unsigned char *new_data = (unsigned char *) nc->recv_mbuf.buf, + *e = (unsigned char *) nc->recv_mbuf.buf + nc->recv_mbuf.len; + uint8_t flags; + int ok, reass; + + if (wsd->reass_len > 0) { + /* + * We already have some previously received data which we need to + * reassemble and deliver to the client code when we get the final + * fragment. + * + * NOTE: it doesn't mean that the current message must be a continuation: + * it might be a control frame (Close, Ping or Pong), which should be + * handled without breaking the fragmented message. + */ + + size_t existing_len = wsd->reass_len; + assert(new_data_len >= existing_len); + + new_data += existing_len; + new_data_len -= existing_len; + } + + flags = new_data[0]; + + reass = new_data_len > 0 && mg_is_ws_fragment(flags) && + !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG); + + if (reass && mg_is_ws_control_frame(flags)) { + /* + * Control frames can't be fragmented, so if we encounter fragmented + * control frame, close connection immediately. + */ + mg_ws_close(nc, "fragmented control frames are illegal", ~0); + return 0; + } else if (new_data_len > 0 && !reass && !mg_is_ws_control_frame(flags) && + wsd->reass_len > 0) { + /* + * When in the middle of a fragmented message, only the continuations + * and control frames are allowed. + */ + mg_ws_close(nc, "non-continuation in the middle of a fragmented message", + ~0); + return 0; + } + + if (new_data_len >= 2) { + len = new_data[1] & 0x7f; + mask_len = new_data[1] & FLAGS_MASK_FIN ? 4 : 0; + if (len < 126 && new_data_len >= mask_len) { + data_len = len; + header_len = 2 + mask_len; + } else if (len == 126 && new_data_len >= 4 + mask_len) { + header_len = 4 + mask_len; + data_len = ntohs(*(uint16_t *) &new_data[2]); + } else if (new_data_len >= 10 + mask_len) { + header_len = 10 + mask_len; + data_len = (((uint64_t) ntohl(*(uint32_t *) &new_data[2])) << 32) + + ntohl(*(uint32_t *) &new_data[6]); + } + } + + frame_len = header_len + data_len; + ok = (frame_len > 0 && frame_len <= new_data_len); + + /* Check for overflow */ + if (frame_len < header_len || frame_len < data_len) { + ok = 0; + mg_ws_close(nc, "overflowed message", ~0); + } + + if (ok) { + size_t cleanup_len = 0; + struct websocket_message wsm; + + wsm.size = (size_t) data_len; + wsm.data = new_data + header_len; + wsm.flags = flags; + + /* Apply mask if necessary */ + if (mask_len > 0) { + for (i = 0; i < data_len; i++) { + new_data[i + header_len] ^= (new_data + header_len - mask_len)[i % 4]; + } + } + + if (reass) { + /* This is a message fragment */ + + if (mg_is_ws_first_fragment(flags)) { + /* + * On the first fragmented frame, skip the first byte (op) and also + * reset size to 1 (op), it'll be incremented with the data len below. + */ + new_data += 1; + wsd->reass_len = 1 /* op */; + } + + /* Append this frame to the reassembled buffer */ + memmove(new_data, wsm.data, e - wsm.data); + wsd->reass_len += wsm.size; + nc->recv_mbuf.len -= wsm.data - new_data; + + if (flags & FLAGS_MASK_FIN) { + /* On last fragmented frame - call user handler and remove data */ + wsm.flags = FLAGS_MASK_FIN | nc->recv_mbuf.buf[0]; + wsm.data = (unsigned char *) nc->recv_mbuf.buf + 1 /* op */; + wsm.size = wsd->reass_len - 1 /* op */; + cleanup_len = wsd->reass_len; + wsd->reass_len = 0; + + /* Pass reassembled message to the client code. */ + mg_handle_incoming_websocket_frame(nc, &wsm); + mbuf_remove(&nc->recv_mbuf, cleanup_len); /* Cleanup frame */ + } + } else { + /* + * This is a complete message, not a fragment. It might happen in between + * of a fragmented message (in this case, WebSocket protocol requires + * current message to be a control frame). + */ + cleanup_len = (size_t) frame_len; + + /* First of all, check if we need to react on a control frame. */ + switch (flags & FLAGS_MASK_OP) { + case WEBSOCKET_OP_PING: + mg_send_websocket_frame(nc, WEBSOCKET_OP_PONG, wsm.data, wsm.size); + break; + + case WEBSOCKET_OP_CLOSE: + mg_ws_close(nc, wsm.data, wsm.size); + break; + } + + /* Pass received message to the client code. */ + mg_handle_incoming_websocket_frame(nc, &wsm); + + /* Cleanup frame */ + memmove(nc->recv_mbuf.buf + wsd->reass_len, + nc->recv_mbuf.buf + wsd->reass_len + cleanup_len, + nc->recv_mbuf.len - wsd->reass_len - cleanup_len); + nc->recv_mbuf.len -= cleanup_len; + } + } + + return ok; +} + +struct ws_mask_ctx { + size_t pos; /* zero means unmasked */ + uint32_t mask; +}; + +static uint32_t mg_ws_random_mask(void) { + uint32_t mask; +/* + * The spec requires WS client to generate hard to + * guess mask keys. From RFC6455, Section 5.3: + * + * The unpredictability of the masking key is essential to prevent + * authors of malicious applications from selecting the bytes that appear on + * the wire. + * + * Hence this feature is essential when the actual end user of this API + * is untrusted code that wouldn't have access to a lower level net API + * anyway (e.g. web browsers). Hence this feature is low prio for most + * mongoose use cases and thus can be disabled, e.g. when porting to a platform + * that lacks rand(). + */ +#if MG_DISABLE_WS_RANDOM_MASK + mask = 0xefbeadde; /* generated with a random number generator, I swear */ +#else + if (sizeof(long) >= 4) { + mask = (uint32_t) rand(); + } else if (sizeof(long) == 2) { + mask = (uint32_t) rand() << 16 | (uint32_t) rand(); + } +#endif + return mask; +} + +static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len, + struct ws_mask_ctx *ctx) { + int header_len; + unsigned char header[10]; + + header[0] = + (op & WEBSOCKET_DONT_FIN ? 0x0 : FLAGS_MASK_FIN) | (op & FLAGS_MASK_OP); + if (len < 126) { + header[1] = (unsigned char) len; + header_len = 2; + } else if (len < 65535) { + uint16_t tmp = htons((uint16_t) len); + header[1] = 126; + memcpy(&header[2], &tmp, sizeof(tmp)); + header_len = 4; + } else { + uint32_t tmp; + header[1] = 127; + tmp = htonl((uint32_t)((uint64_t) len >> 32)); + memcpy(&header[2], &tmp, sizeof(tmp)); + tmp = htonl((uint32_t)(len & 0xffffffff)); + memcpy(&header[6], &tmp, sizeof(tmp)); + header_len = 10; + } + + /* client connections enable masking */ + if (nc->listener == NULL) { + header[1] |= 1 << 7; /* set masking flag */ + mg_send(nc, header, header_len); + ctx->mask = mg_ws_random_mask(); + mg_send(nc, &ctx->mask, sizeof(ctx->mask)); + ctx->pos = nc->send_mbuf.len; + } else { + mg_send(nc, header, header_len); + ctx->pos = 0; + } +} + +static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) { + size_t i; + if (ctx->pos == 0) return; + for (i = 0; i < (mbuf->len - ctx->pos); i++) { + mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4]; + } +} + +void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data, + size_t len) { + struct ws_mask_ctx ctx; + DBG(("%p %d %d", nc, op, (int) len)); + mg_send_ws_header(nc, op, len, &ctx); + mg_send(nc, data, len); + + mg_ws_mask_frame(&nc->send_mbuf, &ctx); + + if (op == WEBSOCKET_OP_CLOSE) { + nc->flags |= MG_F_SEND_AND_CLOSE; + } +} + +void mg_send_websocket_framev(struct mg_connection *nc, int op, + const struct mg_str *strv, int strvcnt) { + struct ws_mask_ctx ctx; + int i; + int len = 0; + for (i = 0; i < strvcnt; i++) { + len += strv[i].len; + } + + mg_send_ws_header(nc, op, len, &ctx); + + for (i = 0; i < strvcnt; i++) { + mg_send(nc, strv[i].p, strv[i].len); + } + + mg_ws_mask_frame(&nc->send_mbuf, &ctx); + + if (op == WEBSOCKET_OP_CLOSE) { + nc->flags |= MG_F_SEND_AND_CLOSE; + } +} + +void mg_printf_websocket_frame(struct mg_connection *nc, int op, + const char *fmt, ...) { + char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; + va_list ap; + int len; + + va_start(ap, fmt); + if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) { + mg_send_websocket_frame(nc, op, buf, len); + } + va_end(ap); + + if (buf != mem && buf != NULL) { + MG_FREE(buf); + } +} + +MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev, + void *ev_data MG_UD_ARG(void *user_data)) { + mg_call(nc, nc->handler, nc->user_data, ev, ev_data); + + switch (ev) { + case MG_EV_RECV: + do { + } while (mg_deliver_websocket_data(nc)); + break; + case MG_EV_POLL: + /* Ping idle websocket connections */ + { + time_t now = *(time_t *) ev_data; + if (nc->flags & MG_F_IS_WEBSOCKET && + now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) { + mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0); + } + } + break; + default: + break; + } +#if MG_ENABLE_CALLBACK_USERDATA + (void) user_data; +#endif +} + +#ifndef MG_EXT_SHA1 +void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[], + const size_t *msg_lens, uint8_t *digest) { + size_t i; + cs_sha1_ctx sha_ctx; + cs_sha1_init(&sha_ctx); + for (i = 0; i < num_msgs; i++) { + cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]); + } + cs_sha1_final(digest, &sha_ctx); +} +#else +extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[], + const size_t *msg_lens, uint8_t *digest); +#endif + +MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc, + const struct mg_str *key, + struct http_message *hm) { + static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic}; + const size_t msg_lens[2] = {key->len, 36}; + unsigned char sha[20]; + char b64_sha[30]; + struct mg_str *s; + + mg_hash_sha1_v(2, msgs, msg_lens, sha); + mg_base64_encode(sha, sizeof(sha), b64_sha); + mg_printf(nc, "%s", + "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n"); + + s = mg_get_http_header(hm, "Sec-WebSocket-Protocol"); + if (s != NULL) { + mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) s->len, s->p); + } + mg_printf(nc, "Sec-WebSocket-Accept: %s%s", b64_sha, "\r\n\r\n"); + + DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha)); +} + +void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path, + const char *host, const char *protocol, + const char *extra_headers) { + mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL, + NULL); +} + +void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path, + const char *host, const char *protocol, + const char *extra_headers, const char *user, + const char *pass) { + mg_send_websocket_handshake3v(nc, mg_mk_str(path), mg_mk_str(host), + mg_mk_str(protocol), mg_mk_str(extra_headers), + mg_mk_str(user), mg_mk_str(pass)); +} + +void mg_send_websocket_handshake3v(struct mg_connection *nc, + const struct mg_str path, + const struct mg_str host, + const struct mg_str protocol, + const struct mg_str extra_headers, + const struct mg_str user, + const struct mg_str pass) { + struct mbuf auth; + char key[25]; + uint32_t nonce[4]; + nonce[0] = mg_ws_random_mask(); + nonce[1] = mg_ws_random_mask(); + nonce[2] = mg_ws_random_mask(); + nonce[3] = mg_ws_random_mask(); + mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key); + + mbuf_init(&auth, 0); + if (user.len > 0) { + mg_basic_auth_header(user, pass, &auth); + } + + /* + * NOTE: the (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is + * broken: it doesn't like zero length to be passed to %.*s + * i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`. + * because it handles NULL specially (and incorrectly). + */ + mg_printf(nc, + "GET %.*s HTTP/1.1\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "%.*s" + "Sec-WebSocket-Version: 13\r\n" + "Sec-WebSocket-Key: %s\r\n", + (int) path.len, path.p, (int) auth.len, + (auth.buf == NULL ? "" : auth.buf), key); + + /* TODO(mkm): take default hostname from http proto data if host == NULL */ + if (host.len > 0) { + int host_len = (int) (path.p - host.p); /* Account for possible :PORT */ + mg_printf(nc, "Host: %.*s\r\n", host_len, host.p); + } + if (protocol.len > 0) { + mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) protocol.len, + protocol.p); + } + if (extra_headers.len > 0) { + mg_printf(nc, "%.*s", (int) extra_headers.len, extra_headers.p); + } + mg_printf(nc, "\r\n"); + + nc->flags |= MG_F_IS_WEBSOCKET; + + mbuf_free(&auth); +} + +void mg_send_websocket_handshake(struct mg_connection *nc, const char *path, + const char *extra_headers) { + struct mg_str null_str = MG_NULL_STR; + mg_send_websocket_handshake3v( + nc, mg_mk_str(path), null_str /* host */, null_str /* protocol */, + mg_mk_str(extra_headers), null_str /* user */, null_str /* pass */); +} + +struct mg_connection *mg_connect_ws_opt( + struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), + struct mg_connect_opts opts, const char *url, const char *protocol, + const char *extra_headers) { + struct mg_str null_str = MG_NULL_STR; + struct mg_str host = MG_NULL_STR, path = MG_NULL_STR, user_info = MG_NULL_STR; + struct mg_connection *nc = + mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http", + "ws", "https", "wss", url, &path, &user_info, &host); + if (nc != NULL) { + mg_send_websocket_handshake3v(nc, path, host, mg_mk_str(protocol), + mg_mk_str(extra_headers), user_info, + null_str); + } + return nc; +} + +struct mg_connection *mg_connect_ws( + struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), + const char *url, const char *protocol, const char *extra_headers) { + struct mg_connect_opts opts; + memset(&opts, 0, sizeof(opts)); + return mg_connect_ws_opt(mgr, MG_CB(ev_handler, user_data), opts, url, + protocol, extra_headers); +} +#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_util.c" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +/* Amalgamated: #include "common/cs_base64.h" */ +/* Amalgamated: #include "mg_internal.h" */ +/* Amalgamated: #include "mg_util.h" */ + +/* For platforms with limited libc */ +#ifndef MAX +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#endif + +const char *mg_skip(const char *s, const char *end, const char *delims, + struct mg_str *v) { + v->p = s; + while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++; + v->len = s - v->p; + while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++; + return s; +} + +#if MG_ENABLE_FILESYSTEM && !defined(MG_USER_FILE_FUNCTIONS) +int mg_stat(const char *path, cs_stat_t *st) { +#ifdef _WIN32 + wchar_t wpath[MG_MAX_PATH]; + to_wchar(path, wpath, ARRAY_SIZE(wpath)); + DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st))); + return _wstati64(wpath, st); +#else + return stat(path, st); +#endif +} + +FILE *mg_fopen(const char *path, const char *mode) { +#ifdef _WIN32 + wchar_t wpath[MG_MAX_PATH], wmode[10]; + to_wchar(path, wpath, ARRAY_SIZE(wpath)); + to_wchar(mode, wmode, ARRAY_SIZE(wmode)); + return _wfopen(wpath, wmode); +#else + return fopen(path, mode); +#endif +} + +int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */ +#if defined(_WIN32) && !defined(WINCE) + wchar_t wpath[MG_MAX_PATH]; + to_wchar(path, wpath, ARRAY_SIZE(wpath)); + return _wopen(wpath, flag, mode); +#else + return open(path, flag, mode); /* LCOV_EXCL_LINE */ +#endif +} + +size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f) { + return fread(ptr, size, count, f); +} + +size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f) { + return fwrite(ptr, size, count, f); +} +#endif + +void mg_base64_encode(const unsigned char *src, int src_len, char *dst) { + cs_base64_encode(src, src_len, dst); +} + +int mg_base64_decode(const unsigned char *s, int len, char *dst) { + return cs_base64_decode(s, len, dst, NULL); +} + +#if MG_ENABLE_THREADS +void *mg_start_thread(void *(*f)(void *), void *p) { +#ifdef WINCE + return (void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL); +#elif defined(_WIN32) + return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p); +#else + pthread_t thread_id = (pthread_t) 0; + pthread_attr_t attr; + + (void) pthread_attr_init(&attr); + (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + +#if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1 + (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE); +#endif + + pthread_create(&thread_id, &attr, f, p); + pthread_attr_destroy(&attr); + + return (void *) thread_id; +#endif +} +#endif /* MG_ENABLE_THREADS */ + +/* Set close-on-exec bit for a given socket. */ +void mg_set_close_on_exec(sock_t sock) { +#if defined(_WIN32) && !defined(WINCE) + (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0); +#elif defined(__unix__) + fcntl(sock, F_SETFD, FD_CLOEXEC); +#else + (void) sock; +#endif +} + +int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len, + int flags) { + int is_v6; + if (buf == NULL || len <= 0) return 0; + memset(buf, 0, len); +#if MG_ENABLE_IPV6 + is_v6 = sa->sa.sa_family == AF_INET6; +#else + is_v6 = 0; +#endif + if (flags & MG_SOCK_STRINGIFY_IP) { +#if MG_ENABLE_IPV6 + const void *addr = NULL; + char *start = buf; + socklen_t capacity = len; + if (!is_v6) { + addr = &sa->sin.sin_addr; + } else { + addr = (void *) &sa->sin6.sin6_addr; + if (flags & MG_SOCK_STRINGIFY_PORT) { + *buf = '['; + start++; + capacity--; + } + } + if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) { + goto cleanup; + } +#elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32) + /* Only Windoze Vista (and newer) have inet_ntop() */ + char *addr_str = inet_ntoa(sa->sin.sin_addr); + if (addr_str != NULL) { + strncpy(buf, inet_ntoa(sa->sin.sin_addr), len - 1); + } else { + goto cleanup; + } +#else + if (inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len) == NULL) { + goto cleanup; + } +#endif + } + if (flags & MG_SOCK_STRINGIFY_PORT) { + int port = ntohs(sa->sin.sin_port); + if (flags & MG_SOCK_STRINGIFY_IP) { + int buf_len = strlen(buf); + snprintf(buf + buf_len, len - (buf_len + 1), "%s:%d", (is_v6 ? "]" : ""), + port); + } else { + snprintf(buf, len, "%d", port); + } + } + + return strlen(buf); + +cleanup: + *buf = '\0'; + return 0; +} + +int mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len, + int flags) { + union socket_address sa; + memset(&sa, 0, sizeof(sa)); + mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa); + return mg_sock_addr_to_str(&sa, buf, len, flags); +} + +#if MG_ENABLE_HEXDUMP +static int mg_hexdump_n(const void *buf, int len, char *dst, int dst_len, + int offset) { + const unsigned char *p = (const unsigned char *) buf; + char ascii[17] = ""; + int i, idx, n = 0; + + for (i = 0; i < len; i++) { + idx = i % 16; + if (idx == 0) { + if (i > 0) n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii); + n += snprintf(dst + n, MAX(dst_len - n, 0), "%04x ", i + offset); + } + if (dst_len - n < 0) { + return n; + } + n += snprintf(dst + n, MAX(dst_len - n, 0), " %02x", p[i]); + ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i]; + ascii[idx + 1] = '\0'; + } + + while (i++ % 16) n += snprintf(dst + n, MAX(dst_len - n, 0), "%s", " "); + n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii); + + return n; +} + +int mg_hexdump(const void *buf, int len, char *dst, int dst_len) { + return mg_hexdump_n(buf, len, dst, dst_len, 0); +} + +void mg_hexdumpf(FILE *fp, const void *buf, int len) { + char tmp[80]; + int offset = 0, n; + while (len > 0) { + n = (len < 16 ? len : 16); + mg_hexdump_n(((const char *) buf) + offset, n, tmp, sizeof(tmp), offset); + fputs(tmp, fp); + offset += n; + len -= n; + } +} + +void mg_hexdump_connection(struct mg_connection *nc, const char *path, + const void *buf, int num_bytes, int ev) { + FILE *fp = NULL; + char src[60], dst[60]; + const char *tag = NULL; + switch (ev) { + case MG_EV_RECV: + tag = "<-"; + break; + case MG_EV_SEND: + tag = "->"; + break; + case MG_EV_ACCEPT: + tag = " 0) { + mg_hexdumpf(fp, buf, num_bytes); + } + if (fp != stdout && fp != stderr) fclose(fp); +} +#endif + +int mg_is_big_endian(void) { + static const int n = 1; + /* TODO(mkm) use compiletime check with 4-byte char literal */ + return ((char *) &n)[0] == 0; +} + +DO_NOT_WARN_UNUSED MG_INTERNAL int mg_get_errno(void) { +#ifndef WINCE + return errno; +#else + /* TODO(alashkin): translate error codes? */ + return GetLastError(); +#endif +} + +void mg_mbuf_append_base64_putc(char ch, void *user_data) { + struct mbuf *mbuf = (struct mbuf *) user_data; + mbuf_append(mbuf, &ch, sizeof(ch)); +} + +void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len) { + struct cs_base64_ctx ctx; + cs_base64_init(&ctx, mg_mbuf_append_base64_putc, mbuf); + cs_base64_update(&ctx, (const char *) data, len); + cs_base64_finish(&ctx); +} + +void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass, + struct mbuf *buf) { + const char *header_prefix = "Authorization: Basic "; + const char *header_suffix = "\r\n"; + + struct cs_base64_ctx ctx; + cs_base64_init(&ctx, mg_mbuf_append_base64_putc, buf); + + mbuf_append(buf, header_prefix, strlen(header_prefix)); + + cs_base64_update(&ctx, user.p, user.len); + if (pass.len > 0) { + cs_base64_update(&ctx, ":", 1); + cs_base64_update(&ctx, pass.p, pass.len); + } + cs_base64_finish(&ctx); + mbuf_append(buf, header_suffix, strlen(header_suffix)); +} + +struct mg_str mg_url_encode_opt(const struct mg_str src, + const struct mg_str safe, unsigned int flags) { + const char *hex = + (flags & MG_URL_ENCODE_F_UPPERCASE_HEX ? "0123456789ABCDEF" + : "0123456789abcdef"); + size_t i = 0; + struct mbuf mb; + mbuf_init(&mb, src.len); + + for (i = 0; i < src.len; i++) { + const unsigned char c = *((const unsigned char *) src.p + i); + if (isalnum(c) || mg_strchr(safe, c) != NULL) { + mbuf_append(&mb, &c, 1); + } else if (c == ' ' && (flags & MG_URL_ENCODE_F_SPACE_AS_PLUS)) { + mbuf_append(&mb, "+", 1); + } else { + mbuf_append(&mb, "%", 1); + mbuf_append(&mb, &hex[c >> 4], 1); + mbuf_append(&mb, &hex[c & 15], 1); + } + } + mbuf_append(&mb, "", 1); + mbuf_trim(&mb); + return mg_mk_str_n(mb.buf, mb.len - 1); +} + +struct mg_str mg_url_encode(const struct mg_str src) { + return mg_url_encode_opt(src, mg_mk_str("._-$,;~()/"), 0); +} +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_mqtt.c" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +#if MG_ENABLE_MQTT + +#include + +/* Amalgamated: #include "mg_internal.h" */ +/* Amalgamated: #include "mg_mqtt.h" */ + +static uint16_t getu16(const char *p) { + const uint8_t *up = (const uint8_t *) p; + return (up[0] << 8) + up[1]; +} + +static const char *scanto(const char *p, struct mg_str *s) { + s->len = getu16(p); + s->p = p + 2; + return s->p + s->len; +} + +MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) { + uint8_t header; + size_t len = 0, len_len = 0; + const char *p, *end; + unsigned char lc = 0; + int cmd; + + if (io->len < 2) return MG_MQTT_ERROR_INCOMPLETE_MSG; + header = io->buf[0]; + cmd = header >> 4; + + /* decode mqtt variable length */ + len = len_len = 0; + p = io->buf + 1; + while ((size_t)(p - io->buf) < io->len) { + lc = *((const unsigned char *) p++); + len += (lc & 0x7f) << 7 * len_len; + len_len++; + if (!(lc & 0x80)) break; + if (len_len > 4) return MG_MQTT_ERROR_MALFORMED_MSG; + } + + end = p + len; + if (lc & 0x80 || len > (io->len - (p - io->buf))) { + return MG_MQTT_ERROR_INCOMPLETE_MSG; + } + + mm->cmd = cmd; + mm->qos = MG_MQTT_GET_QOS(header); + + switch (cmd) { + case MG_MQTT_CMD_CONNECT: { + p = scanto(p, &mm->protocol_name); + if (p > end - 4) return MG_MQTT_ERROR_MALFORMED_MSG; + mm->protocol_version = *(uint8_t *) p++; + mm->connect_flags = *(uint8_t *) p++; + mm->keep_alive_timer = getu16(p); + p += 2; + if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; + p = scanto(p, &mm->client_id); + if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG; + if (mm->connect_flags & MG_MQTT_HAS_WILL) { + if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; + p = scanto(p, &mm->will_topic); + } + if (mm->connect_flags & MG_MQTT_HAS_WILL) { + if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; + p = scanto(p, &mm->will_message); + } + if (mm->connect_flags & MG_MQTT_HAS_USER_NAME) { + if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; + p = scanto(p, &mm->user_name); + } + if (mm->connect_flags & MG_MQTT_HAS_PASSWORD) { + if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; + p = scanto(p, &mm->password); + } + if (p != end) return MG_MQTT_ERROR_MALFORMED_MSG; + + LOG(LL_DEBUG, + ("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] " + "will_msg [%.*s] user_name [%.*s] password [%.*s]", + (int) len, (int) mm->connect_flags, (int) mm->keep_alive_timer, + (int) mm->protocol_name.len, mm->protocol_name.p, + (int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len, + mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p, + (int) mm->user_name.len, mm->user_name.p, (int) mm->password.len, + mm->password.p)); + break; + } + case MG_MQTT_CMD_CONNACK: + if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; + mm->connack_ret_code = p[1]; + break; + case MG_MQTT_CMD_PUBACK: + case MG_MQTT_CMD_PUBREC: + case MG_MQTT_CMD_PUBREL: + case MG_MQTT_CMD_PUBCOMP: + case MG_MQTT_CMD_SUBACK: + mm->message_id = getu16(p); + break; + case MG_MQTT_CMD_PUBLISH: { + p = scanto(p, &mm->topic); + if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG; + if (mm->qos > 0) { + if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; + mm->message_id = getu16(p); + p += 2; + } + mm->payload.p = p; + mm->payload.len = end - p; + break; + } + case MG_MQTT_CMD_SUBSCRIBE: + if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; + mm->message_id = getu16(p); + p += 2; + /* + * topic expressions are left in the payload and can be parsed with + * `mg_mqtt_next_subscribe_topic` + */ + mm->payload.p = p; + mm->payload.len = end - p; + break; + default: + /* Unhandled command */ + break; + } + + mm->len = end - io->buf; + return mm->len; +} + +static void mqtt_handler(struct mg_connection *nc, int ev, + void *ev_data MG_UD_ARG(void *user_data)) { + struct mbuf *io = &nc->recv_mbuf; + struct mg_mqtt_message mm; + memset(&mm, 0, sizeof(mm)); + + nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); + + switch (ev) { + case MG_EV_ACCEPT: + if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc); + break; + case MG_EV_RECV: { + /* There can be multiple messages in the buffer, process them all. */ + while (1) { + int len = parse_mqtt(io, &mm); + if (len < 0) { + if (len == MG_MQTT_ERROR_MALFORMED_MSG) { + /* Protocol error. */ + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } else if (len == MG_MQTT_ERROR_INCOMPLETE_MSG) { + /* Not fully buffered, let's check if we have a chance to get more + * data later */ + if (nc->recv_mbuf_limit > 0 && + nc->recv_mbuf.len >= nc->recv_mbuf_limit) { + LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit " + "%lu bytes, and not drained, closing", + nc, (unsigned long) nc->recv_mbuf.len, + (unsigned long) nc->recv_mbuf_limit)); + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } + } else { + /* Should never be here */ + LOG(LL_ERROR, ("%p invalid len: %d, closing", nc, len)); + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } + break; + } + + nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data)); + mbuf_remove(io, len); + } + break; + } + case MG_EV_POLL: { + struct mg_mqtt_proto_data *pd = + (struct mg_mqtt_proto_data *) nc->proto_data; + double now = mg_time(); + if (pd->keep_alive > 0 && pd->last_control_time > 0 && + (now - pd->last_control_time) > pd->keep_alive) { + LOG(LL_DEBUG, ("Send PINGREQ")); + mg_mqtt_ping(nc); + } + break; + } + } +} + +static void mg_mqtt_proto_data_destructor(void *proto_data) { + MG_FREE(proto_data); +} + +static struct mg_str mg_mqtt_next_topic_component(struct mg_str *topic) { + struct mg_str res = *topic; + const char *c = mg_strchr(*topic, '/'); + if (c != NULL) { + res.len = (c - topic->p); + topic->len -= (res.len + 1); + topic->p += (res.len + 1); + } else { + topic->len = 0; + } + return res; +} + +/* Refernce: https://mosquitto.org/man/mqtt-7.html */ +int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) { + struct mg_str ec, tc; + if (exp.len == 0) return 0; + while (1) { + ec = mg_mqtt_next_topic_component(&exp); + tc = mg_mqtt_next_topic_component(&topic); + if (ec.len == 0) { + if (tc.len != 0) return 0; + if (exp.len == 0) break; + continue; + } + if (mg_vcmp(&ec, "+") == 0) { + if (tc.len == 0 && topic.len == 0) return 0; + continue; + } + if (mg_vcmp(&ec, "#") == 0) { + /* Must be the last component in the expression or it's invalid. */ + return (exp.len == 0); + } + if (mg_strcmp(ec, tc) != 0) { + return 0; + } + } + return (tc.len == 0 && topic.len == 0); +} + +int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) { + return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic); +} + +void mg_set_protocol_mqtt(struct mg_connection *nc) { + nc->proto_handler = mqtt_handler; + nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data)); + nc->proto_data_destructor = mg_mqtt_proto_data_destructor; +} + +static void mg_send_mqtt_header(struct mg_connection *nc, uint8_t cmd, + uint8_t flags, size_t len) { + struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; + uint8_t buf[1 + sizeof(size_t)]; + uint8_t *vlen = &buf[1]; + + buf[0] = (cmd << 4) | flags; + + /* mqtt variable length encoding */ + do { + *vlen = len % 0x80; + len /= 0x80; + if (len > 0) *vlen |= 0x80; + vlen++; + } while (len > 0); + + mg_send(nc, buf, vlen - buf); + pd->last_control_time = mg_time(); +} + +void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) { + static struct mg_send_mqtt_handshake_opts opts; + mg_send_mqtt_handshake_opt(nc, client_id, opts); +} + +void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id, + struct mg_send_mqtt_handshake_opts opts) { + struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; + uint16_t id_len = 0, wt_len = 0, wm_len = 0, user_len = 0, pw_len = 0; + uint16_t netbytes; + size_t total_len; + + if (client_id != NULL) { + id_len = strlen(client_id); + } + + total_len = 7 + 1 + 2 + 2 + id_len; + + if (opts.user_name != NULL) { + opts.flags |= MG_MQTT_HAS_USER_NAME; + } + if (opts.password != NULL) { + opts.flags |= MG_MQTT_HAS_PASSWORD; + } + if (opts.will_topic != NULL && opts.will_message != NULL) { + wt_len = strlen(opts.will_topic); + wm_len = strlen(opts.will_message); + opts.flags |= MG_MQTT_HAS_WILL; + } + if (opts.keep_alive == 0) { + opts.keep_alive = 60; + } + + if (opts.flags & MG_MQTT_HAS_WILL) { + total_len += 2 + wt_len + 2 + wm_len; + } + if (opts.flags & MG_MQTT_HAS_USER_NAME) { + user_len = strlen(opts.user_name); + total_len += 2 + user_len; + } + if (opts.flags & MG_MQTT_HAS_PASSWORD) { + pw_len = strlen(opts.password); + total_len += 2 + pw_len; + } + + mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNECT, 0, total_len); + mg_send(nc, "\00\04MQTT\04", 7); + mg_send(nc, &opts.flags, 1); + + netbytes = htons(opts.keep_alive); + mg_send(nc, &netbytes, 2); + + netbytes = htons(id_len); + mg_send(nc, &netbytes, 2); + mg_send(nc, client_id, id_len); + + if (opts.flags & MG_MQTT_HAS_WILL) { + netbytes = htons(wt_len); + mg_send(nc, &netbytes, 2); + mg_send(nc, opts.will_topic, wt_len); + + netbytes = htons(wm_len); + mg_send(nc, &netbytes, 2); + mg_send(nc, opts.will_message, wm_len); + } + + if (opts.flags & MG_MQTT_HAS_USER_NAME) { + netbytes = htons(user_len); + mg_send(nc, &netbytes, 2); + mg_send(nc, opts.user_name, user_len); + } + if (opts.flags & MG_MQTT_HAS_PASSWORD) { + netbytes = htons(pw_len); + mg_send(nc, &netbytes, 2); + mg_send(nc, opts.password, pw_len); + } + + if (pd != NULL) { + pd->keep_alive = opts.keep_alive; + } +} + +void mg_mqtt_publish(struct mg_connection *nc, const char *topic, + uint16_t message_id, int flags, const void *data, + size_t len) { + uint16_t netbytes; + uint16_t topic_len = strlen(topic); + + size_t total_len = 2 + topic_len + len; + if (MG_MQTT_GET_QOS(flags) > 0) { + total_len += 2; + } + + mg_send_mqtt_header(nc, MG_MQTT_CMD_PUBLISH, flags, total_len); + + netbytes = htons(topic_len); + mg_send(nc, &netbytes, 2); + mg_send(nc, topic, topic_len); + + if (MG_MQTT_GET_QOS(flags) > 0) { + netbytes = htons(message_id); + mg_send(nc, &netbytes, 2); + } + + mg_send(nc, data, len); +} + +void mg_mqtt_subscribe(struct mg_connection *nc, + const struct mg_mqtt_topic_expression *topics, + size_t topics_len, uint16_t message_id) { + uint16_t netbytes; + size_t i; + uint16_t topic_len; + size_t total_len = 2; + + for (i = 0; i < topics_len; i++) { + total_len += 2 + strlen(topics[i].topic) + 1; + } + + mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1), total_len); + + netbytes = htons(message_id); + mg_send(nc, (char *) &netbytes, 2); + + for (i = 0; i < topics_len; i++) { + topic_len = strlen(topics[i].topic); + netbytes = htons(topic_len); + mg_send(nc, &netbytes, 2); + mg_send(nc, topics[i].topic, topic_len); + mg_send(nc, &topics[i].qos, 1); + } +} + +int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg, + struct mg_str *topic, uint8_t *qos, int pos) { + unsigned char *buf = (unsigned char *) msg->payload.p + pos; + int new_pos; + + if ((size_t) pos >= msg->payload.len) return -1; + + topic->len = buf[0] << 8 | buf[1]; + topic->p = (char *) buf + 2; + new_pos = pos + 2 + topic->len + 1; + if ((size_t) new_pos > msg->payload.len) return -1; + *qos = buf[2 + topic->len]; + return new_pos; +} + +void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics, + size_t topics_len, uint16_t message_id) { + uint16_t netbytes; + size_t i; + uint16_t topic_len; + size_t total_len = 2; + + for (i = 0; i < topics_len; i++) { + total_len += 2 + strlen(topics[i]); + } + + mg_send_mqtt_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1), total_len); + + netbytes = htons(message_id); + mg_send(nc, (char *) &netbytes, 2); + + for (i = 0; i < topics_len; i++) { + topic_len = strlen(topics[i]); + netbytes = htons(topic_len); + mg_send(nc, &netbytes, 2); + mg_send(nc, topics[i], topic_len); + } +} + +void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) { + uint8_t unused = 0; + mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNACK, 0, 2); + mg_send(nc, &unused, 1); + mg_send(nc, &return_code, 1); +} + +/* + * Sends a command which contains only a `message_id` and a QoS level of 1. + * + * Helper function. + */ +static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd, + uint16_t message_id) { + uint16_t netbytes; + uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0); + + mg_send_mqtt_header(nc, cmd, flags, 2 /* len */); + + netbytes = htons(message_id); + mg_send(nc, &netbytes, 2); +} + +void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) { + mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id); +} + +void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) { + mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id); +} + +void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) { + mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id); +} + +void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) { + mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id); +} + +void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len, + uint16_t message_id) { + size_t i; + uint16_t netbytes; + + mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len); + + netbytes = htons(message_id); + mg_send(nc, &netbytes, 2); + + for (i = 0; i < qoss_len; i++) { + mg_send(nc, &qoss[i], 1); + } +} + +void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) { + mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id); +} + +void mg_mqtt_ping(struct mg_connection *nc) { + mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0); +} + +void mg_mqtt_pong(struct mg_connection *nc) { + mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0); +} + +void mg_mqtt_disconnect(struct mg_connection *nc) { + mg_send_mqtt_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0); +} + +#endif /* MG_ENABLE_MQTT */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_mqtt_server.c" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +/* Amalgamated: #include "mg_internal.h" */ +/* Amalgamated: #include "mg_mqtt_server.h" */ + +#if MG_ENABLE_MQTT_BROKER + +static void mg_mqtt_session_init(struct mg_mqtt_broker *brk, + struct mg_mqtt_session *s, + struct mg_connection *nc) { + s->brk = brk; + s->subscriptions = NULL; + s->num_subscriptions = 0; + s->nc = nc; +} + +static void mg_mqtt_add_session(struct mg_mqtt_session *s) { + LIST_INSERT_HEAD(&s->brk->sessions, s, link); +} + +static void mg_mqtt_remove_session(struct mg_mqtt_session *s) { + LIST_REMOVE(s, link); +} + +static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) { + size_t i; + for (i = 0; i < s->num_subscriptions; i++) { + MG_FREE((void *) s->subscriptions[i].topic); + } + MG_FREE(s->subscriptions); + MG_FREE(s); +} + +static void mg_mqtt_close_session(struct mg_mqtt_session *s) { + mg_mqtt_remove_session(s); + mg_mqtt_destroy_session(s); +} + +void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) { + LIST_INIT(&brk->sessions); + brk->user_data = user_data; +} + +static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk, + struct mg_connection *nc) { + struct mg_mqtt_session *s = + (struct mg_mqtt_session *) MG_CALLOC(1, sizeof *s); + if (s == NULL) { + /* LCOV_EXCL_START */ + mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE); + return; + /* LCOV_EXCL_STOP */ + } + + /* TODO(mkm): check header (magic and version) */ + + mg_mqtt_session_init(brk, s, nc); + nc->priv_2 = s; + mg_mqtt_add_session(s); + + mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED); +} + +static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc, + struct mg_mqtt_message *msg) { + struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->priv_2; + uint8_t qoss[MG_MQTT_MAX_SESSION_SUBSCRIPTIONS]; + size_t num_subs = 0; + struct mg_str topic; + uint8_t qos; + int pos; + struct mg_mqtt_topic_expression *te; + + for (pos = 0; + (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) { + if (num_subs >= sizeof(MG_MQTT_MAX_SESSION_SUBSCRIPTIONS) || + (ss->num_subscriptions + num_subs >= + MG_MQTT_MAX_SESSION_SUBSCRIPTIONS)) { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + return; + } + qoss[num_subs++] = qos; + } + + if (num_subs > 0) { + te = (struct mg_mqtt_topic_expression *) MG_REALLOC( + ss->subscriptions, + sizeof(*ss->subscriptions) * (ss->num_subscriptions + num_subs)); + if (te == NULL) { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + return; + } + ss->subscriptions = te; + for (pos = 0; + pos < (int) msg->payload.len && + (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1; + ss->num_subscriptions++) { + te = &ss->subscriptions[ss->num_subscriptions]; + te->topic = (char *) MG_MALLOC(topic.len + 1); + te->qos = qos; + memcpy((char *) te->topic, topic.p, topic.len); + ((char *) te->topic)[topic.len] = '\0'; + } + } + + if (pos == (int) msg->payload.len) { + mg_mqtt_suback(nc, qoss, num_subs, msg->message_id); + } else { + /* We did not fully parse the payload, something must be wrong. */ + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } +} + +static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk, + struct mg_mqtt_message *msg) { + struct mg_mqtt_session *s; + size_t i; + + for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) { + for (i = 0; i < s->num_subscriptions; i++) { + if (mg_mqtt_vmatch_topic_expression(s->subscriptions[i].topic, + msg->topic)) { + char buf[100], *p = buf; + mg_asprintf(&p, sizeof(buf), "%.*s", (int) msg->topic.len, + msg->topic.p); + if (p == NULL) { + return; + } + mg_mqtt_publish(s->nc, p, 0, 0, msg->payload.p, msg->payload.len); + if (p != buf) { + MG_FREE(p); + } + break; + } + } + } +} + +void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) { + struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data; + struct mg_mqtt_broker *brk; + + if (nc->listener) { + brk = (struct mg_mqtt_broker *) nc->listener->priv_2; + } else { + brk = (struct mg_mqtt_broker *) nc->priv_2; + } + + switch (ev) { + case MG_EV_ACCEPT: + if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc); + nc->priv_2 = NULL; /* Clear up the inherited pointer to broker */ + break; + case MG_EV_MQTT_CONNECT: + if (nc->priv_2 == NULL) { + mg_mqtt_broker_handle_connect(brk, nc); + } else { + /* Repeated CONNECT */ + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } + break; + case MG_EV_MQTT_SUBSCRIBE: + if (nc->priv_2 != NULL) { + mg_mqtt_broker_handle_subscribe(nc, msg); + } else { + /* Subscribe before CONNECT */ + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } + break; + case MG_EV_MQTT_PUBLISH: + if (nc->priv_2 != NULL) { + mg_mqtt_broker_handle_publish(brk, msg); + } else { + /* Publish before CONNECT */ + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } + break; + case MG_EV_CLOSE: + if (nc->listener && nc->priv_2 != NULL) { + mg_mqtt_close_session((struct mg_mqtt_session *) nc->priv_2); + } + break; + } +} + +struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk, + struct mg_mqtt_session *s) { + return s == NULL ? LIST_FIRST(&brk->sessions) : LIST_NEXT(s, link); +} + +#endif /* MG_ENABLE_MQTT_BROKER */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_dns.c" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +#if MG_ENABLE_DNS + +/* Amalgamated: #include "mg_internal.h" */ +/* Amalgamated: #include "mg_dns.h" */ + +static int mg_dns_tid = 0xa0; + +struct mg_dns_header { + uint16_t transaction_id; + uint16_t flags; + uint16_t num_questions; + uint16_t num_answers; + uint16_t num_authority_prs; + uint16_t num_other_prs; +}; + +struct mg_dns_resource_record *mg_dns_next_record( + struct mg_dns_message *msg, int query, + struct mg_dns_resource_record *prev) { + struct mg_dns_resource_record *rr; + + for (rr = (prev == NULL ? msg->answers : prev + 1); + rr - msg->answers < msg->num_answers; rr++) { + if (rr->rtype == query) { + return rr; + } + } + return NULL; +} + +int mg_dns_parse_record_data(struct mg_dns_message *msg, + struct mg_dns_resource_record *rr, void *data, + size_t data_len) { + switch (rr->rtype) { + case MG_DNS_A_RECORD: + if (data_len < sizeof(struct in_addr)) { + return -1; + } + if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) { + return -1; + } + memcpy(data, rr->rdata.p, data_len); + return 0; +#if MG_ENABLE_IPV6 + case MG_DNS_AAAA_RECORD: + if (data_len < sizeof(struct in6_addr)) { + return -1; /* LCOV_EXCL_LINE */ + } + memcpy(data, rr->rdata.p, data_len); + return 0; +#endif + case MG_DNS_CNAME_RECORD: + mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len); + return 0; + } + + return -1; +} + +int mg_dns_insert_header(struct mbuf *io, size_t pos, + struct mg_dns_message *msg) { + struct mg_dns_header header; + + memset(&header, 0, sizeof(header)); + header.transaction_id = msg->transaction_id; + header.flags = htons(msg->flags); + header.num_questions = htons(msg->num_questions); + header.num_answers = htons(msg->num_answers); + + return mbuf_insert(io, pos, &header, sizeof(header)); +} + +int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) { + unsigned char *begin, *end; + struct mg_dns_resource_record *last_q; + if (msg->num_questions <= 0) return 0; + begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header); + last_q = &msg->questions[msg->num_questions - 1]; + end = (unsigned char *) last_q->name.p + last_q->name.len + 4; + return mbuf_append(io, begin, end - begin); +} + +int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) { + const char *s; + unsigned char n; + size_t pos = io->len; + + do { + if ((s = strchr(name, '.')) == NULL) { + s = name + len; + } + + if (s - name > 127) { + return -1; /* TODO(mkm) cover */ + } + n = s - name; /* chunk length */ + mbuf_append(io, &n, 1); /* send length */ + mbuf_append(io, name, n); + + if (*s == '.') { + n++; + } + + name += n; + len -= n; + } while (*s != '\0'); + mbuf_append(io, "\0", 1); /* Mark end of host name */ + + return io->len - pos; +} + +int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr, + const char *name, size_t nlen, const void *rdata, + size_t rlen) { + size_t pos = io->len; + uint16_t u16; + uint32_t u32; + + if (rr->kind == MG_DNS_INVALID_RECORD) { + return -1; /* LCOV_EXCL_LINE */ + } + + if (mg_dns_encode_name(io, name, nlen) == -1) { + return -1; + } + + u16 = htons(rr->rtype); + mbuf_append(io, &u16, 2); + u16 = htons(rr->rclass); + mbuf_append(io, &u16, 2); + + if (rr->kind == MG_DNS_ANSWER) { + u32 = htonl(rr->ttl); + mbuf_append(io, &u32, 4); + + if (rr->rtype == MG_DNS_CNAME_RECORD) { + int clen; + /* fill size after encoding */ + size_t off = io->len; + mbuf_append(io, &u16, 2); + if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) { + return -1; + } + u16 = clen; + io->buf[off] = u16 >> 8; + io->buf[off + 1] = u16 & 0xff; + } else { + u16 = htons((uint16_t) rlen); + mbuf_append(io, &u16, 2); + mbuf_append(io, rdata, rlen); + } + } + + return io->len - pos; +} + +void mg_send_dns_query(struct mg_connection *nc, const char *name, + int query_type) { + struct mg_dns_message *msg = + (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg)); + struct mbuf pkt; + struct mg_dns_resource_record *rr = &msg->questions[0]; + + DBG(("%s %d", name, query_type)); + + mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */); + + msg->transaction_id = ++mg_dns_tid; + msg->flags = 0x100; + msg->num_questions = 1; + + mg_dns_insert_header(&pkt, 0, msg); + + rr->rtype = query_type; + rr->rclass = 1; /* Class: inet */ + rr->kind = MG_DNS_QUESTION; + + if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) { + /* TODO(mkm): return an error code */ + goto cleanup; /* LCOV_EXCL_LINE */ + } + + /* TCP DNS requires messages to be prefixed with len */ + if (!(nc->flags & MG_F_UDP)) { + uint16_t len = htons((uint16_t) pkt.len); + mbuf_insert(&pkt, 0, &len, 2); + } + + mg_send(nc, pkt.buf, pkt.len); + mbuf_free(&pkt); + +cleanup: + MG_FREE(msg); +} + +static unsigned char *mg_parse_dns_resource_record( + unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr, + int reply) { + unsigned char *name = data; + int chunk_len, data_len; + + while (data < end && (chunk_len = *data)) { + if (((unsigned char *) data)[0] & 0xc0) { + data += 1; + break; + } + data += chunk_len + 1; + } + + if (data > end - 5) { + return NULL; + } + + rr->name.p = (char *) name; + rr->name.len = data - name + 1; + data++; + + rr->rtype = data[0] << 8 | data[1]; + data += 2; + + rr->rclass = data[0] << 8 | data[1]; + data += 2; + + rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION; + if (reply) { + if (data >= end - 6) { + return NULL; + } + + rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 | + data[2] << 8 | data[3]; + data += 4; + + data_len = *data << 8 | *(data + 1); + data += 2; + + rr->rdata.p = (char *) data; + rr->rdata.len = data_len; + data += data_len; + } + return data; +} + +int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) { + struct mg_dns_header *header = (struct mg_dns_header *) buf; + unsigned char *data = (unsigned char *) buf + sizeof(*header); + unsigned char *end = (unsigned char *) buf + len; + int i; + + memset(msg, 0, sizeof(*msg)); + msg->pkt.p = buf; + msg->pkt.len = len; + + if (len < (int) sizeof(*header)) return -1; + + msg->transaction_id = header->transaction_id; + msg->flags = ntohs(header->flags); + msg->num_questions = ntohs(header->num_questions); + if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) { + msg->num_questions = (int) ARRAY_SIZE(msg->questions); + } + msg->num_answers = ntohs(header->num_answers); + if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) { + msg->num_answers = (int) ARRAY_SIZE(msg->answers); + } + + for (i = 0; i < msg->num_questions; i++) { + data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0); + if (data == NULL) return -1; + } + + for (i = 0; i < msg->num_answers; i++) { + data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1); + if (data == NULL) return -1; + } + + return 0; +} + +size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name, + char *dst, int dst_len) { + int chunk_len, num_ptrs = 0; + char *old_dst = dst; + const unsigned char *data = (unsigned char *) name->p; + const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len; + + if (data >= end) { + return 0; + } + + while ((chunk_len = *data++)) { + int leeway = dst_len - (dst - old_dst); + if (data >= end) { + return 0; + } + + if ((chunk_len & 0xc0) == 0xc0) { + uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0]; + if (off >= msg->pkt.len) { + return 0; + } + /* Basic circular loop avoidance: allow up to 16 pointer hops. */ + if (++num_ptrs > 15) { + return 0; + } + data = (unsigned char *) msg->pkt.p + off; + continue; + } + if (chunk_len > 63) { + return 0; + } + if (chunk_len > leeway) { + chunk_len = leeway; + } + + if (data + chunk_len >= end) { + return 0; + } + + memcpy(dst, data, chunk_len); + data += chunk_len; + dst += chunk_len; + leeway -= chunk_len; + if (leeway == 0) { + return dst - old_dst; + } + *dst++ = '.'; + } + + if (dst != old_dst) { + *--dst = 0; + } + return dst - old_dst; +} + +static void dns_handler(struct mg_connection *nc, int ev, + void *ev_data MG_UD_ARG(void *user_data)) { + struct mbuf *io = &nc->recv_mbuf; + struct mg_dns_message msg; + + /* Pass low-level events to the user handler */ + nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); + + switch (ev) { + case MG_EV_RECV: + if (!(nc->flags & MG_F_UDP)) { + mbuf_remove(&nc->recv_mbuf, 2); + } + if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) { + /* reply + recursion allowed + format error */ + memset(&msg, 0, sizeof(msg)); + msg.flags = 0x8081; + mg_dns_insert_header(io, 0, &msg); + if (!(nc->flags & MG_F_UDP)) { + uint16_t len = htons((uint16_t) io->len); + mbuf_insert(io, 0, &len, 2); + } + mg_send(nc, io->buf, io->len); + } else { + /* Call user handler with parsed message */ + nc->handler(nc, MG_DNS_MESSAGE, &msg MG_UD_ARG(user_data)); + } + mbuf_remove(io, io->len); + break; + } +} + +void mg_set_protocol_dns(struct mg_connection *nc) { + nc->proto_handler = dns_handler; +} + +#endif /* MG_ENABLE_DNS */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_dns_server.c" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +#if MG_ENABLE_DNS_SERVER + +/* Amalgamated: #include "mg_internal.h" */ +/* Amalgamated: #include "dns-server.h" */ + +struct mg_dns_reply mg_dns_create_reply(struct mbuf *io, + struct mg_dns_message *msg) { + struct mg_dns_reply rep; + rep.msg = msg; + rep.io = io; + rep.start = io->len; + + /* reply + recursion allowed */ + msg->flags |= 0x8080; + mg_dns_copy_questions(io, msg); + + msg->num_answers = 0; + return rep; +} + +void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) { + size_t sent = r->io->len - r->start; + mg_dns_insert_header(r->io, r->start, r->msg); + if (!(nc->flags & MG_F_UDP)) { + uint16_t len = htons((uint16_t) sent); + mbuf_insert(r->io, r->start, &len, 2); + } + + if (&nc->send_mbuf != r->io) { + mg_send(nc, r->io->buf + r->start, r->io->len - r->start); + r->io->len = r->start; + } +} + +int mg_dns_reply_record(struct mg_dns_reply *reply, + struct mg_dns_resource_record *question, + const char *name, int rtype, int ttl, const void *rdata, + size_t rdata_len) { + struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg; + char rname[512]; + struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers]; + if (msg->num_answers >= MG_MAX_DNS_ANSWERS) { + return -1; /* LCOV_EXCL_LINE */ + } + + if (name == NULL) { + name = rname; + rname[511] = 0; + mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1); + } + + *ans = *question; + ans->kind = MG_DNS_ANSWER; + ans->rtype = rtype; + ans->ttl = ttl; + + if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata, + rdata_len) == -1) { + return -1; /* LCOV_EXCL_LINE */ + }; + + msg->num_answers++; + return 0; +} + +#endif /* MG_ENABLE_DNS_SERVER */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_resolv.c" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +#if MG_ENABLE_ASYNC_RESOLVER + +/* Amalgamated: #include "mg_internal.h" */ +/* Amalgamated: #include "mg_resolv.h" */ + +#ifndef MG_DEFAULT_NAMESERVER +#define MG_DEFAULT_NAMESERVER "8.8.8.8" +#endif + +struct mg_resolve_async_request { + char name[1024]; + int query; + mg_resolve_callback_t callback; + void *data; + time_t timeout; + int max_retries; + enum mg_resolve_err err; + + /* state */ + time_t last_time; + int retries; +}; + +/* + * Find what nameserver to use. + * + * Return 0 if OK, -1 if error + */ +static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) { + int ret = -1; + +#ifdef _WIN32 + int i; + LONG err; + HKEY hKey, hSub; + wchar_t subkey[512], value[128], + *key = L"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces"; + + if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey)) != + ERROR_SUCCESS) { + fprintf(stderr, "cannot open reg key %S: %ld\n", key, err); + ret = -1; + } else { + for (ret = -1, i = 0; 1; i++) { + DWORD subkey_size = sizeof(subkey), type, len = sizeof(value); + if (RegEnumKeyExW(hKey, i, subkey, &subkey_size, NULL, NULL, NULL, + NULL) != ERROR_SUCCESS) { + break; + } + if (RegOpenKeyExW(hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS && + ((RegQueryValueExW(hSub, L"NameServer", 0, &type, (void *) value, + &len) == ERROR_SUCCESS && + value[0] != '\0') || + (RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value, + &len) == ERROR_SUCCESS && + value[0] != '\0'))) { + /* + * See https://github.com/cesanta/mongoose/issues/176 + * The value taken from the registry can be empty, a single + * IP address, or multiple IP addresses separated by comma. + * If it's empty, check the next interface. + * If it's multiple IP addresses, take the first one. + */ + wchar_t *comma = wcschr(value, ','); + if (comma != NULL) { + *comma = '\0'; + } + /* %S will convert wchar_t -> char */ + snprintf(name, name_len, "%S", value); + ret = 0; + RegCloseKey(hSub); + break; + } + } + RegCloseKey(hKey); + } +#elif MG_ENABLE_FILESYSTEM && defined(MG_RESOLV_CONF_FILE_NAME) + FILE *fp; + char line[512]; + + if ((fp = mg_fopen(MG_RESOLV_CONF_FILE_NAME, "r")) == NULL) { + ret = -1; + } else { + /* Try to figure out what nameserver to use */ + for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) { + unsigned int a, b, c, d; + if (sscanf(line, "nameserver %u.%u.%u.%u", &a, &b, &c, &d) == 4) { + snprintf(name, name_len, "%u.%u.%u.%u", a, b, c, d); + ret = 0; + break; + } + } + (void) fclose(fp); + } +#else + snprintf(name, name_len, "%s", MG_DEFAULT_NAMESERVER); +#endif /* _WIN32 */ + + return ret; +} + +int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) { +#if MG_ENABLE_FILESYSTEM && defined(MG_HOSTS_FILE_NAME) + /* TODO(mkm) cache /etc/hosts */ + FILE *fp; + char line[1024]; + char *p; + char alias[256]; + unsigned int a, b, c, d; + int len = 0; + + if ((fp = mg_fopen(MG_HOSTS_FILE_NAME, "r")) == NULL) { + return -1; + } + + for (; fgets(line, sizeof(line), fp) != NULL;) { + if (line[0] == '#') continue; + + if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) { + /* TODO(mkm): handle ipv6 */ + continue; + } + for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) { + if (strcmp(alias, name) == 0) { + usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d); + fclose(fp); + return 0; + } + } + } + + fclose(fp); +#else + (void) name; + (void) usa; +#endif + + return -1; +} + +static void mg_resolve_async_eh(struct mg_connection *nc, int ev, + void *data MG_UD_ARG(void *user_data)) { + time_t now = (time_t) mg_time(); + struct mg_resolve_async_request *req; + struct mg_dns_message *msg; +#if !MG_ENABLE_CALLBACK_USERDATA + void *user_data = nc->user_data; +#endif + + if (ev != MG_EV_POLL) { + DBG(("ev=%d user_data=%p", ev, user_data)); + } + + req = (struct mg_resolve_async_request *) user_data; + + if (req == NULL) { + return; + } + + switch (ev) { + case MG_EV_POLL: + if (req->retries > req->max_retries) { + req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT; + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + break; + } + if (nc->flags & MG_F_CONNECTING) break; + /* fallthrough */ + case MG_EV_CONNECT: + if (req->retries == 0 || now - req->last_time >= req->timeout) { + mg_send_dns_query(nc, req->name, req->query); + req->last_time = now; + req->retries++; + } + break; + case MG_EV_RECV: + msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg)); + if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 && + msg->num_answers > 0) { + req->callback(msg, req->data, MG_RESOLVE_OK); + nc->user_data = NULL; + MG_FREE(req); + } else { + req->err = MG_RESOLVE_NO_ANSWERS; + } + MG_FREE(msg); + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + break; + case MG_EV_SEND: + /* + * If a send error occurs, prevent closing of the connection by the core. + * We will retry after timeout. + */ + nc->flags &= ~MG_F_CLOSE_IMMEDIATELY; + mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len); + break; + case MG_EV_TIMER: + req->err = MG_RESOLVE_TIMEOUT; + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + break; + case MG_EV_CLOSE: + /* If we got here with request still not done, fire an error callback. */ + if (req != NULL) { + char addr[32]; + mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP); +#ifdef MG_LOG_DNS_FAILURES + LOG(LL_ERROR, ("Failed to resolve '%s', server %s", req->name, addr)); +#endif + req->callback(NULL, req->data, req->err); + nc->user_data = NULL; + MG_FREE(req); + } + break; + } +} + +int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query, + mg_resolve_callback_t cb, void *data) { + struct mg_resolve_async_opts opts; + memset(&opts, 0, sizeof(opts)); + return mg_resolve_async_opt(mgr, name, query, cb, data, opts); +} + +int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query, + mg_resolve_callback_t cb, void *data, + struct mg_resolve_async_opts opts) { + struct mg_resolve_async_request *req; + struct mg_connection *dns_nc; + const char *nameserver = opts.nameserver; + char dns_server_buff[17], nameserver_url[26]; + + if (nameserver == NULL) { + nameserver = mgr->nameserver; + } + + DBG(("%s %d %p", name, query, opts.dns_conn)); + + /* resolve with DNS */ + req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req)); + if (req == NULL) { + return -1; + } + + strncpy(req->name, name, sizeof(req->name)); + req->name[sizeof(req->name) - 1] = '\0'; + + req->query = query; + req->callback = cb; + req->data = data; + /* TODO(mkm): parse defaults out of resolve.conf */ + req->max_retries = opts.max_retries ? opts.max_retries : 2; + req->timeout = opts.timeout ? opts.timeout : 5; + + /* Lazily initialize dns server */ + if (nameserver == NULL) { + if (mg_get_ip_address_of_nameserver(dns_server_buff, + sizeof(dns_server_buff)) != -1) { + nameserver = dns_server_buff; + } else { + nameserver = MG_DEFAULT_NAMESERVER; + } + } + + snprintf(nameserver_url, sizeof(nameserver_url), "udp://%s:53", nameserver); + + dns_nc = mg_connect(mgr, nameserver_url, MG_CB(mg_resolve_async_eh, NULL)); + if (dns_nc == NULL) { + MG_FREE(req); + return -1; + } + dns_nc->user_data = req; + if (opts.dns_conn != NULL) { + *opts.dns_conn = dns_nc; + } + + return 0; +} + +void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver) { + MG_FREE((char *) mgr->nameserver); + mgr->nameserver = NULL; + if (nameserver != NULL) { + mgr->nameserver = strdup(nameserver); + } +} + +#endif /* MG_ENABLE_ASYNC_RESOLVER */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_coap.c" +#endif +/* + * Copyright (c) 2015 Cesanta Software Limited + * All rights reserved + * This software is dual-licensed: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. For the terms of this + * license, see . + * + * You are free to use this software under the terms of the GNU General + * Public License, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * Alternatively, you can license this software under a commercial + * license, as set out in . + */ + +/* Amalgamated: #include "mg_internal.h" */ +/* Amalgamated: #include "mg_coap.h" */ + +#if MG_ENABLE_COAP + +void mg_coap_free_options(struct mg_coap_message *cm) { + while (cm->options != NULL) { + struct mg_coap_option *next = cm->options->next; + MG_FREE(cm->options); + cm->options = next; + } +} + +struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm, + uint32_t number, char *value, + size_t len) { + struct mg_coap_option *new_option = + (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option)); + + new_option->number = number; + new_option->value.p = value; + new_option->value.len = len; + + if (cm->options == NULL) { + cm->options = cm->optiomg_tail = new_option; + } else { + /* + * A very simple attention to help clients to compose options: + * CoAP wants to see options ASC ordered. + * Could be change by using sort in coap_compose + */ + if (cm->optiomg_tail->number <= new_option->number) { + /* if option is already ordered just add it */ + cm->optiomg_tail = cm->optiomg_tail->next = new_option; + } else { + /* looking for appropriate position */ + struct mg_coap_option *current_opt = cm->options; + struct mg_coap_option *prev_opt = 0; + + while (current_opt != NULL) { + if (current_opt->number > new_option->number) { + break; + } + prev_opt = current_opt; + current_opt = current_opt->next; + } + + if (prev_opt != NULL) { + prev_opt->next = new_option; + new_option->next = current_opt; + } else { + /* insert new_option to the beginning */ + new_option->next = cm->options; + cm->options = new_option; + } + } + } + + return new_option; +} + +/* + * Fills CoAP header in mg_coap_message. + * + * Helper function. + */ +static char *coap_parse_header(char *ptr, struct mbuf *io, + struct mg_coap_message *cm) { + if (io->len < sizeof(uint32_t)) { + cm->flags |= MG_COAP_NOT_ENOUGH_DATA; + return NULL; + } + + /* + * Version (Ver): 2-bit unsigned integer. Indicates the CoAP version + * number. Implementations of this specification MUST set this field + * to 1 (01 binary). Other values are reserved for future versions. + * Messages with unknown version numbers MUST be silently ignored. + */ + if (((uint8_t) *ptr >> 6) != 1) { + cm->flags |= MG_COAP_IGNORE; + return NULL; + } + + /* + * Type (T): 2-bit unsigned integer. Indicates if this message is of + * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or + * Reset (3). + */ + cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4; + cm->flags |= MG_COAP_MSG_TYPE_FIELD; + + /* + * Token Length (TKL): 4-bit unsigned integer. Indicates the length of + * the variable-length Token field (0-8 bytes). Lengths 9-15 are + * reserved, MUST NOT be sent, and MUST be processed as a message + * format error. + */ + cm->token.len = *ptr & 0x0F; + if (cm->token.len > 8) { + cm->flags |= MG_COAP_FORMAT_ERROR; + return NULL; + } + + ptr++; + + /* + * Code: 8-bit unsigned integer, split into a 3-bit class (most + * significant bits) and a 5-bit detail (least significant bits) + */ + cm->code_class = (uint8_t) *ptr >> 5; + cm->code_detail = *ptr & 0x1F; + cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD); + + ptr++; + + /* Message ID: 16-bit unsigned integer in network byte order. */ + cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1); + cm->flags |= MG_COAP_MSG_ID_FIELD; + + ptr += 2; + + return ptr; +} + +/* + * Fills token information in mg_coap_message. + * + * Helper function. + */ +static char *coap_get_token(char *ptr, struct mbuf *io, + struct mg_coap_message *cm) { + if (cm->token.len != 0) { + if (ptr + cm->token.len > io->buf + io->len) { + cm->flags |= MG_COAP_NOT_ENOUGH_DATA; + return NULL; + } else { + cm->token.p = ptr; + ptr += cm->token.len; + cm->flags |= MG_COAP_TOKEN_FIELD; + } + } + + return ptr; +} + +/* + * Returns Option Delta or Length. + * + * Helper function. + */ +static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) { + int ret = 0; + + if (*opt_info == 13) { + /* + * 13: An 8-bit unsigned integer follows the initial byte and + * indicates the Option Delta/Length minus 13. + */ + if (ptr < io->buf + io->len) { + *opt_info = (uint8_t) *ptr + 13; + ret = sizeof(uint8_t); + } else { + ret = -1; /* LCOV_EXCL_LINE */ + } + } else if (*opt_info == 14) { + /* + * 14: A 16-bit unsigned integer in network byte order follows the + * initial byte and indicates the Option Delta/Length minus 269. + */ + if (ptr + sizeof(uint8_t) < io->buf + io->len) { + *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269; + ret = sizeof(uint16_t); + } else { + ret = -1; /* LCOV_EXCL_LINE */ + } + } + + return ret; +} + +/* + * Fills options in mg_coap_message. + * + * Helper function. + * + * General options format: + * +---------------+---------------+ + * | Option Delta | Option Length | 1 byte + * +---------------+---------------+ + * \ Option Delta (extended) \ 0-2 bytes + * +-------------------------------+ + * / Option Length (extended) \ 0-2 bytes + * +-------------------------------+ + * \ Option Value \ 0 or more bytes + * +-------------------------------+ + */ +static char *coap_get_options(char *ptr, struct mbuf *io, + struct mg_coap_message *cm) { + uint16_t prev_opt = 0; + + if (ptr == io->buf + io->len) { + /* end of packet, ok */ + return NULL; + } + + /* 0xFF is payload marker */ + while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) { + uint16_t option_delta, option_lenght; + int optinfo_len; + + /* Option Delta: 4-bit unsigned integer */ + option_delta = ((uint8_t) *ptr & 0xF0) >> 4; + /* Option Length: 4-bit unsigned integer */ + option_lenght = *ptr & 0x0F; + + if (option_delta == 15 || option_lenght == 15) { + /* + * 15: Reserved for future use. If the field is set to this value, + * it MUST be processed as a message format error + */ + cm->flags |= MG_COAP_FORMAT_ERROR; + break; + } + + ptr++; + + /* check for extended option delta */ + optinfo_len = coap_get_ext_opt(ptr, io, &option_delta); + if (optinfo_len == -1) { + cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ + break; /* LCOV_EXCL_LINE */ + } + + ptr += optinfo_len; + + /* check or extended option lenght */ + optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght); + if (optinfo_len == -1) { + cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ + break; /* LCOV_EXCL_LINE */ + } + + ptr += optinfo_len; + + /* + * Instead of specifying the Option Number directly, the instances MUST + * appear in order of their Option Numbers and a delta encoding is used + * between them. + */ + option_delta += prev_opt; + + mg_coap_add_option(cm, option_delta, ptr, option_lenght); + + prev_opt = option_delta; + + if (ptr + option_lenght > io->buf + io->len) { + cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ + break; /* LCOV_EXCL_LINE */ + } + + ptr += option_lenght; + } + + if ((cm->flags & MG_COAP_ERROR) != 0) { + mg_coap_free_options(cm); + return NULL; + } + + cm->flags |= MG_COAP_OPTIOMG_FIELD; + + if (ptr == io->buf + io->len) { + /* end of packet, ok */ + return NULL; + } + + ptr++; + + return ptr; +} + +uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) { + char *ptr; + + memset(cm, 0, sizeof(*cm)); + + if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) { + return cm->flags; + } + + if ((ptr = coap_get_token(ptr, io, cm)) == NULL) { + return cm->flags; + } + + if ((ptr = coap_get_options(ptr, io, cm)) == NULL) { + return cm->flags; + } + + /* the rest is payload */ + cm->payload.len = io->len - (ptr - io->buf); + if (cm->payload.len != 0) { + cm->payload.p = ptr; + cm->flags |= MG_COAP_PAYLOAD_FIELD; + } + + return cm->flags; +} + +/* + * Calculates extended size of given Opt Number/Length in coap message. + * + * Helper function. + */ +static size_t coap_get_ext_opt_size(uint32_t value) { + int ret = 0; + + if (value >= 13 && value <= 0xFF + 13) { + ret = sizeof(uint8_t); + } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) { + ret = sizeof(uint16_t); + } + + return ret; +} + +/* + * Splits given Opt Number/Length into base and ext values. + * + * Helper function. + */ +static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) { + int ret = 0; + + if (value < 13) { + *base = value; + } else if (value >= 13 && value <= 0xFF + 13) { + *base = 13; + *ext = value - 13; + ret = sizeof(uint8_t); + } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) { + *base = 14; + *ext = value - 269; + ret = sizeof(uint16_t); + } + + return ret; +} + +/* + * Puts uint16_t (in network order) into given char stream. + * + * Helper function. + */ +static char *coap_add_uint16(char *ptr, uint16_t val) { + *ptr = val >> 8; + ptr++; + *ptr = val & 0x00FF; + ptr++; + return ptr; +} + +/* + * Puts extended value of Opt Number/Length into given char stream. + * + * Helper function. + */ +static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) { + if (len == sizeof(uint8_t)) { + *ptr = (char) val; + ptr++; + } else if (len == sizeof(uint16_t)) { + ptr = coap_add_uint16(ptr, val); + } + + return ptr; +} + +/* + * Verifies given mg_coap_message and calculates message size for it. + * + * Helper function. + */ +static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm, + size_t *len) { + struct mg_coap_option *opt; + uint32_t prev_opt_number; + + *len = 4; /* header */ + if (cm->msg_type > MG_COAP_MSG_MAX) { + return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD; + } + if (cm->token.len > 8) { + return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD; + } + if (cm->code_class > 7) { + return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD; + } + if (cm->code_detail > 31) { + return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD; + } + + *len += cm->token.len; + if (cm->payload.len != 0) { + *len += cm->payload.len + 1; /* ... + 1; add payload marker */ + } + + opt = cm->options; + prev_opt_number = 0; + while (opt != NULL) { + *len += 1; /* basic delta/length */ + *len += coap_get_ext_opt_size(opt->number - prev_opt_number); + *len += coap_get_ext_opt_size((uint32_t) opt->value.len); + /* + * Current implementation performs check if + * option_number > previous option_number and produces an error + * TODO(alashkin): write design doc with limitations + * May be resorting is more suitable solution. + */ + if ((opt->next != NULL && opt->number > opt->next->number) || + opt->value.len > 0xFFFF + 269 || + opt->number - prev_opt_number > 0xFFFF + 269) { + return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD; + } + *len += opt->value.len; + prev_opt_number = opt->number; + opt = opt->next; + } + + return 0; +} + +uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) { + struct mg_coap_option *opt; + uint32_t res, prev_opt_number; + size_t prev_io_len, packet_size; + char *ptr; + + res = coap_calculate_packet_size(cm, &packet_size); + if (res != 0) { + return res; + } + + /* saving previous lenght to handle non-empty mbuf */ + prev_io_len = io->len; + if (mbuf_append(io, NULL, packet_size) == 0) return MG_COAP_ERROR; + ptr = io->buf + prev_io_len; + + /* + * since cm is verified, it is possible to use bits shift operator + * without additional zeroing of unused bits + */ + + /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */ + *ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len); + ptr++; + + /* code class: 3 bits, code detail: 5 bits */ + *ptr = (cm->code_class << 5) | (cm->code_detail); + ptr++; + + ptr = coap_add_uint16(ptr, cm->msg_id); + + if (cm->token.len != 0) { + memcpy(ptr, cm->token.p, cm->token.len); + ptr += cm->token.len; + } + + opt = cm->options; + prev_opt_number = 0; + while (opt != NULL) { + uint8_t delta_base = 0, length_base = 0; + uint16_t delta_ext = 0, length_ext = 0; + + size_t opt_delta_len = + coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext); + size_t opt_lenght_len = + coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext); + + *ptr = (delta_base << 4) | length_base; + ptr++; + + ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len); + ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len); + + if (opt->value.len != 0) { + memcpy(ptr, opt->value.p, opt->value.len); + ptr += opt->value.len; + } + + prev_opt_number = opt->number; + opt = opt->next; + } + + if (cm->payload.len != 0) { + *ptr = (char) -1; + ptr++; + memcpy(ptr, cm->payload.p, cm->payload.len); + } + + return 0; +} + +uint32_t mg_coap_send_message(struct mg_connection *nc, + struct mg_coap_message *cm) { + struct mbuf packet_out; + uint32_t compose_res; + + mbuf_init(&packet_out, 0); + compose_res = mg_coap_compose(cm, &packet_out); + if (compose_res != 0) { + return compose_res; /* LCOV_EXCL_LINE */ + } + + mg_send(nc, packet_out.buf, (int) packet_out.len); + mbuf_free(&packet_out); + + return 0; +} + +uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) { + struct mg_coap_message cm; + memset(&cm, 0, sizeof(cm)); + cm.msg_type = MG_COAP_MSG_ACK; + cm.msg_id = msg_id; + + return mg_coap_send_message(nc, &cm); +} + +static void coap_handler(struct mg_connection *nc, int ev, + void *ev_data MG_UD_ARG(void *user_data)) { + struct mbuf *io = &nc->recv_mbuf; + struct mg_coap_message cm; + uint32_t parse_res; + + memset(&cm, 0, sizeof(cm)); + + nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); + + switch (ev) { + case MG_EV_RECV: + parse_res = mg_coap_parse(io, &cm); + if ((parse_res & MG_COAP_IGNORE) == 0) { + if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) { + /* + * Since we support UDP only + * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR + */ + cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */ + } /* LCOV_EXCL_LINE */ + nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type, + &cm MG_UD_ARG(user_data)); + } + + mg_coap_free_options(&cm); + mbuf_remove(io, io->len); + break; + } +} +/* + * Attach built-in CoAP event handler to the given connection. + * + * The user-defined event handler will receive following extra events: + * + * - MG_EV_COAP_CON + * - MG_EV_COAP_NOC + * - MG_EV_COAP_ACK + * - MG_EV_COAP_RST + */ +int mg_set_protocol_coap(struct mg_connection *nc) { + /* supports UDP only */ + if ((nc->flags & MG_F_UDP) == 0) { + return -1; + } + + nc->proto_handler = coap_handler; + + return 0; +} + +#endif /* MG_ENABLE_COAP */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_sntp.c" +#endif +/* + * Copyright (c) 2016 Cesanta Software Limited + * All rights reserved + */ + +/* Amalgamated: #include "mg_internal.h" */ +/* Amalgamated: #include "mg_sntp.h" */ +/* Amalgamated: #include "mg_util.h" */ + +#if MG_ENABLE_SNTP + +#define SNTP_TIME_OFFSET 2208988800 + +#ifndef SNTP_TIMEOUT +#define SNTP_TIMEOUT 10 +#endif + +#ifndef SNTP_ATTEMPTS +#define SNTP_ATTEMPTS 3 +#endif + +static uint64_t mg_get_sec(uint64_t val) { + return (val & 0xFFFFFFFF00000000) >> 32; +} + +static uint64_t mg_get_usec(uint64_t val) { + uint64_t tmp = (val & 0x00000000FFFFFFFF); + tmp *= 1000000; + tmp >>= 32; + return tmp; +} + +static void mg_ntp_to_tv(uint64_t val, struct timeval *tv) { + uint64_t tmp; + tmp = mg_get_sec(val); + tmp -= SNTP_TIME_OFFSET; + tv->tv_sec = tmp; + tv->tv_usec = mg_get_usec(val); +} + +static void mg_get_ntp_ts(const char *ntp, uint64_t *val) { + uint32_t tmp; + memcpy(&tmp, ntp, sizeof(tmp)); + tmp = ntohl(tmp); + *val = (uint64_t) tmp << 32; + memcpy(&tmp, ntp + 4, sizeof(tmp)); + tmp = ntohl(tmp); + *val |= tmp; +} + +void mg_sntp_send_request(struct mg_connection *c) { + uint8_t buf[48] = {0}; + /* + * header - 8 bit: + * LI (2 bit) - 3 (not in sync), VN (3 bit) - 4 (version), + * mode (3 bit) - 3 (client) + */ + buf[0] = (3 << 6) | (4 << 3) | 3; + +/* + * Next fields should be empty in client request + * stratum, 8 bit + * poll interval, 8 bit + * rrecision, 8 bit + * root delay, 32 bit + * root dispersion, 32 bit + * ref id, 32 bit + * ref timestamp, 64 bit + * originate Timestamp, 64 bit + * receive Timestamp, 64 bit +*/ + +/* + * convert time to sntp format (sntp starts from 00:00:00 01.01.1900) + * according to rfc868 it is 2208988800L sec + * this information is used to correct roundtrip delay + * but if local clock is absolutely broken (and doesn't work even + * as simple timer), it is better to disable it +*/ +#ifndef MG_SNTP_NO_DELAY_CORRECTION + uint32_t sec; + sec = htonl((uint32_t)(mg_time() + SNTP_TIME_OFFSET)); + memcpy(&buf[40], &sec, sizeof(sec)); +#endif + + mg_send(c, buf, sizeof(buf)); +} + +#ifndef MG_SNTP_NO_DELAY_CORRECTION +static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) { + /* roundloop delay = (T4 - T1) - (T3 - T2) */ + uint64_t d1 = ((mg_time() + SNTP_TIME_OFFSET) * 1000000) - + (mg_get_sec(t1) * 1000000 + mg_get_usec(t1)); + uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) - + (mg_get_sec(t2) * 1000000 + mg_get_usec(t2)); + + return (d1 > d2) ? d1 - d2 : 0; +} +#endif + +MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len, + struct mg_sntp_message *msg) { + uint8_t hdr; + uint64_t trsm_ts_T3, delay = 0; + int mode; + struct timeval tv; + + if (len < 48) { + return -1; + } + + hdr = buf[0]; + + if ((hdr & 0x38) >> 3 != 4) { + /* Wrong version */ + return -1; + } + + mode = hdr & 0x7; + if (mode != 4 && mode != 5) { + /* Not a server reply */ + return -1; + } + + memset(msg, 0, sizeof(*msg)); + + msg->kiss_of_death = (buf[1] == 0); /* Server asks to not send requests */ + + mg_get_ntp_ts(&buf[40], &trsm_ts_T3); + +#ifndef MG_SNTP_NO_DELAY_CORRECTION + { + uint64_t orig_ts_T1, recv_ts_T2; + mg_get_ntp_ts(&buf[24], &orig_ts_T1); + mg_get_ntp_ts(&buf[32], &recv_ts_T2); + delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3); + } +#endif + + mg_ntp_to_tv(trsm_ts_T3, &tv); + + msg->time = (double) tv.tv_sec + (((double) tv.tv_usec + delay) / 1000000.0); + + return 0; +} + +static void mg_sntp_handler(struct mg_connection *c, int ev, + void *ev_data MG_UD_ARG(void *user_data)) { + struct mbuf *io = &c->recv_mbuf; + struct mg_sntp_message msg; + + c->handler(c, ev, ev_data MG_UD_ARG(user_data)); + + switch (ev) { + case MG_EV_RECV: { + if (mg_sntp_parse_reply(io->buf, io->len, &msg) < 0) { + DBG(("Invalid SNTP packet received (%d)", (int) io->len)); + c->handler(c, MG_SNTP_MALFORMED_REPLY, NULL MG_UD_ARG(user_data)); + } else { + c->handler(c, MG_SNTP_REPLY, (void *) &msg MG_UD_ARG(user_data)); + } + + mbuf_remove(io, io->len); + break; + } + } +} + +int mg_set_protocol_sntp(struct mg_connection *c) { + if ((c->flags & MG_F_UDP) == 0) { + return -1; + } + + c->proto_handler = mg_sntp_handler; + + return 0; +} + +struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, + MG_CB(mg_event_handler_t event_handler, + void *user_data), + const char *sntp_server_name) { + struct mg_connection *c = NULL; + char url[100], *p_url = url; + const char *proto = "", *port = "", *tmp; + + /* If port is not specified, use default (123) */ + tmp = strchr(sntp_server_name, ':'); + if (tmp != NULL && *(tmp + 1) == '/') { + tmp = strchr(tmp + 1, ':'); + } + + if (tmp == NULL) { + port = ":123"; + } + + /* Add udp:// if needed */ + if (strncmp(sntp_server_name, "udp://", 6) != 0) { + proto = "udp://"; + } + + mg_asprintf(&p_url, sizeof(url), "%s%s%s", proto, sntp_server_name, port); + + c = mg_connect(mgr, p_url, event_handler MG_UD_ARG(user_data)); + + if (c == NULL) { + goto cleanup; + } + + mg_set_protocol_sntp(c); + +cleanup: + if (p_url != url) { + MG_FREE(p_url); + } + + return c; +} + +struct sntp_data { + mg_event_handler_t hander; + int count; +}; + +static void mg_sntp_util_ev_handler(struct mg_connection *c, int ev, + void *ev_data MG_UD_ARG(void *user_data)) { +#if !MG_ENABLE_CALLBACK_USERDATA + void *user_data = c->user_data; +#endif + struct sntp_data *sd = (struct sntp_data *) user_data; + + switch (ev) { + case MG_EV_CONNECT: + if (*(int *) ev_data != 0) { + mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); + break; + } + /* fallthrough */ + case MG_EV_TIMER: + if (sd->count <= SNTP_ATTEMPTS) { + mg_sntp_send_request(c); + mg_set_timer(c, mg_time() + 10); + sd->count++; + } else { + mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); + c->flags |= MG_F_CLOSE_IMMEDIATELY; + } + break; + case MG_SNTP_MALFORMED_REPLY: + mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); + c->flags |= MG_F_CLOSE_IMMEDIATELY; + break; + case MG_SNTP_REPLY: + mg_call(c, sd->hander, c->user_data, MG_SNTP_REPLY, ev_data); + c->flags |= MG_F_CLOSE_IMMEDIATELY; + break; + case MG_EV_CLOSE: + MG_FREE(user_data); + c->user_data = NULL; + break; + } +} + +struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr, + mg_event_handler_t event_handler, + const char *sntp_server_name) { + struct mg_connection *c; + struct sntp_data *sd = (struct sntp_data *) MG_CALLOC(1, sizeof(*sd)); + if (sd == NULL) { + return NULL; + } + + c = mg_sntp_connect(mgr, MG_CB(mg_sntp_util_ev_handler, sd), + sntp_server_name); + if (c == NULL) { + MG_FREE(sd); + return NULL; + } + + sd->hander = event_handler; +#if !MG_ENABLE_CALLBACK_USERDATA + c->user_data = sd; +#endif + + return c; +} + +#endif /* MG_ENABLE_SNTP */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_socks.c" +#endif +/* + * Copyright (c) 2017 Cesanta Software Limited + * All rights reserved + */ + +#if MG_ENABLE_SOCKS + +/* Amalgamated: #include "mg_socks.h" */ +/* Amalgamated: #include "mg_internal.h" */ + +/* + * https://www.ietf.org/rfc/rfc1928.txt paragraph 3, handle client handshake + * + * +----+----------+----------+ + * |VER | NMETHODS | METHODS | + * +----+----------+----------+ + * | 1 | 1 | 1 to 255 | + * +----+----------+----------+ + */ +static void mg_socks5_handshake(struct mg_connection *c) { + struct mbuf *r = &c->recv_mbuf; + if (r->buf[0] != MG_SOCKS_VERSION) { + c->flags |= MG_F_CLOSE_IMMEDIATELY; + } else if (r->len > 2 && (size_t) r->buf[1] + 2 <= r->len) { + /* https://www.ietf.org/rfc/rfc1928.txt paragraph 3 */ + unsigned char reply[2] = {MG_SOCKS_VERSION, MG_SOCKS_HANDSHAKE_FAILURE}; + int i; + for (i = 2; i < r->buf[1] + 2; i++) { + /* TODO(lsm): support other auth methods */ + if (r->buf[i] == MG_SOCKS_HANDSHAKE_NOAUTH) reply[1] = r->buf[i]; + } + mbuf_remove(r, 2 + r->buf[1]); + mg_send(c, reply, sizeof(reply)); + c->flags |= MG_SOCKS_HANDSHAKE_DONE; /* Mark handshake done */ + } +} + +static void disband(struct mg_connection *c) { + struct mg_connection *c2 = (struct mg_connection *) c->user_data; + if (c2 != NULL) { + c2->flags |= MG_F_SEND_AND_CLOSE; + c2->user_data = NULL; + } + c->flags |= MG_F_SEND_AND_CLOSE; + c->user_data = NULL; +} + +static void relay_data(struct mg_connection *c) { + struct mg_connection *c2 = (struct mg_connection *) c->user_data; + if (c2 != NULL) { + mg_send(c2, c->recv_mbuf.buf, c->recv_mbuf.len); + mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len); + } else { + c->flags |= MG_F_SEND_AND_CLOSE; + } +} + +static void serv_ev_handler(struct mg_connection *c, int ev, void *ev_data) { + if (ev == MG_EV_CLOSE) { + disband(c); + } else if (ev == MG_EV_RECV) { + relay_data(c); + } else if (ev == MG_EV_CONNECT) { + int res = *(int *) ev_data; + if (res != 0) LOG(LL_ERROR, ("connect error: %d", res)); + } +} + +static void mg_socks5_connect(struct mg_connection *c, const char *addr) { + struct mg_connection *serv = mg_connect(c->mgr, addr, serv_ev_handler); + serv->user_data = c; + c->user_data = serv; +} + +/* + * Request, https://www.ietf.org/rfc/rfc1928.txt paragraph 4 + * + * +----+-----+-------+------+----------+----------+ + * |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | + * +----+-----+-------+------+----------+----------+ + * | 1 | 1 | X'00' | 1 | Variable | 2 | + * +----+-----+-------+------+----------+----------+ + */ +static void mg_socks5_handle_request(struct mg_connection *c) { + struct mbuf *r = &c->recv_mbuf; + unsigned char *p = (unsigned char *) r->buf; + unsigned char addr_len = 4, reply = MG_SOCKS_SUCCESS; + int ver, cmd, atyp; + char addr[300]; + + if (r->len < 8) return; /* return if not fully buffered. min DST.ADDR is 2 */ + ver = p[0]; + cmd = p[1]; + atyp = p[3]; + + /* TODO(lsm): support other commands */ + if (ver != MG_SOCKS_VERSION || cmd != MG_SOCKS_CMD_CONNECT) { + reply = MG_SOCKS_CMD_NOT_SUPPORTED; + } else if (atyp == MG_SOCKS_ADDR_IPV4) { + addr_len = 4; + if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ + snprintf(addr, sizeof(addr), "%d.%d.%d.%d:%d", p[4], p[5], p[6], p[7], + p[8] << 8 | p[9]); + mg_socks5_connect(c, addr); + } else if (atyp == MG_SOCKS_ADDR_IPV6) { + addr_len = 16; + if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ + snprintf(addr, sizeof(addr), "[%x:%x:%x:%x:%x:%x:%x:%x]:%d", + p[4] << 8 | p[5], p[6] << 8 | p[7], p[8] << 8 | p[9], + p[10] << 8 | p[11], p[12] << 8 | p[13], p[14] << 8 | p[15], + p[16] << 8 | p[17], p[18] << 8 | p[19], p[20] << 8 | p[21]); + mg_socks5_connect(c, addr); + } else if (atyp == MG_SOCKS_ADDR_DOMAIN) { + addr_len = p[4] + 1; + if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ + snprintf(addr, sizeof(addr), "%.*s:%d", p[4], p + 5, + p[4 + addr_len] << 8 | p[4 + addr_len + 1]); + mg_socks5_connect(c, addr); + } else { + reply = MG_SOCKS_ADDR_NOT_SUPPORTED; + } + + /* + * Reply, https://www.ietf.org/rfc/rfc1928.txt paragraph 5 + * + * +----+-----+-------+------+----------+----------+ + * |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | + * +----+-----+-------+------+----------+----------+ + * | 1 | 1 | X'00' | 1 | Variable | 2 | + * +----+-----+-------+------+----------+----------+ + */ + { + unsigned char buf[] = {MG_SOCKS_VERSION, reply, 0}; + mg_send(c, buf, sizeof(buf)); + } + mg_send(c, r->buf + 3, addr_len + 1 + 2); + + mbuf_remove(r, 6 + addr_len); /* Remove request from the input stream */ + c->flags |= MG_SOCKS_CONNECT_DONE; /* Mark ourselves as connected */ +} + +static void socks_handler(struct mg_connection *c, int ev, void *ev_data) { + if (ev == MG_EV_RECV) { + if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) mg_socks5_handshake(c); + if (c->flags & MG_SOCKS_HANDSHAKE_DONE && + !(c->flags & MG_SOCKS_CONNECT_DONE)) { + mg_socks5_handle_request(c); + } + if (c->flags & MG_SOCKS_CONNECT_DONE) relay_data(c); + } else if (ev == MG_EV_CLOSE) { + disband(c); + } + (void) ev_data; +} + +void mg_set_protocol_socks(struct mg_connection *c) { + c->proto_handler = socks_handler; +} +#endif +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/cc3200/cc3200_libc.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if CS_PLATFORM == CS_P_CC3200 + +/* Amalgamated: #include "common/mg_mem.h" */ +#include +#include + +#ifndef __TI_COMPILER_VERSION__ +#include +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +#define CONSOLE_UART UARTA0_BASE + +#ifdef __TI_COMPILER_VERSION__ +int asprintf(char **strp, const char *fmt, ...) { + va_list ap; + int len; + + *strp = MG_MALLOC(BUFSIZ); + if (*strp == NULL) return -1; + + va_start(ap, fmt); + len = vsnprintf(*strp, BUFSIZ, fmt, ap); + va_end(ap); + + if (len > 0) { + *strp = MG_REALLOC(*strp, len + 1); + if (*strp == NULL) return -1; + } + + if (len >= BUFSIZ) { + va_start(ap, fmt); + len = vsnprintf(*strp, len + 1, fmt, ap); + va_end(ap); + } + + return len; +} + +#if MG_TI_NO_HOST_INTERFACE +time_t HOSTtime() { + struct timeval tp; + gettimeofday(&tp, NULL); + return tp.tv_sec; +} +#endif + +#endif /* __TI_COMPILER_VERSION__ */ + +void fprint_str(FILE *fp, const char *str) { + while (*str != '\0') { + if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r'); + MAP_UARTCharPut(CONSOLE_UART, *str++); + } +} + +void _exit(int status) { + fprint_str(stderr, "_exit\n"); + /* cause an unaligned access exception, that will drop you into gdb */ + *(int *) 1 = status; + while (1) + ; /* avoid gcc warning because stdlib abort() has noreturn attribute */ +} + +void _not_implemented(const char *what) { + fprint_str(stderr, what); + fprint_str(stderr, " is not implemented\n"); + _exit(42); +} + +int _kill(int pid, int sig) { + (void) pid; + (void) sig; + _not_implemented("_kill"); + return -1; +} + +int _getpid() { + fprint_str(stderr, "_getpid is not implemented\n"); + return 42; +} + +int _isatty(int fd) { + /* 0, 1 and 2 are TTYs. */ + return fd < 2; +} + +#endif /* CS_PLATFORM == CS_P_CC3200 */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/msp432/msp432_libc.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if CS_PLATFORM == CS_P_MSP432 + +#include +#include + +int gettimeofday(struct timeval *tp, void *tzp) { + uint32_t ticks = Clock_getTicks(); + tp->tv_sec = ticks / 1000; + tp->tv_usec = (ticks % 1000) * 1000; + return 0; +} + +#endif /* CS_PLATFORM == CS_P_MSP432 */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/nrf5/nrf5_libc.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \ + defined(__ARMCC_VERSION) +int gettimeofday(struct timeval *tp, void *tzp) { + /* TODO */ + tp->tv_sec = 0; + tp->tv_usec = 0; + return 0; +} +#endif +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/simplelink/sl_fs_slfs.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ +#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ + +#if defined(MG_FS_SLFS) + +#include +#ifndef __TI_COMPILER_VERSION__ +#include +#include +#endif + +#define MAX_OPEN_SLFS_FILES 8 + +/* Indirect libc interface - same functions, different names. */ +int fs_slfs_open(const char *pathname, int flags, mode_t mode); +int fs_slfs_close(int fd); +ssize_t fs_slfs_read(int fd, void *buf, size_t count); +ssize_t fs_slfs_write(int fd, const void *buf, size_t count); +int fs_slfs_stat(const char *pathname, struct stat *s); +int fs_slfs_fstat(int fd, struct stat *s); +off_t fs_slfs_lseek(int fd, off_t offset, int whence); +int fs_slfs_unlink(const char *filename); +int fs_slfs_rename(const char *from, const char *to); + +void fs_slfs_set_file_size(const char *name, size_t size); +void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token); +void fs_slfs_unset_file_flags(const char *name); + +#endif /* defined(MG_FS_SLFS) */ + +#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/simplelink/sl_fs_slfs.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Standard libc interface to TI SimpleLink FS. */ + +#if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) + +/* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */ + +#include + +#if CS_PLATFORM == CS_P_CC3200 +#include +#endif + +/* Amalgamated: #include "common/cs_dbg.h" */ +/* Amalgamated: #include "common/mg_mem.h" */ + +#if SL_MAJOR_VERSION_NUM < 2 +int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) { + _i32 fh; + _i32 r = sl_FsOpen(fname, flags, (unsigned long *) token, &fh); + return (r < 0 ? r : fh); +} +#else /* SL_MAJOR_VERSION_NUM >= 2 */ +int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) { + return sl_FsOpen(fname, flags, (unsigned long *) token); +} +#endif + +/* From sl_fs.c */ +int set_errno(int e); +const char *drop_dir(const char *fname, bool *is_slfs); + +/* + * With SLFS, you have to pre-declare max file size. Yes. Really. + * 64K should be enough for everyone. Right? + */ +#ifndef FS_SLFS_MAX_FILE_SIZE +#define FS_SLFS_MAX_FILE_SIZE (64 * 1024) +#endif + +struct sl_file_open_info { + char *name; + size_t size; + uint32_t flags; + uint32_t *token; +}; + +struct sl_fd_info { + _i32 fh; + _off_t pos; + size_t size; +}; + +static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES]; +static struct sl_file_open_info s_sl_file_open_infos[MAX_OPEN_SLFS_FILES]; + +static struct sl_file_open_info *fs_slfs_find_foi(const char *name, + bool create); + +static int sl_fs_to_errno(_i32 r) { + DBG(("SL error: %d", (int) r)); + switch (r) { + case SL_FS_OK: + return 0; + case SL_ERROR_FS_FILE_NAME_EXIST: + return EEXIST; + case SL_ERROR_FS_WRONG_FILE_NAME: + return EINVAL; + case SL_ERROR_FS_NO_AVAILABLE_NV_INDEX: + case SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE: + return ENOSPC; + case SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM: + return ENOMEM; + case SL_ERROR_FS_FILE_NOT_EXISTS: + return ENOENT; + case SL_ERROR_FS_NOT_SUPPORTED: + return ENOTSUP; + } + return ENXIO; +} + +int fs_slfs_open(const char *pathname, int flags, mode_t mode) { + int fd; + for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) { + if (s_sl_fds[fd].fh <= 0) break; + } + if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM); + struct sl_fd_info *fi = &s_sl_fds[fd]; + + /* + * Apply path manipulations again, in case we got here directly + * (via TI libc's "add_device"). + */ + pathname = drop_dir(pathname, NULL); + + _u32 am = 0; + fi->size = (size_t) -1; + int rw = (flags & 3); + size_t new_size = 0; + struct sl_file_open_info *foi = + fs_slfs_find_foi(pathname, false /* create */); + if (foi != NULL) { + LOG(LL_DEBUG, ("FOI for %s: %d 0x%x %p", pathname, (int) foi->size, + (unsigned int) foi->flags, foi->token)); + } + if (rw == O_RDONLY) { + SlFsFileInfo_t sl_fi; + _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi); + if (r == SL_FS_OK) { + fi->size = SL_FI_FILE_SIZE(sl_fi); + } + am = SL_FS_READ; + } else { + if (!(flags & O_TRUNC) || (flags & O_APPEND)) { + // FailFS files cannot be opened for append and will be truncated + // when opened for write. + return set_errno(ENOTSUP); + } + if (flags & O_CREAT) { + if (foi->size > 0) { + new_size = foi->size; + } else { + new_size = FS_SLFS_MAX_FILE_SIZE; + } + am = FS_MODE_OPEN_CREATE(new_size, 0); + } else { + am = SL_FS_WRITE; + } +#if SL_MAJOR_VERSION_NUM >= 2 + am |= SL_FS_OVERWRITE; +#endif + } + uint32_t *token = NULL; + if (foi != NULL) { + am |= foi->flags; + token = foi->token; + } + fi->fh = slfs_open((_u8 *) pathname, am, token); + LOG(LL_DEBUG, ("sl_FsOpen(%s, 0x%x, %p) sz %u = %d", pathname, (int) am, + token, (unsigned int) new_size, (int) fi->fh)); + int r; + if (fi->fh >= 0) { + fi->pos = 0; + r = fd; + } else { + r = set_errno(sl_fs_to_errno(fi->fh)); + } + return r; +} + +int fs_slfs_close(int fd) { + struct sl_fd_info *fi = &s_sl_fds[fd]; + if (fi->fh <= 0) return set_errno(EBADF); + _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0); + LOG(LL_DEBUG, ("sl_FsClose(%d) = %d", (int) fi->fh, (int) r)); + s_sl_fds[fd].fh = -1; + return set_errno(sl_fs_to_errno(r)); +} + +ssize_t fs_slfs_read(int fd, void *buf, size_t count) { + struct sl_fd_info *fi = &s_sl_fds[fd]; + if (fi->fh <= 0) return set_errno(EBADF); + /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE. + */ + if (fi->pos == fi->size) return 0; + _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count); + DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count, + (int) r)); + if (r >= 0) { + fi->pos += r; + return r; + } + return set_errno(sl_fs_to_errno(r)); +} + +ssize_t fs_slfs_write(int fd, const void *buf, size_t count) { + struct sl_fd_info *fi = &s_sl_fds[fd]; + if (fi->fh <= 0) return set_errno(EBADF); + _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count); + DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count, + (int) r)); + if (r >= 0) { + fi->pos += r; + return r; + } + return set_errno(sl_fs_to_errno(r)); +} + +int fs_slfs_stat(const char *pathname, struct stat *s) { + SlFsFileInfo_t sl_fi; + /* + * Apply path manipulations again, in case we got here directly + * (via TI libc's "add_device"). + */ + pathname = drop_dir(pathname, NULL); + _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi); + if (r == SL_FS_OK) { + s->st_mode = S_IFREG | 0666; + s->st_nlink = 1; + s->st_size = SL_FI_FILE_SIZE(sl_fi); + return 0; + } + return set_errno(sl_fs_to_errno(r)); +} + +int fs_slfs_fstat(int fd, struct stat *s) { + struct sl_fd_info *fi = &s_sl_fds[fd]; + if (fi->fh <= 0) return set_errno(EBADF); + s->st_mode = 0666; + s->st_mode = S_IFREG | 0666; + s->st_nlink = 1; + s->st_size = fi->size; + return 0; +} + +off_t fs_slfs_lseek(int fd, off_t offset, int whence) { + if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF); + switch (whence) { + case SEEK_SET: + s_sl_fds[fd].pos = offset; + break; + case SEEK_CUR: + s_sl_fds[fd].pos += offset; + break; + case SEEK_END: + return set_errno(ENOTSUP); + } + return 0; +} + +int fs_slfs_unlink(const char *pathname) { + /* + * Apply path manipulations again, in case we got here directly + * (via TI libc's "add_device"). + */ + pathname = drop_dir(pathname, NULL); + return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0))); +} + +int fs_slfs_rename(const char *from, const char *to) { + return set_errno(ENOTSUP); +} + +static struct sl_file_open_info *fs_slfs_find_foi(const char *name, + bool create) { + int i = 0; + for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) { + if (s_sl_file_open_infos[i].name != NULL && + strcmp(drop_dir(s_sl_file_open_infos[i].name, NULL), name) == 0) { + break; + } + } + if (i != MAX_OPEN_SLFS_FILES) return &s_sl_file_open_infos[i]; + if (!create) return NULL; + for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) { + if (s_sl_file_open_infos[i].name == NULL) break; + } + if (i == MAX_OPEN_SLFS_FILES) { + i = 0; /* Evict a random slot. */ + } + if (s_sl_file_open_infos[i].name != NULL) { + free(s_sl_file_open_infos[i].name); + } + s_sl_file_open_infos[i].name = strdup(name); + return &s_sl_file_open_infos[i]; +} + +void fs_slfs_set_file_size(const char *name, size_t size) { + struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */); + foi->size = size; +} + +void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token) { + struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */); + foi->flags = flags; + foi->token = token; +} + +void fs_slfs_unset_file_flags(const char *name) { + struct sl_file_open_info *foi = fs_slfs_find_foi(name, false /* create */); + if (foi == NULL) return; + free(foi->name); + memset(foi, 0, sizeof(*foi)); +} + +#endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/simplelink/sl_fs.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if MG_NET_IF == MG_NET_IF_SIMPLELINK && \ + (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS)) + +int set_errno(int e) { + errno = e; + return (e == 0 ? 0 : -1); +} + +const char *drop_dir(const char *fname, bool *is_slfs) { + if (is_slfs != NULL) { + *is_slfs = (strncmp(fname, "SL:", 3) == 0); + if (*is_slfs) fname += 3; + } + /* Drop "./", if any */ + if (fname[0] == '.' && fname[1] == '/') { + fname += 2; + } + /* + * Drop / if it is the only one in the path. + * This allows use of /pretend/directories but serves /file.txt as normal. + */ + if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) { + fname++; + } + return fname; +} + +#if !defined(MG_FS_NO_VFS) + +#include +#include +#include +#include +#include +#ifdef __TI_COMPILER_VERSION__ +#include +#endif + +/* Amalgamated: #include "common/cs_dbg.h" */ +/* Amalgamated: #include "common/platform.h" */ + +#ifdef CC3200_FS_SPIFFS +/* Amalgamated: #include "cc3200_fs_spiffs.h" */ +#endif + +#ifdef MG_FS_SLFS +/* Amalgamated: #include "sl_fs_slfs.h" */ +#endif + +#define NUM_SYS_FDS 3 +#define SPIFFS_FD_BASE 10 +#define SLFS_FD_BASE 100 + +#if !defined(MG_UART_CHAR_PUT) && !defined(MG_UART_WRITE) +#if CS_PLATFORM == CS_P_CC3200 +#include +#include +#include +#include +#include +#define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c); +#else +#define MG_UART_WRITE(fd, buf, len) +#endif /* CS_PLATFORM == CS_P_CC3200 */ +#endif /* !MG_UART_CHAR_PUT */ + +enum fd_type { + FD_INVALID, + FD_SYS, +#ifdef CC3200_FS_SPIFFS + FD_SPIFFS, +#endif +#ifdef MG_FS_SLFS + FD_SLFS +#endif +}; +static int fd_type(int fd) { + if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS; +#ifdef CC3200_FS_SPIFFS + if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) { + return FD_SPIFFS; + } +#endif +#ifdef MG_FS_SLFS + if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) { + return FD_SLFS; + } +#endif + return FD_INVALID; +} + +#if MG_TI_NO_HOST_INTERFACE +int open(const char *pathname, unsigned flags, int mode) { +#else +int _open(const char *pathname, int flags, mode_t mode) { +#endif + int fd = -1; + bool is_sl; + const char *fname = drop_dir(pathname, &is_sl); + if (is_sl) { +#ifdef MG_FS_SLFS + fd = fs_slfs_open(fname, flags, mode); + if (fd >= 0) fd += SLFS_FD_BASE; +#endif + } else { +#ifdef CC3200_FS_SPIFFS + fd = fs_spiffs_open(fname, flags, mode); + if (fd >= 0) fd += SPIFFS_FD_BASE; +#endif + } + LOG(LL_DEBUG, + ("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname)); + return fd; +} + +int _stat(const char *pathname, struct stat *st) { + int res = -1; + bool is_sl; + const char *fname = drop_dir(pathname, &is_sl); + memset(st, 0, sizeof(*st)); + /* Simulate statting the root directory. */ + if (fname[0] == '\0' || strcmp(fname, ".") == 0) { + st->st_ino = 0; + st->st_mode = S_IFDIR | 0777; + st->st_nlink = 1; + st->st_size = 0; + return 0; + } + if (is_sl) { +#ifdef MG_FS_SLFS + res = fs_slfs_stat(fname, st); +#endif + } else { +#ifdef CC3200_FS_SPIFFS + res = fs_spiffs_stat(fname, st); +#endif + } + LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname)); + return res; +} + +#if MG_TI_NO_HOST_INTERFACE +int close(int fd) { +#else +int _close(int fd) { +#endif + int r = -1; + switch (fd_type(fd)) { + case FD_INVALID: + r = set_errno(EBADF); + break; + case FD_SYS: + r = set_errno(EACCES); + break; +#ifdef CC3200_FS_SPIFFS + case FD_SPIFFS: + r = fs_spiffs_close(fd - SPIFFS_FD_BASE); + break; +#endif +#ifdef MG_FS_SLFS + case FD_SLFS: + r = fs_slfs_close(fd - SLFS_FD_BASE); + break; +#endif + } + DBG(("close(%d) = %d", fd, r)); + return r; +} + +#if MG_TI_NO_HOST_INTERFACE +off_t lseek(int fd, off_t offset, int whence) { +#else +off_t _lseek(int fd, off_t offset, int whence) { +#endif + int r = -1; + switch (fd_type(fd)) { + case FD_INVALID: + r = set_errno(EBADF); + break; + case FD_SYS: + r = set_errno(ESPIPE); + break; +#ifdef CC3200_FS_SPIFFS + case FD_SPIFFS: + r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence); + break; +#endif +#ifdef MG_FS_SLFS + case FD_SLFS: + r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence); + break; +#endif + } + DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r)); + return r; +} + +int _fstat(int fd, struct stat *s) { + int r = -1; + memset(s, 0, sizeof(*s)); + switch (fd_type(fd)) { + case FD_INVALID: + r = set_errno(EBADF); + break; + case FD_SYS: { + /* Create barely passable stats for STD{IN,OUT,ERR}. */ + memset(s, 0, sizeof(*s)); + s->st_ino = fd; + s->st_mode = S_IFCHR | 0666; + r = 0; + break; + } +#ifdef CC3200_FS_SPIFFS + case FD_SPIFFS: + r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s); + break; +#endif +#ifdef MG_FS_SLFS + case FD_SLFS: + r = fs_slfs_fstat(fd - SLFS_FD_BASE, s); + break; +#endif + } + DBG(("fstat(%d) = %d", fd, r)); + return r; +} + +#if MG_TI_NO_HOST_INTERFACE +int read(int fd, char *buf, unsigned count) { +#else +ssize_t _read(int fd, void *buf, size_t count) { +#endif + int r = -1; + switch (fd_type(fd)) { + case FD_INVALID: + r = set_errno(EBADF); + break; + case FD_SYS: { + if (fd != 0) { + r = set_errno(EACCES); + break; + } + /* Should we allow reading from stdin = uart? */ + r = set_errno(ENOTSUP); + break; + } +#ifdef CC3200_FS_SPIFFS + case FD_SPIFFS: + r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count); + break; +#endif +#ifdef MG_FS_SLFS + case FD_SLFS: + r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count); + break; +#endif + } + DBG(("read(%d, %u) = %d", fd, count, r)); + return r; +} + +#if MG_TI_NO_HOST_INTERFACE +int write(int fd, const char *buf, unsigned count) { +#else +ssize_t _write(int fd, const void *buf, size_t count) { +#endif + int r = -1; + switch (fd_type(fd)) { + case FD_INVALID: + r = set_errno(EBADF); + break; + case FD_SYS: { + if (fd == 0) { + r = set_errno(EACCES); + break; + } +#ifdef MG_UART_WRITE + MG_UART_WRITE(fd, buf, count); +#elif defined(MG_UART_CHAR_PUT) + { + size_t i; + for (i = 0; i < count; i++) { + const char c = ((const char *) buf)[i]; + if (c == '\n') MG_UART_CHAR_PUT(fd, '\r'); + MG_UART_CHAR_PUT(fd, c); + } + } +#endif + r = count; + break; + } +#ifdef CC3200_FS_SPIFFS + case FD_SPIFFS: + r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count); + break; +#endif +#ifdef MG_FS_SLFS + case FD_SLFS: + r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count); + break; +#endif + } + return r; +} + +/* + * On Newlib we override rename directly too, because the default + * implementation using _link and _unlink doesn't work for us. + */ +#if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) +int rename(const char *frompath, const char *topath) { + int r = -1; + bool is_sl_from, is_sl_to; + const char *from = drop_dir(frompath, &is_sl_from); + const char *to = drop_dir(topath, &is_sl_to); + if (is_sl_from || is_sl_to) { + set_errno(ENOTSUP); + } else { +#ifdef CC3200_FS_SPIFFS + r = fs_spiffs_rename(from, to); +#endif + } + DBG(("rename(%s, %s) = %d", from, to, r)); + return r; +} +#endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */ + +#if MG_TI_NO_HOST_INTERFACE +int unlink(const char *pathname) { +#else +int _unlink(const char *pathname) { +#endif + int r = -1; + bool is_sl; + const char *fname = drop_dir(pathname, &is_sl); + if (is_sl) { +#ifdef MG_FS_SLFS + r = fs_slfs_unlink(fname); +#endif + } else { +#ifdef CC3200_FS_SPIFFS + r = fs_spiffs_unlink(fname); +#endif + } + DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname)); + return r; +} + +#ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */ +DIR *opendir(const char *dir_name) { + DIR *r = NULL; + bool is_sl; + drop_dir(dir_name, &is_sl); + if (is_sl) { + r = NULL; + set_errno(ENOTSUP); + } else { + r = fs_spiffs_opendir(dir_name); + } + DBG(("opendir(%s) = %p", dir_name, r)); + return r; +} + +struct dirent *readdir(DIR *dir) { + struct dirent *res = fs_spiffs_readdir(dir); + DBG(("readdir(%p) = %p", dir, res)); + return res; +} + +int closedir(DIR *dir) { + int res = fs_spiffs_closedir(dir); + DBG(("closedir(%p) = %d", dir, res)); + return res; +} + +int rmdir(const char *path) { + return fs_spiffs_rmdir(path); +} + +int mkdir(const char *path, mode_t mode) { + (void) path; + (void) mode; + /* for spiffs supports only root dir, which comes from mongoose as '.' */ + return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR; +} +#endif + +int sl_fs_init(void) { + int ret = 1; +#ifdef __TI_COMPILER_VERSION__ +#ifdef MG_FS_SLFS +#pragma diag_push +#pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \ + */ + ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read, + fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink, + fs_slfs_rename) == 0); +#pragma diag_pop +#endif +#endif + return ret; +} + +#endif /* !defined(MG_FS_NO_VFS) */ +#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \ + defined(MG_FS_SPIFFS)) */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/simplelink/sl_socket.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if MG_NET_IF == MG_NET_IF_SIMPLELINK + +#include +#include + +/* Amalgamated: #include "common/platform.h" */ + +const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) { + int res; + struct in_addr *in = (struct in_addr *) src; + if (af != AF_INET) { + errno = ENOTSUP; + return NULL; + } + res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0), + SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2), + SL_IPV4_BYTE(in->s_addr, 3)); + return res > 0 ? dst : NULL; +} + +char *inet_ntoa(struct in_addr n) { + static char a[16]; + return (char *) inet_ntop(AF_INET, &n, a, sizeof(a)); +} + +int inet_pton(int af, const char *src, void *dst) { + uint32_t a0, a1, a2, a3; + uint8_t *db = (uint8_t *) dst; + if (af != AF_INET) { + errno = ENOTSUP; + return 0; + } + if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) { + return 0; + } + *db = a3; + *(db + 1) = a2; + *(db + 2) = a1; + *(db + 3) = a0; + return 1; +} + +#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/simplelink/sl_mg_task.c" +#endif +#if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) + +/* Amalgamated: #include "mg_task.h" */ + +#include + +enum mg_q_msg_type { + MG_Q_MSG_CB, +}; +struct mg_q_msg { + enum mg_q_msg_type type; + void (*cb)(struct mg_mgr *mgr, void *arg); + void *arg; +}; +static OsiMsgQ_t s_mg_q; +static void mg_task(void *arg); + +bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) { + if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) { + return false; + } + if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size, + (void *) mg_init, priority, NULL) != OSI_OK) { + return false; + } + return true; +} + +static void mg_task(void *arg) { + struct mg_mgr mgr; + mg_init_cb mg_init = (mg_init_cb) arg; + mg_mgr_init(&mgr, NULL); + mg_init(&mgr); + while (1) { + struct mg_q_msg msg; + mg_mgr_poll(&mgr, 1); + if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue; + switch (msg.type) { + case MG_Q_MSG_CB: { + msg.cb(&mgr, msg.arg); + } + } + } +} + +void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) { + struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg}; + osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT); +} + +#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \ + */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/simplelink/sl_net_if.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ +#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ + +/* Amalgamated: #include "mongoose/src/net_if.h" */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef MG_ENABLE_NET_IF_SIMPLELINK +#define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK +#endif + +extern const struct mg_iface_vtable mg_simplelink_iface_vtable; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/simplelink/sl_net_if.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Amalgamated: #include "common/platforms/simplelink/sl_net_if.h" */ + +#if MG_ENABLE_NET_IF_SIMPLELINK + +/* Amalgamated: #include "mongoose/src/internal.h" */ +/* Amalgamated: #include "mongoose/src/util.h" */ + +#define MG_TCP_RECV_BUFFER_SIZE 1024 +#define MG_UDP_RECV_BUFFER_SIZE 1500 + +static sock_t mg_open_listening_socket(struct mg_connection *nc, + union socket_address *sa, int type, + int proto); + +static void mg_set_non_blocking_mode(sock_t sock) { + SlSockNonblocking_t opt; +#if SL_MAJOR_VERSION_NUM < 2 + opt.NonblockingEnabled = 1; +#else + opt.NonBlockingEnabled = 1; +#endif + sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt)); +} + +static int mg_is_error(int n) { + return (n < 0 && n != SL_ERROR_BSD_EALREADY && n != SL_ERROR_BSD_EAGAIN); +} + +static void mg_sl_if_connect_tcp(struct mg_connection *nc, + const union socket_address *sa) { + int proto = 0; +#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK + if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET; +#endif + sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto); + if (sock < 0) { + nc->err = sock; + goto out; + } + mg_sock_set(nc, sock); +#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK + nc->err = sl_set_ssl_opts(sock, nc); + if (nc->err != 0) goto out; +#endif + nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin)); +out: + DBG(("%p to %s:%d sock %d %d err %d", nc, inet_ntoa(sa->sin.sin_addr), + ntohs(sa->sin.sin_port), nc->sock, proto, nc->err)); +} + +static void mg_sl_if_connect_udp(struct mg_connection *nc) { + sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) { + nc->err = sock; + return; + } + mg_sock_set(nc, sock); + nc->err = 0; +} + +static int mg_sl_if_listen_tcp(struct mg_connection *nc, + union socket_address *sa) { + int proto = 0; + if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET; + sock_t sock = mg_open_listening_socket(nc, sa, SOCK_STREAM, proto); + if (sock < 0) return sock; + mg_sock_set(nc, sock); + return 0; +} + +static int mg_sl_if_listen_udp(struct mg_connection *nc, + union socket_address *sa) { + sock_t sock = mg_open_listening_socket(nc, sa, SOCK_DGRAM, 0); + if (sock == INVALID_SOCKET) return (errno ? errno : 1); + mg_sock_set(nc, sock); + return 0; +} + +static int mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf, + size_t len) { + int n = (int) sl_Send(nc->sock, buf, len, 0); + if (n < 0 && !mg_is_error(n)) n = 0; + return n; +} + +static int mg_sl_if_udp_send(struct mg_connection *nc, const void *buf, + size_t len) { + int n = sl_SendTo(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin)); + if (n < 0 && !mg_is_error(n)) n = 0; + return n; +} + +static int mg_sl_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len) { + int n = sl_Recv(nc->sock, buf, len, 0); + if (n == 0) { + /* Orderly shutdown of the socket, try flushing output. */ + nc->flags |= MG_F_SEND_AND_CLOSE; + } else if (n < 0 && !mg_is_error(n)) { + n = 0; + } + return n; +} + +static int mg_sl_if_udp_recv(struct mg_connection *nc, void *buf, size_t len, + union socket_address *sa, size_t *sa_len) { + SlSocklen_t sa_len_t = *sa_len; + int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0, + (SlSockAddr_t *) sa, &sa_len_t); + *sa_len = sa_len_t; + if (n < 0 && !mg_is_error(n)) n = 0; + return n; +} + +static int mg_sl_if_create_conn(struct mg_connection *nc) { + (void) nc; + return 1; +} + +void mg_sl_if_destroy_conn(struct mg_connection *nc) { + if (nc->sock == INVALID_SOCKET) return; + /* For UDP, only close outgoing sockets or listeners. */ + if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) { + sl_Close(nc->sock); + } + nc->sock = INVALID_SOCKET; +} + +static int mg_accept_conn(struct mg_connection *lc) { + struct mg_connection *nc; + union socket_address sa; + socklen_t sa_len = sizeof(sa); + sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len); + if (sock < 0) { + DBG(("%p: failed to accept: %d", lc, sock)); + return 0; + } + nc = mg_if_accept_new_conn(lc); + if (nc == NULL) { + sl_Close(sock); + return 0; + } + DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr), + ntohs(sa.sin.sin_port))); + mg_sock_set(nc, sock); + mg_if_accept_tcp_cb(nc, &sa, sa_len); + return 1; +} + +/* 'sa' must be an initialized address to bind to */ +static sock_t mg_open_listening_socket(struct mg_connection *nc, + union socket_address *sa, int type, + int proto) { + int r; + socklen_t sa_len = + (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6); + sock_t sock = sl_Socket(sa->sa.sa_family, type, proto); + if (sock < 0) return sock; +#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK + if ((r = sl_set_ssl_opts(sock, nc)) < 0) goto clean; +#endif + if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) goto clean; + if (type != SOCK_DGRAM) { + if ((r = sl_Listen(sock, SOMAXCONN)) < 0) goto clean; + } + mg_set_non_blocking_mode(sock); +clean: + if (r < 0) { + sl_Close(sock); + sock = r; + } + return sock; +} + +#define _MG_F_FD_CAN_READ 1 +#define _MG_F_FD_CAN_WRITE 1 << 1 +#define _MG_F_FD_ERROR 1 << 2 + +void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) { + DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, + fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); + + if (!mg_if_poll(nc, now)) return; + + if (nc->flags & MG_F_CONNECTING) { + if ((nc->flags & MG_F_UDP) || nc->err != SL_ERROR_BSD_EALREADY) { + mg_if_connect_cb(nc, nc->err); + } else { + /* In SimpleLink, to get status of non-blocking connect() we need to wait + * until socket is writable and repeat the call to sl_Connect again, + * which will now return the real status. */ + if (fd_flags & _MG_F_FD_CAN_WRITE) { + nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin)); + DBG(("%p conn res=%d", nc, nc->err)); + if (nc->err == SL_ERROR_BSD_ESECSNOVERIFY || + /* TODO(rojer): Provide API to set the date for verification. */ + nc->err == SL_ERROR_BSD_ESECDATEERROR +#if SL_MAJOR_VERSION_NUM >= 2 + /* Per SWRU455, this error does not mean verification failed, + * it only means that the cert used is not present in the trusted + * root CA catalog. Which is perfectly fine. */ + || + nc->err == SL_ERROR_BSD_ESECUNKNOWNROOTCA +#endif + ) { + nc->err = 0; + } + mg_if_connect_cb(nc, nc->err); + } + } + /* Ignore read/write in further processing, we've handled it. */ + fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE); + } + + if (fd_flags & _MG_F_FD_CAN_READ) { + if (nc->flags & MG_F_UDP) { + mg_if_can_recv_cb(nc); + } else { + if (nc->flags & MG_F_LISTENING) { + mg_accept_conn(nc); + } else { + mg_if_can_recv_cb(nc); + } + } + } + + if (fd_flags & _MG_F_FD_CAN_WRITE) { + mg_if_can_send_cb(nc); + } + + DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, nc->flags, + (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); +} + +/* Associate a socket to a connection. */ +void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) { + mg_set_non_blocking_mode(sock); + nc->sock = sock; + DBG(("%p %d", nc, sock)); +} + +void mg_sl_if_init(struct mg_iface *iface) { + (void) iface; + DBG(("%p using sl_Select()", iface->mgr)); +} + +void mg_sl_if_free(struct mg_iface *iface) { + (void) iface; +} + +void mg_sl_if_add_conn(struct mg_connection *nc) { + (void) nc; +} + +void mg_sl_if_remove_conn(struct mg_connection *nc) { + (void) nc; +} + +time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) { + struct mg_mgr *mgr = iface->mgr; + double now = mg_time(); + double min_timer; + struct mg_connection *nc, *tmp; + struct SlTimeval_t tv; + SlFdSet_t read_set, write_set, err_set; + sock_t max_fd = INVALID_SOCKET; + int num_fds, num_ev = 0, num_timers = 0; + + SL_SOCKET_FD_ZERO(&read_set); + SL_SOCKET_FD_ZERO(&write_set); + SL_SOCKET_FD_ZERO(&err_set); + + /* + * Note: it is ok to have connections with sock == INVALID_SOCKET in the list, + * e.g. timer-only "connections". + */ + min_timer = 0; + for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) { + tmp = nc->next; + + if (nc->sock != INVALID_SOCKET) { + num_fds++; + + if (!(nc->flags & MG_F_WANT_WRITE) && + nc->recv_mbuf.len < nc->recv_mbuf_limit && + (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) { + SL_SOCKET_FD_SET(nc->sock, &read_set); + if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock; + } + + if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) || + (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) { + SL_SOCKET_FD_SET(nc->sock, &write_set); + SL_SOCKET_FD_SET(nc->sock, &err_set); + if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock; + } + } + + if (nc->ev_timer_time > 0) { + if (num_timers == 0 || nc->ev_timer_time < min_timer) { + min_timer = nc->ev_timer_time; + } + num_timers++; + } + } + + /* + * If there is a timer to be fired earlier than the requested timeout, + * adjust the timeout. + */ + if (num_timers > 0) { + double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */; + if (timer_timeout_ms < timeout_ms) { + timeout_ms = timer_timeout_ms; + } + } + if (timeout_ms < 0) timeout_ms = 0; + + tv.tv_sec = timeout_ms / 1000; + tv.tv_usec = (timeout_ms % 1000) * 1000; + + if (num_fds > 0) { + num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv); + } + + now = mg_time(); + DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, + num_fds, timeout_ms)); + + for (nc = mgr->active_connections; nc != NULL; nc = tmp) { + int fd_flags = 0; + if (nc->sock != INVALID_SOCKET) { + if (num_ev > 0) { + fd_flags = + (SL_SOCKET_FD_ISSET(nc->sock, &read_set) && + (!(nc->flags & MG_F_UDP) || nc->listener == NULL) + ? _MG_F_FD_CAN_READ + : 0) | + (SL_SOCKET_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE + : 0) | + (SL_SOCKET_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0); + } + /* SimpleLink does not report UDP sockets as writable. */ + if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) { + fd_flags |= _MG_F_FD_CAN_WRITE; + } + } + tmp = nc->next; + mg_mgr_handle_conn(nc, fd_flags, now); + } + + return now; +} + +void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote, + union socket_address *sa) { + /* SimpleLink does not provide a way to get socket's peer address after + * accept or connect. Address should have been preserved in the connection, + * so we do our best here by using it. */ + if (remote) memcpy(sa, &nc->sa, sizeof(*sa)); +} + +void sl_restart_cb(struct mg_mgr *mgr) { + /* + * SimpleLink has been restarted, meaning all sockets have been invalidated. + * We try our best - we'll restart the listeners, but for outgoing + * connections we have no option but to terminate. + */ + struct mg_connection *nc; + for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { + if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */ + if (nc->flags & MG_F_LISTENING) { + DBG(("restarting %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr), + ntohs(nc->sa.sin.sin_port))); + int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa) + : mg_sl_if_listen_tcp(nc, &nc->sa)); + if (res == 0) continue; + /* Well, we tried and failed. Fall through to closing. */ + } + nc->sock = INVALID_SOCKET; + DBG(("terminating %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr), + ntohs(nc->sa.sin.sin_port))); + /* TODO(rojer): Outgoing UDP? */ + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + } +} + +/* clang-format off */ +#define MG_SL_IFACE_VTABLE \ + { \ + mg_sl_if_init, \ + mg_sl_if_free, \ + mg_sl_if_add_conn, \ + mg_sl_if_remove_conn, \ + mg_sl_if_poll, \ + mg_sl_if_listen_tcp, \ + mg_sl_if_listen_udp, \ + mg_sl_if_connect_tcp, \ + mg_sl_if_connect_udp, \ + mg_sl_if_tcp_send, \ + mg_sl_if_udp_send, \ + mg_sl_if_tcp_recv, \ + mg_sl_if_udp_recv, \ + mg_sl_if_create_conn, \ + mg_sl_if_destroy_conn, \ + mg_sl_if_sock_set, \ + mg_sl_if_get_conn_addr, \ + } +/* clang-format on */ + +const struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE; +#if MG_NET_IF == MG_NET_IF_SIMPLELINK +const struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE; +#endif + +#endif /* MG_ENABLE_NET_IF_SIMPLELINK */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/simplelink/sl_ssl_if.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK + +/* Amalgamated: #include "common/mg_mem.h" */ + +#ifndef MG_SSL_IF_SIMPLELINK_SLFS_PREFIX +#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "SL:" +#endif + +#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN \ + (sizeof(MG_SSL_IF_SIMPLELINK_SLFS_PREFIX) - 1) + +struct mg_ssl_if_ctx { + char *ssl_cert; + char *ssl_key; + char *ssl_ca_cert; + char *ssl_server_name; +}; + +void mg_ssl_if_init() { +} + +enum mg_ssl_if_result mg_ssl_if_conn_init( + struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, + const char **err_msg) { + struct mg_ssl_if_ctx *ctx = + (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); + if (ctx == NULL) { + MG_SET_PTRPTR(err_msg, "Out of memory"); + return MG_SSL_ERROR; + } + nc->ssl_if_data = ctx; + + if (params->cert != NULL || params->key != NULL) { + if (params->cert != NULL && params->key != NULL) { + ctx->ssl_cert = strdup(params->cert); + ctx->ssl_key = strdup(params->key); + } else { + MG_SET_PTRPTR(err_msg, "Both cert and key are required."); + return MG_SSL_ERROR; + } + } + if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) { + ctx->ssl_ca_cert = strdup(params->ca_cert); + } + /* TODO(rojer): cipher_suites. */ + if (params->server_name != NULL) { + ctx->ssl_server_name = strdup(params->server_name); + } + return MG_SSL_OK; +} + +enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, + struct mg_connection *lc) { + /* SimpleLink does everything for us, nothing for us to do. */ + (void) nc; + (void) lc; + return MG_SSL_OK; +} + +enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) { + /* SimpleLink has already performed the handshake, nothing to do. */ + return MG_SSL_OK; +} + +int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) { + /* SimpelLink handles TLS, so this is just a pass-through. */ + int n = nc->iface->vtable->tcp_recv(nc, buf, len); + if (n == 0) nc->flags |= MG_F_WANT_READ; + return n; +} + +int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) { + /* SimpelLink handles TLS, so this is just a pass-through. */ + return nc->iface->vtable->tcp_send(nc, buf, len); +} + +void mg_ssl_if_conn_close_notify(struct mg_connection *nc) { + /* Nothing to do */ + (void) nc; +} + +void mg_ssl_if_conn_free(struct mg_connection *nc) { + struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; + if (ctx == NULL) return; + nc->ssl_if_data = NULL; + MG_FREE(ctx->ssl_cert); + MG_FREE(ctx->ssl_key); + MG_FREE(ctx->ssl_ca_cert); + MG_FREE(ctx->ssl_server_name); + memset(ctx, 0, sizeof(*ctx)); + MG_FREE(ctx); +} + +bool pem_to_der(const char *pem_file, const char *der_file) { + bool ret = false; + FILE *pf = NULL, *df = NULL; + bool writing = false; + pf = fopen(pem_file, "r"); + if (pf == NULL) goto clean; + remove(der_file); + fs_slfs_set_file_size(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, 2048); + df = fopen(der_file, "w"); + fs_slfs_unset_file_flags(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN); + if (df == NULL) goto clean; + while (1) { + char pem_buf[70]; + char der_buf[48]; + if (!fgets(pem_buf, sizeof(pem_buf), pf)) break; + if (writing) { + if (strstr(pem_buf, "-----END ") != NULL) { + ret = true; + break; + } + int l = 0; + while (!isspace((unsigned int) pem_buf[l])) l++; + int der_len = 0; + cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf), + der_buf, &der_len); + if (der_len <= 0) break; + if (fwrite(der_buf, 1, der_len, df) != der_len) break; + } else if (strstr(pem_buf, "-----BEGIN ") != NULL) { + writing = true; + } + } + +clean: + if (pf != NULL) fclose(pf); + if (df != NULL) { + fclose(df); + if (!ret) remove(der_file); + } + return ret; +} + +#if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS) +/* If the file's extension is .pem, convert it to DER format and put on SLFS. */ +static char *sl_pem2der(const char *pem_file) { + const char *pem_ext = strstr(pem_file, ".pem"); + if (pem_ext == NULL || *(pem_ext + 4) != '\0') { + return strdup(pem_file); + } + char *der_file = NULL; + /* DER file must be located on SLFS, add prefix. */ + int l = mg_asprintf(&der_file, 0, MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "%.*s.der", + (int) (pem_ext - pem_file), pem_file); + if (der_file == NULL) return NULL; + bool result = false; + cs_stat_t st; + if (mg_stat(der_file, &st) != 0) { + result = pem_to_der(pem_file, der_file); + LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result)); + } else { + /* File exists, assume it's already been converted. */ + result = true; + } + if (result) { + /* Strip the SL: prefix we added since NWP does not expect it. */ + memmove(der_file, der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, + l - 2 /* including \0 */); + } else { + MG_FREE(der_file); + der_file = NULL; + } + return der_file; +} +#else +static char *sl_pem2der(const char *pem_file) { + return strdup(pem_file); +} +#endif + +int sl_set_ssl_opts(int sock, struct mg_connection *nc) { + int err; + const struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; + DBG(("%p ssl ctx: %p", nc, ctx)); + + if (ctx == NULL) return 0; + DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"), + (ctx->ssl_key ? ctx->ssl_cert : "-"), + (ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"), + (ctx->ssl_server_name ? ctx->ssl_server_name : "-"))); + if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) { + char *ssl_cert = sl_pem2der(ctx->ssl_cert), *ssl_key = NULL; + if (ssl_cert != NULL) { + err = sl_SetSockOpt(sock, SL_SOL_SOCKET, + SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert, + strlen(ssl_cert)); + MG_FREE(ssl_cert); + LOG(LL_DEBUG, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err)); + ssl_key = sl_pem2der(ctx->ssl_key); + if (ssl_key != NULL) { + err = sl_SetSockOpt(sock, SL_SOL_SOCKET, + SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key, + strlen(ssl_key)); + MG_FREE(ssl_key); + LOG(LL_DEBUG, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err)); + } else { + err = -1; + } + } else { + err = -1; + } + if (err != 0) return err; + } + if (ctx->ssl_ca_cert != NULL) { + if (ctx->ssl_ca_cert[0] != '\0') { + char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert); + if (ssl_ca_cert != NULL) { + err = + sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME, + ssl_ca_cert, strlen(ssl_ca_cert)); + LOG(LL_DEBUG, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err)); + } else { + err = -1; + } + MG_FREE(ssl_ca_cert); + if (err != 0) return err; + } + } + if (ctx->ssl_server_name != NULL) { + err = sl_SetSockOpt(sock, SL_SOL_SOCKET, + SL_SO_SECURE_DOMAIN_NAME_VERIFICATION, + ctx->ssl_server_name, strlen(ctx->ssl_server_name)); + DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err)); + /* Domain name verificationw as added in a NWP service pack, older + * versions return SL_ERROR_BSD_ENOPROTOOPT. There isn't much we can do + * about it, + * so we ignore the error. */ + if (err != 0 && err != SL_ERROR_BSD_ENOPROTOOPT) return err; + } + return 0; +} + +#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/lwip/mg_lwip_net_if.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ +#define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ + +#ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL +#define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL +#endif + +#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL + +#include + +extern const struct mg_iface_vtable mg_lwip_iface_vtable; + +struct mg_lwip_conn_state { + struct mg_connection *nc; + struct mg_connection *lc; + union { + struct tcp_pcb *tcp; + struct udp_pcb *udp; + } pcb; + err_t err; + size_t num_sent; /* Number of acknowledged bytes to be reported to the core */ + struct pbuf *rx_chain; /* Chain of incoming data segments. */ + size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */ + /* Last SSL write size, for retries. */ + int last_ssl_write_size; + /* Whether MG_SIG_RECV is already pending for this connection */ + int recv_pending; + /* Whether the connection is about to close, just `rx_chain` needs to drain */ + int draining_rx_chain; +}; + +enum mg_sig_type { + MG_SIG_CONNECT_RESULT = 1, + MG_SIG_RECV = 2, + MG_SIG_CLOSE_CONN = 3, + MG_SIG_TOMBSTONE = 4, + MG_SIG_ACCEPT = 5, +}; + +void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc); + +/* To be implemented by the platform. */ +void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr); + +#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */ + +#endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/lwip/mg_lwip_net_if.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL + +/* Amalgamated: #include "common/mg_mem.h" */ + +#include +#include +#include +#include +#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 +#include /* For tcp_seg */ +#else +#include +#endif +#include + +/* Amalgamated: #include "common/cs_dbg.h" */ + +/* + * Newest versions of LWIP have ip_2_ip4, older have ipX_2_ip, + * even older have nothing. + */ +#ifndef ip_2_ip4 +#ifdef ipX_2_ip +#define ip_2_ip4(addr) ipX_2_ip(addr) +#else +#define ip_2_ip4(addr) (addr) +#endif +#endif + +/* + * Depending on whether Mongoose is compiled with ipv6 support, use right + * lwip functions + */ +#if MG_ENABLE_IPV6 +#define TCP_NEW tcp_new_ip6 +#define TCP_BIND tcp_bind_ip6 +#define UDP_BIND udp_bind_ip6 +#define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x)) +#define SET_ADDR(dst, src) \ + memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \ + sizeof((dst)->sin6.sin6_addr.s6_addr)) +#else +#define TCP_NEW tcp_new +#define TCP_BIND tcp_bind +#define UDP_BIND udp_bind +#define IPADDR_NTOA ipaddr_ntoa +#define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = ip_2_ip4(src)->addr +#endif + +#if NO_SYS +#define tcpip_callback(fn, arg) (fn)(arg) +typedef void (*tcpip_callback_fn)(void *arg); +#endif + +void mg_lwip_if_init(struct mg_iface *iface); +void mg_lwip_if_free(struct mg_iface *iface); +void mg_lwip_if_add_conn(struct mg_connection *nc); +void mg_lwip_if_remove_conn(struct mg_connection *nc); +time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms); + +#if defined(RTOS_SDK) || defined(ESP_PLATFORM) +extern void mgos_lock(); +extern void mgos_unlock(); +#else +#define mgos_lock() +#define mgos_unlock() +#endif + +static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p); + +#if LWIP_TCP_KEEPALIVE +void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle, + int interval, int count) { + if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) { + return; + } + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + struct tcp_pcb *tpcb = cs->pcb.tcp; + if (idle > 0 && interval > 0 && count > 0) { + tpcb->keep_idle = idle * 1000; + tpcb->keep_intvl = interval * 1000; + tpcb->keep_cnt = count; + tpcb->so_options |= SOF_KEEPALIVE; + } else { + tpcb->so_options &= ~SOF_KEEPALIVE; + } +} +#elif !defined(MG_NO_LWIP_TCP_KEEPALIVE) +#warning LWIP TCP keepalive is disabled. Please consider enabling it. +#endif /* LWIP_TCP_KEEPALIVE */ + +static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) { + struct mg_connection *nc = (struct mg_connection *) arg; + DBG(("%p connect to %s:%u = %d", nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)), + tpcb->remote_port, err)); + if (nc == NULL) { + tcp_abort(tpcb); + return ERR_ARG; + } + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + cs->err = err; +#if LWIP_TCP_KEEPALIVE + if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6); +#endif + mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); + return ERR_OK; +} + +static void mg_lwip_tcp_error_cb(void *arg, err_t err) { + struct mg_connection *nc = (struct mg_connection *) arg; + DBG(("%p conn error %d", nc, err)); + if (nc == NULL || (nc->flags & MG_F_CLOSE_IMMEDIATELY)) return; + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + cs->pcb.tcp = NULL; /* Has already been deallocated */ + if (nc->flags & MG_F_CONNECTING) { + cs->err = err; + mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); + } else { + mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); + } +} + +static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb, + struct pbuf *p, err_t err) { + struct mg_connection *nc = (struct mg_connection *) arg; + struct mg_lwip_conn_state *cs = + (nc ? (struct mg_lwip_conn_state *) nc->sock : NULL); + DBG(("%p %p %p %p %u %d", nc, cs, tpcb, p, (p != NULL ? p->tot_len : 0), + err)); + if (p == NULL) { + if (nc != NULL && !(nc->flags & MG_F_CLOSE_IMMEDIATELY)) { + if (cs->rx_chain != NULL) { + /* + * rx_chain still contains non-consumed data, don't close the + * connection + */ + cs->draining_rx_chain = 1; + } else { + mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); + } + } else { + /* Tombstoned connection, do nothing. */ + } + return ERR_OK; + } else if (nc == NULL) { + tcp_abort(tpcb); + return ERR_ARG; + } + /* + * If we get a chain of more than one segment at once, we need to bump + * refcount on the subsequent bufs to make them independent. + */ + if (p->next != NULL) { + struct pbuf *q = p->next; + for (; q != NULL; q = q->next) pbuf_ref(q); + } + mgos_lock(); + if (cs->rx_chain == NULL) { + cs->rx_offset = 0; + } else if (pbuf_clen(cs->rx_chain) >= 4) { + /* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX + * will be completely blocked. We already have at least 4 in the chain, + * this one is the last, so we have to make a copy and release this one. */ + struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM); + if (np != NULL) { + pbuf_copy(np, p); + pbuf_free(p); + p = np; + } + } + mg_lwip_recv_common(nc, p); + mgos_unlock(); + (void) err; + return ERR_OK; +} + +static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb, + u16_t num_sent) { + struct mg_connection *nc = (struct mg_connection *) arg; + DBG(("%p %p %u %p %p", nc, tpcb, num_sent, tpcb->unsent, tpcb->unacked)); + if (nc == NULL) return ERR_OK; + if ((nc->flags & MG_F_SEND_AND_CLOSE) && !(nc->flags & MG_F_WANT_WRITE) && + nc->send_mbuf.len == 0 && tpcb->unsent == NULL && tpcb->unacked == NULL) { + mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); + } + if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) { + mg_lwip_mgr_schedule_poll(nc->mgr); + } + (void) num_sent; + return ERR_OK; +} + +struct mg_lwip_if_connect_tcp_ctx { + struct mg_connection *nc; + const union socket_address *sa; +}; + +static void mg_lwip_if_connect_tcp_tcpip(void *arg) { + struct mg_lwip_if_connect_tcp_ctx *ctx = + (struct mg_lwip_if_connect_tcp_ctx *) arg; + struct mg_connection *nc = ctx->nc; + const union socket_address *sa = ctx->sa; + + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + struct tcp_pcb *tpcb = TCP_NEW(); + cs->pcb.tcp = tpcb; + ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; + u16_t port = ntohs(sa->sin.sin_port); + tcp_arg(tpcb, nc); + tcp_err(tpcb, mg_lwip_tcp_error_cb); + tcp_sent(tpcb, mg_lwip_tcp_sent_cb); + tcp_recv(tpcb, mg_lwip_tcp_recv_cb); + cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */); + DBG(("%p tcp_bind = %d", nc, cs->err)); + if (cs->err != ERR_OK) { + mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); + return; + } + cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb); + DBG(("%p tcp_connect %p = %d", nc, tpcb, cs->err)); + if (cs->err != ERR_OK) { + mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); + return; + } +} + +void mg_lwip_if_connect_tcp(struct mg_connection *nc, + const union socket_address *sa) { + struct mg_lwip_if_connect_tcp_ctx ctx = {.nc = nc, .sa = sa}; + tcpip_callback(mg_lwip_if_connect_tcp_tcpip, &ctx); +} + +/* + * Lwip included in the SDKs for nRF5x chips has different type for the + * callback of `udp_recv()` + */ +#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 +static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p, + const ip_addr_t *addr, u16_t port) +#else +static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p, + ip_addr_t *addr, u16_t port) +#endif +{ + struct mg_connection *nc = (struct mg_connection *) arg; + DBG(("%p %s:%u %p %u %u", nc, IPADDR_NTOA(addr), port, p, p->ref, p->len)); + /* Put address in a separate pbuf and tack it onto the packet. */ + struct pbuf *sap = + pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM); + if (sap == NULL) { + pbuf_free(p); + return; + } + union socket_address *sa = (union socket_address *) sap->payload; +#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 + sa->sin.sin_addr.s_addr = ip_2_ip4(addr)->addr; +#else + sa->sin.sin_addr.s_addr = addr->addr; +#endif + sa->sin.sin_port = htons(port); + /* Logic in the recv handler requires that there be exactly one data pbuf. */ + p = pbuf_coalesce(p, PBUF_RAW); + pbuf_chain(sap, p); + mgos_lock(); + mg_lwip_recv_common(nc, sap); + mgos_unlock(); + (void) pcb; +} + +static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) { + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + if (cs->rx_chain == NULL) { + cs->rx_chain = p; + } else { + pbuf_chain(cs->rx_chain, p); + } + if (!cs->recv_pending) { + cs->recv_pending = 1; + mg_lwip_post_signal(MG_SIG_RECV, nc); + } +} + +static int mg_lwip_if_udp_recv(struct mg_connection *nc, void *buf, size_t len, + union socket_address *sa, size_t *sa_len) { + /* + * For UDP, RX chain consists of interleaved address and packet bufs: + * Address pbuf followed by exactly one data pbuf (recv_cb took care of that). + */ + int res = 0; + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + if (nc->sock == INVALID_SOCKET) return -1; + mgos_lock(); + if (cs->rx_chain != NULL) { + struct pbuf *ap = cs->rx_chain; + struct pbuf *dp = ap->next; + cs->rx_chain = pbuf_dechain(dp); + res = MIN(dp->len, len); + pbuf_copy_partial(dp, buf, res, 0); + pbuf_free(dp); + pbuf_copy_partial(ap, sa, MIN(*sa_len, ap->len), 0); + pbuf_free(ap); + } + mgos_unlock(); + return res; +} + +static void mg_lwip_if_connect_udp_tcpip(void *arg) { + struct mg_connection *nc = (struct mg_connection *) arg; + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + struct udp_pcb *upcb = udp_new(); + cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */); + DBG(("%p udp_bind %p = %d", nc, upcb, cs->err)); + if (cs->err == ERR_OK) { + udp_recv(upcb, mg_lwip_udp_recv_cb, nc); + cs->pcb.udp = upcb; + } else { + udp_remove(upcb); + } + mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); +} + +void mg_lwip_if_connect_udp(struct mg_connection *nc) { + tcpip_callback(mg_lwip_if_connect_udp_tcpip, nc); +} + +static void tcp_close_tcpip(void *arg) { + tcp_close((struct tcp_pcb *) arg); +} + +void mg_lwip_handle_accept(struct mg_connection *nc) { + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + if (cs->pcb.tcp == NULL) return; + union socket_address sa; + struct tcp_pcb *tpcb = cs->pcb.tcp; + SET_ADDR(&sa, &tpcb->remote_ip); + sa.sin.sin_port = htons(tpcb->remote_port); + mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin)); +} + +static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) { + struct mg_connection *lc = (struct mg_connection *) arg, *nc; + struct mg_lwip_conn_state *lcs, *cs; + struct tcp_pcb_listen *lpcb; + LOG(LL_DEBUG, + ("%p conn %p from %s:%u", lc, newtpcb, + IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port)); + if (lc == NULL) { + tcp_abort(newtpcb); + return ERR_ABRT; + } + lcs = (struct mg_lwip_conn_state *) lc->sock; + lpcb = (struct tcp_pcb_listen *) lcs->pcb.tcp; +#if TCP_LISTEN_BACKLOG + tcp_accepted(lpcb); +#endif + nc = mg_if_accept_new_conn(lc); + if (nc == NULL) { + tcp_abort(newtpcb); + return ERR_ABRT; + } + cs = (struct mg_lwip_conn_state *) nc->sock; + cs->lc = lc; + cs->pcb.tcp = newtpcb; + /* We need to set up callbacks before returning because data may start + * arriving immediately. */ + tcp_arg(newtpcb, nc); + tcp_err(newtpcb, mg_lwip_tcp_error_cb); + tcp_sent(newtpcb, mg_lwip_tcp_sent_cb); + tcp_recv(newtpcb, mg_lwip_tcp_recv_cb); +#if LWIP_TCP_KEEPALIVE + mg_lwip_set_keepalive_params(nc, 60, 10, 6); +#endif + mg_lwip_post_signal(MG_SIG_ACCEPT, nc); + (void) err; + (void) lpcb; + return ERR_OK; +} + +struct mg_lwip_if_listen_ctx { + struct mg_connection *nc; + union socket_address *sa; + int ret; +}; + +static void mg_lwip_if_listen_tcp_tcpip(void *arg) { + struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg; + struct mg_connection *nc = ctx->nc; + union socket_address *sa = ctx->sa; + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + struct tcp_pcb *tpcb = TCP_NEW(); + ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; + u16_t port = ntohs(sa->sin.sin_port); + cs->err = TCP_BIND(tpcb, ip, port); + DBG(("%p tcp_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err)); + if (cs->err != ERR_OK) { + tcp_close(tpcb); + ctx->ret = -1; + return; + } + tcp_arg(tpcb, nc); + tpcb = tcp_listen(tpcb); + cs->pcb.tcp = tpcb; + tcp_accept(tpcb, mg_lwip_accept_cb); + ctx->ret = 0; +} + +int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { + struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa}; + tcpip_callback(mg_lwip_if_listen_tcp_tcpip, &ctx); + return ctx.ret; +} + +static void mg_lwip_if_listen_udp_tcpip(void *arg) { + struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg; + struct mg_connection *nc = ctx->nc; + union socket_address *sa = ctx->sa; + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + struct udp_pcb *upcb = udp_new(); + ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; + u16_t port = ntohs(sa->sin.sin_port); + cs->err = UDP_BIND(upcb, ip, port); + DBG(("%p udb_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err)); + if (cs->err != ERR_OK) { + udp_remove(upcb); + ctx->ret = -1; + } else { + udp_recv(upcb, mg_lwip_udp_recv_cb, nc); + cs->pcb.udp = upcb; + ctx->ret = 0; + } +} + +int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { + struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa}; + tcpip_callback(mg_lwip_if_listen_udp_tcpip, &ctx); + return ctx.ret; +} + +struct mg_lwip_tcp_write_ctx { + struct mg_connection *nc; + const void *data; + uint16_t len; + int ret; +}; + +static void tcp_output_tcpip(void *arg) { + tcp_output((struct tcp_pcb *) arg); +} + +static void mg_lwip_tcp_write_tcpip(void *arg) { + struct mg_lwip_tcp_write_ctx *ctx = (struct mg_lwip_tcp_write_ctx *) arg; + struct mg_connection *nc = ctx->nc; + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + struct tcp_pcb *tpcb = cs->pcb.tcp; + size_t len = MIN(tpcb->mss, MIN(ctx->len, tpcb->snd_buf)); + size_t unsent, unacked; + if (len == 0) { + DBG(("%p no buf avail %u %u %p %p", tpcb, tpcb->snd_buf, tpcb->snd_queuelen, + tpcb->unsent, tpcb->unacked)); + tcpip_callback(tcp_output_tcpip, tpcb); + ctx->ret = 0; + return; + } + unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0); + unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0); +/* + * On ESP8266 we only allow one TCP segment in flight at any given time. + * This may increase latency and reduce efficiency of tcp windowing, + * but memory is scarce and precious on that platform so we do this to + * reduce footprint. + */ +#if CS_PLATFORM == CS_P_ESP8266 + if (unacked > 0) { + ctx->ret = 0; + return; + } + len = MIN(len, (TCP_MSS - unsent)); +#endif + cs->err = tcp_write(tpcb, ctx->data, len, TCP_WRITE_FLAG_COPY); + unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0); + unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0); + DBG(("%p tcp_write %u = %d, %u %u", tpcb, len, cs->err, unsent, unacked)); + if (cs->err != ERR_OK) { + /* + * We ignore ERR_MEM because memory will be freed up when the data is sent + * and we'll retry. + */ + ctx->ret = (cs->err == ERR_MEM ? 0 : -1); + return; + } + ctx->ret = len; + (void) unsent; + (void) unacked; +} + +int mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) { + struct mg_lwip_tcp_write_ctx ctx = {.nc = nc, .data = buf, .len = len}; + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + if (nc->sock == INVALID_SOCKET) return -1; + struct tcp_pcb *tpcb = cs->pcb.tcp; + if (tpcb == NULL) return -1; + if (tpcb->snd_buf <= 0) return 0; + tcpip_callback(mg_lwip_tcp_write_tcpip, &ctx); + return ctx.ret; +} + +struct udp_sendto_ctx { + struct udp_pcb *upcb; + struct pbuf *p; + ip_addr_t *ip; + uint16_t port; + int ret; +}; + +static void udp_sendto_tcpip(void *arg) { + struct udp_sendto_ctx *ctx = (struct udp_sendto_ctx *) arg; + ctx->ret = udp_sendto(ctx->upcb, ctx->p, ctx->ip, ctx->port); +} + +static int mg_lwip_if_udp_send(struct mg_connection *nc, const void *data, + size_t len) { + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + if (nc->sock == INVALID_SOCKET || cs->pcb.udp == NULL) return -1; + struct udp_pcb *upcb = cs->pcb.udp; + struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM); +#if defined(LWIP_IPV4) && LWIP_IPV4 && defined(LWIP_IPV6) && LWIP_IPV6 + ip_addr_t ip = {.u_addr.ip4.addr = nc->sa.sin.sin_addr.s_addr, .type = 0}; +#else + ip_addr_t ip = {.addr = nc->sa.sin.sin_addr.s_addr}; +#endif + u16_t port = ntohs(nc->sa.sin.sin_port); + if (p == NULL) return 0; + memcpy(p->payload, data, len); + struct udp_sendto_ctx ctx = {.upcb = upcb, .p = p, .ip = &ip, .port = port}; + tcpip_callback(udp_sendto_tcpip, &ctx); + cs->err = ctx.ret; + pbuf_free(p); + return (cs->err == ERR_OK ? (int) len : -2); +} + +static int mg_lwip_if_can_send(struct mg_connection *nc, + struct mg_lwip_conn_state *cs) { + int can_send = 0; + if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) { + /* We have stuff to send, but can we? */ + if (nc->flags & MG_F_UDP) { + /* UDP is always ready for sending. */ + can_send = (cs->pcb.udp != NULL); + } else { + can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0); +/* See comment above. */ +#if CS_PLATFORM == CS_P_ESP8266 + if (cs->pcb.tcp->unacked != NULL) can_send = 0; +#endif + } + } + return can_send; +} + +struct tcp_recved_ctx { + struct tcp_pcb *tpcb; + size_t len; +}; + +void tcp_recved_tcpip(void *arg) { + struct tcp_recved_ctx *ctx = (struct tcp_recved_ctx *) arg; + if (ctx->tpcb != NULL) tcp_recved(ctx->tpcb, ctx->len); +} + +static int mg_lwip_if_tcp_recv(struct mg_connection *nc, void *buf, + size_t len) { + int res = 0; + char *bufp = buf; + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + if (nc->sock == INVALID_SOCKET) return -1; + mgos_lock(); + while (cs->rx_chain != NULL && len > 0) { + struct pbuf *seg = cs->rx_chain; + size_t seg_len = (seg->len - cs->rx_offset); + size_t copy_len = MIN(len, seg_len); + + pbuf_copy_partial(seg, bufp, copy_len, cs->rx_offset); + len -= copy_len; + res += copy_len; + bufp += copy_len; + cs->rx_offset += copy_len; + if (cs->rx_offset == cs->rx_chain->len) { + cs->rx_chain = pbuf_dechain(cs->rx_chain); + pbuf_free(seg); + cs->rx_offset = 0; + } + } + mgos_unlock(); + if (res > 0) { + struct tcp_recved_ctx ctx = {.tpcb = cs->pcb.tcp, .len = res}; + tcpip_callback(tcp_recved_tcpip, &ctx); + } + return res; +} + +int mg_lwip_if_create_conn(struct mg_connection *nc) { + struct mg_lwip_conn_state *cs = + (struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs)); + if (cs == NULL) return 0; + cs->nc = nc; + nc->sock = (intptr_t) cs; + return 1; +} + +static void udp_remove_tcpip(void *arg) { + udp_remove((struct udp_pcb *) arg); +} + +void mg_lwip_if_destroy_conn(struct mg_connection *nc) { + if (nc->sock == INVALID_SOCKET) return; + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + if (!(nc->flags & MG_F_UDP)) { + struct tcp_pcb *tpcb = cs->pcb.tcp; + if (tpcb != NULL) { + tcp_arg(tpcb, NULL); + DBG(("%p tcp_close %p", nc, tpcb)); + tcp_arg(tpcb, NULL); + tcpip_callback(tcp_close_tcpip, tpcb); + } + while (cs->rx_chain != NULL) { + struct pbuf *seg = cs->rx_chain; + cs->rx_chain = pbuf_dechain(cs->rx_chain); + pbuf_free(seg); + } + memset(cs, 0, sizeof(*cs)); + MG_FREE(cs); + } else if (nc->listener == NULL) { + /* Only close outgoing UDP pcb or listeners. */ + struct udp_pcb *upcb = cs->pcb.udp; + if (upcb != NULL) { + DBG(("%p udp_remove %p", nc, upcb)); + tcpip_callback(udp_remove_tcpip, upcb); + } + memset(cs, 0, sizeof(*cs)); + MG_FREE(cs); + } + nc->sock = INVALID_SOCKET; +} + +void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote, + union socket_address *sa) { + memset(sa, 0, sizeof(*sa)); + if (nc == NULL || nc->sock == INVALID_SOCKET) return; + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + if (nc->flags & MG_F_UDP) { + struct udp_pcb *upcb = cs->pcb.udp; + if (remote) { + memcpy(sa, &nc->sa, sizeof(*sa)); + } else if (upcb != NULL) { + sa->sin.sin_port = htons(upcb->local_port); + SET_ADDR(sa, &upcb->local_ip); + } + } else { + struct tcp_pcb *tpcb = cs->pcb.tcp; + if (remote) { + memcpy(sa, &nc->sa, sizeof(*sa)); + } else if (tpcb != NULL) { + sa->sin.sin_port = htons(tpcb->local_port); + SET_ADDR(sa, &tpcb->local_ip); + } + } +} + +void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) { + nc->sock = sock; +} + +/* clang-format off */ +#define MG_LWIP_IFACE_VTABLE \ + { \ + mg_lwip_if_init, \ + mg_lwip_if_free, \ + mg_lwip_if_add_conn, \ + mg_lwip_if_remove_conn, \ + mg_lwip_if_poll, \ + mg_lwip_if_listen_tcp, \ + mg_lwip_if_listen_udp, \ + mg_lwip_if_connect_tcp, \ + mg_lwip_if_connect_udp, \ + mg_lwip_if_tcp_send, \ + mg_lwip_if_udp_send, \ + mg_lwip_if_tcp_recv, \ + mg_lwip_if_udp_recv, \ + mg_lwip_if_create_conn, \ + mg_lwip_if_destroy_conn, \ + mg_lwip_if_sock_set, \ + mg_lwip_if_get_conn_addr, \ + } +/* clang-format on */ + +const struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE; +#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL +const struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE; +#endif + +#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/lwip/mg_lwip_ev_mgr.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL + +#ifndef MG_SIG_QUEUE_LEN +#define MG_SIG_QUEUE_LEN 32 +#endif + +struct mg_ev_mgr_lwip_signal { + int sig; + struct mg_connection *nc; +}; + +struct mg_ev_mgr_lwip_data { + struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN]; + int sig_queue_len; + int start_index; +}; + +void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) { + struct mg_ev_mgr_lwip_data *md = + (struct mg_ev_mgr_lwip_data *) nc->iface->data; + mgos_lock(); + if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) { + mgos_unlock(); + return; + } + int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN; + md->sig_queue[end_index].sig = sig; + md->sig_queue[end_index].nc = nc; + md->sig_queue_len++; + mg_lwip_mgr_schedule_poll(nc->mgr); + mgos_unlock(); +} + +void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) { + struct mg_ev_mgr_lwip_data *md = + (struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data; + while (md->sig_queue_len > 0) { + mgos_lock(); + int i = md->start_index; + int sig = md->sig_queue[i].sig; + struct mg_connection *nc = md->sig_queue[i].nc; + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + md->start_index = (i + 1) % MG_SIG_QUEUE_LEN; + md->sig_queue_len--; + mgos_unlock(); + if (nc->iface == NULL || nc->mgr == NULL) continue; + switch (sig) { + case MG_SIG_CONNECT_RESULT: { + mg_if_connect_cb(nc, cs->err); + break; + } + case MG_SIG_CLOSE_CONN: { + mg_close_conn(nc); + break; + } + case MG_SIG_RECV: { + cs->recv_pending = 0; + mg_if_can_recv_cb(nc); + mbuf_trim(&nc->recv_mbuf); + break; + } + case MG_SIG_TOMBSTONE: { + break; + } + case MG_SIG_ACCEPT: { + mg_lwip_handle_accept(nc); + break; + } + } + } +} + +void mg_lwip_if_init(struct mg_iface *iface) { + LOG(LL_INFO, ("Mongoose %s, LwIP %u.%u.%u", MG_VERSION, LWIP_VERSION_MAJOR, + LWIP_VERSION_MINOR, LWIP_VERSION_REVISION)); + iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data)); +} + +void mg_lwip_if_free(struct mg_iface *iface) { + MG_FREE(iface->data); + iface->data = NULL; +} + +void mg_lwip_if_add_conn(struct mg_connection *nc) { + (void) nc; +} + +void mg_lwip_if_remove_conn(struct mg_connection *nc) { + struct mg_ev_mgr_lwip_data *md = + (struct mg_ev_mgr_lwip_data *) nc->iface->data; + /* Walk the queue and null-out further signals for this conn. */ + for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) { + if (md->sig_queue[i].nc == nc) { + md->sig_queue[i].sig = MG_SIG_TOMBSTONE; + } + } +} + +time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) { + struct mg_mgr *mgr = iface->mgr; + int n = 0; + double now = mg_time(); + struct mg_connection *nc, *tmp; + double min_timer = 0; + int num_timers = 0; +#if 0 + DBG(("begin poll @%u", (unsigned int) (now * 1000))); +#endif + mg_ev_mgr_lwip_process_signals(mgr); + for (nc = mgr->active_connections; nc != NULL; nc = tmp) { + struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; + tmp = nc->next; + n++; + if (!mg_if_poll(nc, now)) continue; + if (nc->sock != INVALID_SOCKET && + !(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL && + cs->pcb.tcp->unsent != NULL) { + tcpip_callback(tcp_output_tcpip, cs->pcb.tcp); + } + if (nc->ev_timer_time > 0) { + if (num_timers == 0 || nc->ev_timer_time < min_timer) { + min_timer = nc->ev_timer_time; + } + num_timers++; + } + + if (nc->sock != INVALID_SOCKET) { + if (mg_lwip_if_can_send(nc, cs)) { + mg_if_can_send_cb(nc); + mbuf_trim(&nc->send_mbuf); + } + if (cs->rx_chain != NULL) { + mg_if_can_recv_cb(nc); + } else if (cs->draining_rx_chain) { + /* + * If the connection is about to close, and rx_chain is finally empty, + * send the MG_SIG_CLOSE_CONN signal + */ + mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); + } + } + } +#if 0 + DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms", + (unsigned int) (now * 1000), n, num_timers, + (unsigned int) (min_timer * 1000), timeout_ms)); +#endif + (void) timeout_ms; + return now; +} + +#endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/wince/wince_libc.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef WINCE + +const char *strerror(int err) { + /* + * TODO(alashkin): there is no strerror on WinCE; + * look for similar wce_xxxx function + */ + static char buf[10]; + snprintf(buf, sizeof(buf), "%d", err); + return buf; +} + +int open(const char *filename, int oflag, int pmode) { + /* + * TODO(alashkin): mg_open function is not used in mongoose + * but exists in documentation as utility function + * Shall we delete it at all or implement for WinCE as well? + */ + DebugBreak(); + return 0; /* for compiler */ +} + +int _wstati64(const wchar_t *path, cs_stat_t *st) { + DWORD fa = GetFileAttributesW(path); + if (fa == INVALID_FILE_ATTRIBUTES) { + return -1; + } + memset(st, 0, sizeof(*st)); + if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) { + HANDLE h; + FILETIME ftime; + st->st_mode |= _S_IFREG; + h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, NULL); + if (h == INVALID_HANDLE_VALUE) { + return -1; + } + st->st_size = GetFileSize(h, NULL); + GetFileTime(h, NULL, NULL, &ftime); + st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime + + ((uint64_t) ftime.dwHighDateTime << 32)) / + 10000000.0) - + 11644473600); + CloseHandle(h); + } else { + st->st_mode |= _S_IFDIR; + } + return 0; +} + +/* Windows CE doesn't have neither gmtime nor strftime */ +static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) { + FILETIME ft; + SYSTEMTIME systime; + if (t != NULL) { + uint64_t filetime = (*t + 11644473600) * 10000000; + ft.dwLowDateTime = filetime & 0xFFFFFFFF; + ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32; + FileTimeToSystemTime(&ft, &systime); + } else { + GetSystemTime(&systime); + } + /* There is no PRIu16 in WinCE SDK */ + snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear, + (int) systime.wMonth, (int) systime.wDay, (int) systime.wHour, + (int) systime.wMinute, (int) systime.wSecond); +} + +#endif +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/pic32/pic32_net_if.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ +#define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ + +/* Amalgamated: #include "mongoose/src/net_if.h" */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef MG_ENABLE_NET_IF_PIC32 +#define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32 +#endif + +extern const struct mg_iface_vtable mg_pic32_iface_vtable; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/pic32/pic32_net_if.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if MG_ENABLE_NET_IF_PIC32 + +int mg_pic32_if_create_conn(struct mg_connection *nc) { + (void) nc; + return 1; +} + +void mg_pic32_if_recved(struct mg_connection *nc, size_t len) { + (void) nc; + (void) len; +} + +void mg_pic32_if_add_conn(struct mg_connection *nc) { + (void) nc; +} + +void mg_pic32_if_init(struct mg_iface *iface) { + (void) iface; + (void) mg_get_errno(); /* Shutup compiler */ +} + +void mg_pic32_if_free(struct mg_iface *iface) { + (void) iface; +} + +void mg_pic32_if_remove_conn(struct mg_connection *nc) { + (void) nc; +} + +void mg_pic32_if_destroy_conn(struct mg_connection *nc) { + if (nc->sock == INVALID_SOCKET) return; + /* For UDP, only close outgoing sockets or listeners. */ + if (!(nc->flags & MG_F_UDP)) { + /* Close TCP */ + TCPIP_TCP_Close((TCP_SOCKET) nc->sock); + } else if (nc->listener == NULL) { + /* Only close outgoing UDP or listeners. */ + TCPIP_UDP_Close((UDP_SOCKET) nc->sock); + } + + nc->sock = INVALID_SOCKET; +} + +int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { + nc->sock = TCPIP_UDP_ServerOpen( + sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 + : IP_ADDRESS_TYPE_IPV6, + ntohs(sa->sin.sin_port), + sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin); + if (nc->sock == INVALID_SOCKET) { + return -1; + } + return 0; +} + +void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf, + size_t len) { + mbuf_append(&nc->send_mbuf, buf, len); +} + +void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf, + size_t len) { + mbuf_append(&nc->send_mbuf, buf, len); +} + +int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { + nc->sock = TCPIP_TCP_ServerOpen( + sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 + : IP_ADDRESS_TYPE_IPV6, + ntohs(sa->sin.sin_port), + sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin); + memcpy(&nc->sa, sa, sizeof(*sa)); + if (nc->sock == INVALID_SOCKET) { + return -1; + } + return 0; +} + +static int mg_accept_conn(struct mg_connection *lc) { + struct mg_connection *nc; + TCP_SOCKET_INFO si; + union socket_address sa; + + nc = mg_if_accept_new_conn(lc); + + if (nc == NULL) { + return 0; + } + + nc->sock = lc->sock; + nc->flags &= ~MG_F_LISTENING; + + if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) { + return 0; + } + + if (si.addressType == IP_ADDRESS_TYPE_IPV4) { + sa.sin.sin_family = AF_INET; + sa.sin.sin_port = htons(si.remotePort); + sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val; + } else { + /* TODO(alashkin): do something with _potential_ IPv6 */ + memset(&sa, 0, sizeof(sa)); + } + + mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa)); + + return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0; +} + +char *inet_ntoa(struct in_addr in) { + static char addr[17]; + snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1, + (int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3, + (int) in.S_un.S_un_b.s_b4); + return addr; +} + +static void mg_handle_send(struct mg_connection *nc) { + uint16_t bytes_written = 0; + if (nc->flags & MG_F_UDP) { + if (!TCPIP_UDP_RemoteBind( + (UDP_SOCKET) nc->sock, + nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 + : IP_ADDRESS_TYPE_IPV6, + ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + return; + } + bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0); + if (bytes_written >= nc->send_mbuf.len) { + if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock, + (uint8_t *) nc->send_mbuf.buf, + nc->send_mbuf.len) != nc->send_mbuf.len) { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + bytes_written = 0; + } + } + } else { + bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock); + if (bytes_written != 0) { + if (bytes_written > nc->send_mbuf.len) { + bytes_written = nc->send_mbuf.len; + } + if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock, + (uint8_t *) nc->send_mbuf.buf, + bytes_written) != bytes_written) { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + bytes_written = 0; + } + } + } + + mg_if_sent_cb(nc, bytes_written); +} + +static void mg_handle_recv(struct mg_connection *nc) { + uint16_t bytes_read = 0; + uint8_t *buf = NULL; + if (nc->flags & MG_F_UDP) { + bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock); + if (bytes_read != 0 && + (nc->recv_mbuf_limit == -1 || + nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) { + buf = (uint8_t *) MG_MALLOC(bytes_read); + if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) != + bytes_read) { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + bytes_read = 0; + MG_FREE(buf); + } + } + } else { + bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock); + if (bytes_read != 0) { + if (nc->recv_mbuf_limit != -1 && + nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) { + bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len; + } + buf = (uint8_t *) MG_MALLOC(bytes_read); + if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) != + bytes_read) { + nc->flags |= MG_F_CLOSE_IMMEDIATELY; + MG_FREE(buf); + bytes_read = 0; + } + } + } + + if (bytes_read != 0) { + mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */); + } +} + +time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) { + struct mg_mgr *mgr = iface->mgr; + double now = mg_time(); + struct mg_connection *nc, *tmp; + + for (nc = mgr->active_connections; nc != NULL; nc = tmp) { + tmp = nc->next; + + if (nc->flags & MG_F_CONNECTING) { + /* processing connections */ + if (nc->flags & MG_F_UDP || + TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) { + mg_if_connect_cb(nc, 0); + } + } else if (nc->flags & MG_F_LISTENING) { + if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) { + /* accept new connections */ + mg_accept_conn(nc); + } + } else { + if (nc->send_mbuf.len != 0) { + mg_handle_send(nc); + } + + if (nc->recv_mbuf_limit == -1 || + nc->recv_mbuf.len < nc->recv_mbuf_limit) { + mg_handle_recv(nc); + } + } + } + + for (nc = mgr->active_connections; nc != NULL; nc = tmp) { + tmp = nc->next; + if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) || + (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) { + mg_close_conn(nc); + } + } + + return now; +} + +void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) { + nc->sock = sock; +} + +void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote, + union socket_address *sa) { + /* TODO(alaskin): not implemented yet */ +} + +void mg_pic32_if_connect_tcp(struct mg_connection *nc, + const union socket_address *sa) { + nc->sock = TCPIP_TCP_ClientOpen( + sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 + : IP_ADDRESS_TYPE_IPV6, + ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin); + nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0; +} + +void mg_pic32_if_connect_udp(struct mg_connection *nc) { + nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL); + nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0; +} + +/* clang-format off */ +#define MG_PIC32_IFACE_VTABLE \ + { \ + mg_pic32_if_init, \ + mg_pic32_if_free, \ + mg_pic32_if_add_conn, \ + mg_pic32_if_remove_conn, \ + mg_pic32_if_poll, \ + mg_pic32_if_listen_tcp, \ + mg_pic32_if_listen_udp, \ + mg_pic32_if_connect_tcp, \ + mg_pic32_if_connect_udp, \ + mg_pic32_if_tcp_send, \ + mg_pic32_if_udp_send, \ + mg_pic32_if_recved, \ + mg_pic32_if_create_conn, \ + mg_pic32_if_destroy_conn, \ + mg_pic32_if_sock_set, \ + mg_pic32_if_get_conn_addr, \ + } +/* clang-format on */ + +const struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE; +#if MG_NET_IF == MG_NET_IF_PIC32 +const struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE; +#endif + +#endif /* MG_ENABLE_NET_IF_PIC32 */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/windows/windows_direct.c" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef _WIN32 + +int rmdir(const char *dirname) { + return _rmdir(dirname); +} + +unsigned int sleep(unsigned int seconds) { + Sleep(seconds * 1000); + return 0; +} + +#endif /* _WIN32 */ diff --git a/util/mongoose.h b/util/mongoose.h new file mode 100644 index 0000000..0f85b18 --- /dev/null +++ b/util/mongoose.h @@ -0,0 +1,6683 @@ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_common.h" +#endif +/* + * Copyright (c) 2004-2013 Sergey Lyubka + * Copyright (c) 2013-2015 Cesanta Software Limited + * All rights reserved + * + * This software is dual-licensed: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. For the terms of this + * license, see . + * + * You are free to use this software under the terms of the GNU General + * Public License, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * Alternatively, you can license this software under a commercial + * license, as set out in . + */ + +#ifndef CS_MONGOOSE_SRC_COMMON_H_ +#define CS_MONGOOSE_SRC_COMMON_H_ + +#define MG_VERSION "6.14" + +/* Local tweaks, applied before any of Mongoose's own headers. */ +#ifdef MG_LOCALS +#include +#endif + +#endif /* CS_MONGOOSE_SRC_COMMON_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platform.h" +#endif +#ifndef CS_COMMON_PLATFORM_H_ +#define CS_COMMON_PLATFORM_H_ + +/* + * For the "custom" platform, includes and dependencies can be + * provided through mg_locals.h. + */ +#define CS_P_CUSTOM 0 +#define CS_P_UNIX 1 +#define CS_P_WINDOWS 2 +#define CS_P_ESP32 15 +#define CS_P_ESP8266 3 +#define CS_P_CC3100 6 +#define CS_P_CC3200 4 +#define CS_P_CC3220 17 +#define CS_P_MSP432 5 +#define CS_P_TM4C129 14 +#define CS_P_MBED 7 +#define CS_P_WINCE 8 +#define CS_P_NXP_LPC 13 +#define CS_P_NXP_KINETIS 9 +#define CS_P_NRF51 12 +#define CS_P_NRF52 10 +#define CS_P_PIC32 11 +#define CS_P_STM32 16 +/* Next id: 18 */ + +/* If not specified explicitly, we guess platform by defines. */ +#ifndef CS_PLATFORM + +#if defined(TARGET_IS_MSP432P4XX) || defined(__MSP432P401R__) +#define CS_PLATFORM CS_P_MSP432 +#elif defined(cc3200) || defined(TARGET_IS_CC3200) +#define CS_PLATFORM CS_P_CC3200 +#elif defined(cc3220) || defined(TARGET_IS_CC3220) +#define CS_PLATFORM CS_P_CC3220 +#elif defined(__unix__) || defined(__APPLE__) +#define CS_PLATFORM CS_P_UNIX +#elif defined(WINCE) +#define CS_PLATFORM CS_P_WINCE +#elif defined(_WIN32) +#define CS_PLATFORM CS_P_WINDOWS +#elif defined(__MBED__) +#define CS_PLATFORM CS_P_MBED +#elif defined(__USE_LPCOPEN) +#define CS_PLATFORM CS_P_NXP_LPC +#elif defined(FRDM_K64F) || defined(FREEDOM) +#define CS_PLATFORM CS_P_NXP_KINETIS +#elif defined(PIC32) +#define CS_PLATFORM CS_P_PIC32 +#elif defined(ESP_PLATFORM) +#define CS_PLATFORM CS_P_ESP32 +#elif defined(ICACHE_FLASH) +#define CS_PLATFORM CS_P_ESP8266 +#elif defined(TARGET_IS_TM4C129_RA0) || defined(TARGET_IS_TM4C129_RA1) || \ + defined(TARGET_IS_TM4C129_RA2) +#define CS_PLATFORM CS_P_TM4C129 +#elif defined(STM32) +#define CS_PLATFORM CS_P_STM32 +#endif + +#ifndef CS_PLATFORM +#error "CS_PLATFORM is not specified and we couldn't guess it." +#endif + +#endif /* !defined(CS_PLATFORM) */ + +#define MG_NET_IF_SOCKET 1 +#define MG_NET_IF_SIMPLELINK 2 +#define MG_NET_IF_LWIP_LOW_LEVEL 3 +#define MG_NET_IF_PIC32 4 +#define MG_NET_IF_NULL 5 + +#define MG_SSL_IF_OPENSSL 1 +#define MG_SSL_IF_MBEDTLS 2 +#define MG_SSL_IF_SIMPLELINK 3 + +/* Amalgamated: #include "common/platforms/platform_unix.h" */ +/* Amalgamated: #include "common/platforms/platform_windows.h" */ +/* Amalgamated: #include "common/platforms/platform_esp32.h" */ +/* Amalgamated: #include "common/platforms/platform_esp8266.h" */ +/* Amalgamated: #include "common/platforms/platform_cc3100.h" */ +/* Amalgamated: #include "common/platforms/platform_cc3200.h" */ +/* Amalgamated: #include "common/platforms/platform_cc3220.h" */ +/* Amalgamated: #include "common/platforms/platform_mbed.h" */ +/* Amalgamated: #include "common/platforms/platform_nrf51.h" */ +/* Amalgamated: #include "common/platforms/platform_nrf52.h" */ +/* Amalgamated: #include "common/platforms/platform_wince.h" */ +/* Amalgamated: #include "common/platforms/platform_nxp_lpc.h" */ +/* Amalgamated: #include "common/platforms/platform_nxp_kinetis.h" */ +/* Amalgamated: #include "common/platforms/platform_pic32.h" */ +/* Amalgamated: #include "common/platforms/platform_stm32.h" */ + +/* Common stuff */ + +#if !defined(PRINTF_LIKE) +#if defined(__GNUC__) || defined(__clang__) || defined(__TI_COMPILER_VERSION__) +#define PRINTF_LIKE(f, a) __attribute__((format(printf, f, a))) +#else +#define PRINTF_LIKE(f, a) +#endif +#endif + +#if !defined(WEAK) +#if (defined(__GNUC__) || defined(__clang__) || \ + defined(__TI_COMPILER_VERSION__)) && \ + !defined(_WIN32) +#define WEAK __attribute__((weak)) +#else +#define WEAK +#endif +#endif + +#ifdef __GNUC__ +#define NORETURN __attribute__((noreturn)) +#define NOINLINE __attribute__((noinline)) +#define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) +#define NOINSTR __attribute__((no_instrument_function)) +#define DO_NOT_WARN_UNUSED __attribute__((unused)) +#else +#define NORETURN +#define NOINLINE +#define WARN_UNUSED_RESULT +#define NOINSTR +#define DO_NOT_WARN_UNUSED +#endif /* __GNUC__ */ + +#ifndef ARRAY_SIZE +#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0])) +#endif + +#endif /* CS_COMMON_PLATFORM_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_windows.h" +#endif +#ifndef CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_ +#if CS_PLATFORM == CS_P_WINDOWS + +/* + * MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) + * MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013) + * MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012) + * MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010) + * MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008) + * MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005) + * MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio 2003) + * MSVC++ 7.0 _MSC_VER == 1300 + * MSVC++ 6.0 _MSC_VER == 1200 + * MSVC++ 5.0 _MSC_VER == 1100 + */ +#ifdef _MSC_VER +#pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */ +#pragma warning(disable : 4204) /* missing c99 support */ +#endif + +#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS +#define _WINSOCK_DEPRECATED_NO_WARNINGS 1 +#endif + +#ifndef _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +#pragma comment(lib, "ws2_32.lib") /* Linking with winsock library */ +#endif + +#include +#include +#include +#include + +#if _MSC_VER < 1700 +typedef int bool; +#else +#include +#endif + +#if defined(_MSC_VER) && _MSC_VER >= 1800 +#define strdup _strdup +#endif + +#ifndef EINPROGRESS +#define EINPROGRESS WSAEINPROGRESS +#endif +#ifndef EWOULDBLOCK +#define EWOULDBLOCK WSAEWOULDBLOCK +#endif +#ifndef __func__ +#define STRX(x) #x +#define STR(x) STRX(x) +#define __func__ __FILE__ ":" STR(__LINE__) +#endif +#define snprintf _snprintf +#define vsnprintf _vsnprintf +#define to64(x) _atoi64(x) +#if !defined(__MINGW32__) && !defined(__MINGW64__) +#define popen(x, y) _popen((x), (y)) +#define pclose(x) _pclose(x) +#define fileno _fileno +#endif +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#define fseeko(x, y, z) _fseeki64((x), (y), (z)) +#else +#define fseeko(x, y, z) fseek((x), (y), (z)) +#endif +#if defined(_MSC_VER) && _MSC_VER <= 1200 +typedef unsigned long uintptr_t; +typedef long intptr_t; +#endif +typedef int socklen_t; +#if _MSC_VER >= 1700 +#include +#else +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef int int32_t; +typedef unsigned int uint32_t; +typedef short int16_t; +typedef unsigned short uint16_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +#endif +typedef SOCKET sock_t; +typedef uint32_t in_addr_t; +#ifndef UINT16_MAX +#define UINT16_MAX 65535 +#endif +#ifndef UINT32_MAX +#define UINT32_MAX 4294967295 +#endif +#ifndef pid_t +#define pid_t HANDLE +#endif +#define INT64_FMT "I64d" +#define INT64_X_FMT "I64x" +#define SIZE_T_FMT "Iu" +typedef struct _stati64 cs_stat_t; +#ifndef S_ISDIR +#define S_ISDIR(x) (((x) &_S_IFMT) == _S_IFDIR) +#endif +#ifndef S_ISREG +#define S_ISREG(x) (((x) &_S_IFMT) == _S_IFREG) +#endif +#define DIRSEP '\\' +#define CS_DEFINE_DIRENT + +#ifndef va_copy +#ifdef __va_copy +#define va_copy __va_copy +#else +#define va_copy(x, y) (x) = (y) +#endif +#endif + +#ifndef MG_MAX_HTTP_REQUEST_SIZE +#define MG_MAX_HTTP_REQUEST_SIZE 8192 +#endif + +#ifndef MG_MAX_HTTP_SEND_MBUF +#define MG_MAX_HTTP_SEND_MBUF 4096 +#endif + +#ifndef MG_MAX_HTTP_HEADERS +#define MG_MAX_HTTP_HEADERS 40 +#endif + +#ifndef CS_ENABLE_STDIO +#define CS_ENABLE_STDIO 1 +#endif + +#ifndef MG_ENABLE_BROADCAST +#define MG_ENABLE_BROADCAST 1 +#endif + +#ifndef MG_ENABLE_DIRECTORY_LISTING +#define MG_ENABLE_DIRECTORY_LISTING 1 +#endif + +#ifndef MG_ENABLE_FILESYSTEM +#define MG_ENABLE_FILESYSTEM 1 +#endif + +#ifndef MG_ENABLE_HTTP_CGI +#define MG_ENABLE_HTTP_CGI MG_ENABLE_FILESYSTEM +#endif + +#ifndef MG_NET_IF +#define MG_NET_IF MG_NET_IF_SOCKET +#endif + +unsigned int sleep(unsigned int seconds); + +/* https://stackoverflow.com/questions/16647819/timegm-cross-platform */ +#define timegm _mkgmtime + +#define gmtime_r(a, b) \ + do { \ + *(b) = *gmtime(a); \ + } while (0) + +#endif /* CS_PLATFORM == CS_P_WINDOWS */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_unix.h" +#endif +#ifndef CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_ +#if CS_PLATFORM == CS_P_UNIX + +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 600 +#endif + +/* wants this for C++ */ +#ifndef __STDC_FORMAT_MACROS +#define __STDC_FORMAT_MACROS +#endif + +/* C++ wants that for INT64_MAX */ +#ifndef __STDC_LIMIT_MACROS +#define __STDC_LIMIT_MACROS +#endif + +/* Enable fseeko() and ftello() functions */ +#ifndef _LARGEFILE_SOURCE +#define _LARGEFILE_SOURCE +#endif + +/* Enable 64-bit file offsets */ +#ifndef _FILE_OFFSET_BITS +#define _FILE_OFFSET_BITS 64 +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __APPLE__ +#include +#ifndef BYTE_ORDER +#define LITTLE_ENDIAN __DARWIN_LITTLE_ENDIAN +#define BIG_ENDIAN __DARWIN_BIG_ENDIAN +#define PDP_ENDIAN __DARWIN_PDP_ENDIAN +#define BYTE_ORDER __DARWIN_BYTE_ORDER +#endif +#endif + +/* + * osx correctly avoids defining strtoll when compiling in strict ansi mode. + * c++ 11 standard defines strtoll as well. + * We require strtoll, and if your embedded pre-c99 compiler lacks one, please + * implement a shim. + */ +#if !(defined(__cplusplus) && __cplusplus >= 201103L) && \ + !(defined(__DARWIN_C_LEVEL) && __DARWIN_C_LEVEL >= 200809L) +long long strtoll(const char *, char **, int); +#endif + +typedef int sock_t; +#define INVALID_SOCKET (-1) +#define SIZE_T_FMT "zu" +typedef struct stat cs_stat_t; +#define DIRSEP '/' +#define to64(x) strtoll(x, NULL, 10) +#define INT64_FMT PRId64 +#define INT64_X_FMT PRIx64 + +#ifndef __cdecl +#define __cdecl +#endif + +#ifndef va_copy +#ifdef __va_copy +#define va_copy __va_copy +#else +#define va_copy(x, y) (x) = (y) +#endif +#endif + +#define closesocket(x) close(x) + +#ifndef MG_MAX_HTTP_REQUEST_SIZE +#define MG_MAX_HTTP_REQUEST_SIZE 8192 +#endif + +#ifndef MG_MAX_HTTP_SEND_MBUF +#define MG_MAX_HTTP_SEND_MBUF 4096 +#endif + +#ifndef MG_MAX_HTTP_HEADERS +#define MG_MAX_HTTP_HEADERS 40 +#endif + +#ifndef CS_ENABLE_STDIO +#define CS_ENABLE_STDIO 1 +#endif + +#ifndef MG_ENABLE_BROADCAST +#define MG_ENABLE_BROADCAST 1 +#endif + +#ifndef MG_ENABLE_DIRECTORY_LISTING +#define MG_ENABLE_DIRECTORY_LISTING 1 +#endif + +#ifndef MG_ENABLE_FILESYSTEM +#define MG_ENABLE_FILESYSTEM 1 +#endif + +#ifndef MG_ENABLE_HTTP_CGI +#define MG_ENABLE_HTTP_CGI MG_ENABLE_FILESYSTEM +#endif + +#ifndef MG_NET_IF +#define MG_NET_IF MG_NET_IF_SOCKET +#endif + +#ifndef MG_HOSTS_FILE_NAME +#define MG_HOSTS_FILE_NAME "/etc/hosts" +#endif + +#ifndef MG_RESOLV_CONF_FILE_NAME +#define MG_RESOLV_CONF_FILE_NAME "/etc/resolv.conf" +#endif + +#endif /* CS_PLATFORM == CS_P_UNIX */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_esp32.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_ +#if CS_PLATFORM == CS_P_ESP32 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SIZE_T_FMT "u" +typedef struct stat cs_stat_t; +#define DIRSEP '/' +#define to64(x) strtoll(x, NULL, 10) +#define INT64_FMT PRId64 +#define INT64_X_FMT PRIx64 +#define __cdecl +#define _FILE_OFFSET_BITS 32 + +#define MG_LWIP 1 + +#ifndef MG_NET_IF +#define MG_NET_IF MG_NET_IF_SOCKET +#endif + +#ifndef CS_ENABLE_STDIO +#define CS_ENABLE_STDIO 1 +#endif + +#endif /* CS_PLATFORM == CS_P_ESP32 */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_esp8266.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_ +#if CS_PLATFORM == CS_P_ESP8266 + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SIZE_T_FMT "u" +typedef struct stat cs_stat_t; +#define DIRSEP '/' +#if !defined(MGOS_VFS_DEFINE_DIRENT) +#define CS_DEFINE_DIRENT +#endif + +#define to64(x) strtoll(x, NULL, 10) +#define INT64_FMT PRId64 +#define INT64_X_FMT PRIx64 +#define __cdecl +#define _FILE_OFFSET_BITS 32 + +#define MG_LWIP 1 + +/* struct timeval is defined in sys/time.h. */ +#define LWIP_TIMEVAL_PRIVATE 0 + +#ifndef MG_NET_IF +#include +#if LWIP_SOCKET /* RTOS SDK has LWIP sockets */ +#define MG_NET_IF MG_NET_IF_SOCKET +#else +#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL +#endif +#endif + +#ifndef CS_ENABLE_STDIO +#define CS_ENABLE_STDIO 1 +#endif + +#define inet_ntop(af, src, dst, size) \ + (((af) == AF_INET) ? ipaddr_ntoa_r((const ip_addr_t *) (src), (dst), (size)) \ + : NULL) +#define inet_pton(af, src, dst) \ + (((af) == AF_INET) ? ipaddr_aton((src), (ip_addr_t *) (dst)) : 0) + +#endif /* CS_PLATFORM == CS_P_ESP8266 */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_cc3100.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_ +#if CS_PLATFORM == CS_P_CC3100 + +#include +#include +#include +#include +#include +#include +#include + +#define MG_NET_IF MG_NET_IF_SIMPLELINK +#define MG_SSL_IF MG_SSL_IF_SIMPLELINK + +/* + * CC3100 SDK and STM32 SDK include headers w/out path, just like + * #include "simplelink.h". As result, we have to add all required directories + * into Makefile IPATH and do the same thing (include w/out path) + */ + +#include +#include +#undef timeval + +typedef int sock_t; +#define INVALID_SOCKET (-1) + +#define to64(x) strtoll(x, NULL, 10) +#define INT64_FMT PRId64 +#define INT64_X_FMT PRIx64 +#define SIZE_T_FMT "u" + +#define SOMAXCONN 8 + +const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); +char *inet_ntoa(struct in_addr in); +int inet_pton(int af, const char *src, void *dst); + +#endif /* CS_PLATFORM == CS_P_CC3100 */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_cc3200.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ +#if CS_PLATFORM == CS_P_CC3200 + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef __TI_COMPILER_VERSION__ +#include +#include +#endif + +#define MG_NET_IF MG_NET_IF_SIMPLELINK +#define MG_SSL_IF MG_SSL_IF_SIMPLELINK + +/* Only SPIFFS supports directories, SLFS does not. */ +#if defined(CC3200_FS_SPIFFS) && !defined(MG_ENABLE_DIRECTORY_LISTING) +#define MG_ENABLE_DIRECTORY_LISTING 1 +#endif + +/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */ + +typedef int sock_t; +#define INVALID_SOCKET (-1) +#define SIZE_T_FMT "u" +typedef struct stat cs_stat_t; +#define DIRSEP '/' +#define to64(x) strtoll(x, NULL, 10) +#define INT64_FMT PRId64 +#define INT64_X_FMT PRIx64 +#define __cdecl + +#define fileno(x) -1 + +/* Some functions we implement for Mongoose. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __TI_COMPILER_VERSION__ +struct SlTimeval_t; +#define timeval SlTimeval_t +int gettimeofday(struct timeval *t, void *tz); +int settimeofday(const struct timeval *tv, const void *tz); + +int asprintf(char **strp, const char *fmt, ...); + +#endif + +/* TI's libc does not have stat & friends, add them. */ +#ifdef __TI_COMPILER_VERSION__ + +#include + +typedef unsigned int mode_t; +typedef size_t _off_t; +typedef long ssize_t; + +struct stat { + int st_ino; + mode_t st_mode; + int st_nlink; + time_t st_mtime; + off_t st_size; +}; + +int _stat(const char *pathname, struct stat *st); +int stat(const char *pathname, struct stat *st); + +#define __S_IFMT 0170000 + +#define __S_IFDIR 0040000 +#define __S_IFCHR 0020000 +#define __S_IFREG 0100000 + +#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask)) + +#define S_IFDIR __S_IFDIR +#define S_IFCHR __S_IFCHR +#define S_IFREG __S_IFREG +#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR) +#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG) + +/* 5.x series compilers don't have va_copy, 16.x do. */ +#if __TI_COMPILER_VERSION__ < 16000000 +#define va_copy(apc, ap) ((apc) = (ap)) +#endif + +#endif /* __TI_COMPILER_VERSION__ */ + +#ifdef CC3200_FS_SLFS +#define MG_FS_SLFS +#endif + +#if (defined(CC3200_FS_SPIFFS) || defined(CC3200_FS_SLFS)) && \ + !defined(MG_ENABLE_FILESYSTEM) +#define MG_ENABLE_FILESYSTEM 1 +#define CS_DEFINE_DIRENT +#endif + +#ifndef CS_ENABLE_STDIO +#define CS_ENABLE_STDIO 1 +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* CS_PLATFORM == CS_P_CC3200 */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_cc3220.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3220_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_CC3220_H_ +#if CS_PLATFORM == CS_P_CC3220 + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef __TI_COMPILER_VERSION__ +#include +#include +#endif + +#define MG_NET_IF MG_NET_IF_SIMPLELINK +#ifndef MG_SSL_IF +#define MG_SSL_IF MG_SSL_IF_SIMPLELINK +#endif + +/* Only SPIFFS supports directories, SLFS does not. */ +#if defined(CC3220_FS_SPIFFS) && !defined(MG_ENABLE_DIRECTORY_LISTING) +#define MG_ENABLE_DIRECTORY_LISTING 1 +#endif + +/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */ + +typedef int sock_t; +#define INVALID_SOCKET (-1) +#define SIZE_T_FMT "u" +typedef struct stat cs_stat_t; +#define DIRSEP '/' +#define to64(x) strtoll(x, NULL, 10) +#define INT64_FMT PRId64 +#define INT64_X_FMT PRIx64 +#define __cdecl + +#define fileno(x) -1 + +/* Some functions we implement for Mongoose. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __TI_COMPILER_VERSION__ +struct SlTimeval_t; +#define timeval SlTimeval_t +int gettimeofday(struct timeval *t, void *tz); +int settimeofday(const struct timeval *tv, const void *tz); + +int asprintf(char **strp, const char *fmt, ...); + +#endif + +/* TI's libc does not have stat & friends, add them. */ +#ifdef __TI_COMPILER_VERSION__ + +#include + +typedef unsigned int mode_t; +typedef size_t _off_t; +typedef long ssize_t; + +struct stat { + int st_ino; + mode_t st_mode; + int st_nlink; + time_t st_mtime; + off_t st_size; +}; + +int _stat(const char *pathname, struct stat *st); +int stat(const char *pathname, struct stat *st); + +#define __S_IFMT 0170000 + +#define __S_IFDIR 0040000 +#define __S_IFCHR 0020000 +#define __S_IFREG 0100000 + +#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask)) + +#define S_IFDIR __S_IFDIR +#define S_IFCHR __S_IFCHR +#define S_IFREG __S_IFREG +#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR) +#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG) + +#endif /* __TI_COMPILER_VERSION__ */ + +#ifndef CS_ENABLE_STDIO +#define CS_ENABLE_STDIO 1 +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* CS_PLATFORM == CS_P_CC3220 */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_msp432.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_ +#if CS_PLATFORM == CS_P_MSP432 + +#include +#include +#include +#include +#include +#include +#include + +#ifndef __TI_COMPILER_VERSION__ +#include +#include +#endif + +#define MG_NET_IF MG_NET_IF_SIMPLELINK +#define MG_SSL_IF MG_SSL_IF_SIMPLELINK + +/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */ + +typedef int sock_t; +#define INVALID_SOCKET (-1) +#define SIZE_T_FMT "u" +typedef struct stat cs_stat_t; +#define DIRSEP '/' +#define to64(x) strtoll(x, NULL, 10) +#define INT64_FMT PRId64 +#define INT64_X_FMT PRIx64 +#define __cdecl + +#define fileno(x) -1 + +/* Some functions we implement for Mongoose. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __TI_COMPILER_VERSION__ +struct SlTimeval_t; +#define timeval SlTimeval_t +int gettimeofday(struct timeval *t, void *tz); +#endif + +/* TI's libc does not have stat & friends, add them. */ +#ifdef __TI_COMPILER_VERSION__ + +#include + +typedef unsigned int mode_t; +typedef size_t _off_t; +typedef long ssize_t; + +struct stat { + int st_ino; + mode_t st_mode; + int st_nlink; + time_t st_mtime; + off_t st_size; +}; + +int _stat(const char *pathname, struct stat *st); +#define stat(a, b) _stat(a, b) + +#define __S_IFMT 0170000 + +#define __S_IFDIR 0040000 +#define __S_IFCHR 0020000 +#define __S_IFREG 0100000 + +#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask)) + +#define S_IFDIR __S_IFDIR +#define S_IFCHR __S_IFCHR +#define S_IFREG __S_IFREG +#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR) +#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG) + +/* As of 5.2.7, TI compiler does not support va_copy() yet. */ +#define va_copy(apc, ap) ((apc) = (ap)) + +#endif /* __TI_COMPILER_VERSION__ */ + +#ifndef CS_ENABLE_STDIO +#define CS_ENABLE_STDIO 1 +#endif + +#if (defined(CC3200_FS_SPIFFS) || defined(CC3200_FS_SLFS)) && \ + !defined(MG_ENABLE_FILESYSTEM) +#define MG_ENABLE_FILESYSTEM 1 +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* CS_PLATFORM == CS_P_MSP432 */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_tm4c129.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_ +#if CS_PLATFORM == CS_P_TM4C129 + +#include +#include +#include +#include +#include +#include +#include + +#ifndef __TI_COMPILER_VERSION__ +#include +#include +#endif + +#define SIZE_T_FMT "u" +typedef struct stat cs_stat_t; +#define DIRSEP '/' +#define to64(x) strtoll(x, NULL, 10) +#define INT64_FMT PRId64 +#define INT64_X_FMT PRIx64 +#define __cdecl + +#ifndef MG_NET_IF +#include +#if LWIP_SOCKET +#define MG_NET_IF MG_NET_IF_SOCKET +#else +#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL +#endif +#define MG_LWIP 1 +#elif MG_NET_IF == MG_NET_IF_SIMPLELINK +/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */ +#endif + +#ifndef CS_ENABLE_STDIO +#define CS_ENABLE_STDIO 1 +#endif + +#ifdef __TI_COMPILER_VERSION__ +/* As of 5.2.8, TI compiler does not support va_copy() yet. */ +#define va_copy(apc, ap) ((apc) = (ap)) +#endif /* __TI_COMPILER_VERSION__ */ + +#ifdef __cplusplus +} +#endif + +#endif /* CS_PLATFORM == CS_P_TM4C129 */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_mbed.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_PLATFORM_MBED_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_MBED_H_ +#if CS_PLATFORM == CS_P_MBED + +/* + * mbed.h contains C++ code (e.g. templates), thus, it should be processed + * only if included directly to startup file (ex: main.cpp) + */ +#ifdef __cplusplus +/* Amalgamated: #include "mbed.h" */ +#endif /* __cplusplus */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +typedef struct stat cs_stat_t; +#define DIRSEP '/' + +#ifndef CS_ENABLE_STDIO +#define CS_ENABLE_STDIO 1 +#endif + +/* + * mbed can be compiled with the ARM compiler which + * just doesn't come with a gettimeofday shim + * because it's a BSD API and ARM targets embedded + * non-unix platforms. + */ +#if defined(__ARMCC_VERSION) || defined(__ICCARM__) +#define _TIMEVAL_DEFINED +#define gettimeofday _gettimeofday + +/* copied from GCC on ARM; for some reason useconds are signed */ +typedef long suseconds_t; /* microseconds (signed) */ +struct timeval { + time_t tv_sec; /* seconds */ + suseconds_t tv_usec; /* and microseconds */ +}; + +#endif + +#if MG_NET_IF == MG_NET_IF_SIMPLELINK + +#define MG_SIMPLELINK_NO_OSI 1 + +#include + +typedef int sock_t; +#define INVALID_SOCKET (-1) + +#define to64(x) strtoll(x, NULL, 10) +#define INT64_FMT PRId64 +#define INT64_X_FMT PRIx64 +#define SIZE_T_FMT "u" + +#define SOMAXCONN 8 + +const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); +char *inet_ntoa(struct in_addr in); +int inet_pton(int af, const char *src, void *dst); +int inet_aton(const char *cp, struct in_addr *inp); +in_addr_t inet_addr(const char *cp); + +#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */ + +#endif /* CS_PLATFORM == CS_P_MBED */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_MBED_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_nrf51.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_ +#if CS_PLATFORM == CS_P_NRF51 + +#include +#include +#include +#include +#include +#include + +#define to64(x) strtoll(x, NULL, 10) + +#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL +#define MG_LWIP 1 +#define MG_ENABLE_IPV6 1 + +/* + * For ARM C Compiler, make lwip to export `struct timeval`; for other + * compilers, suppress it. + */ +#if !defined(__ARMCC_VERSION) +#define LWIP_TIMEVAL_PRIVATE 0 +#else +struct timeval; +int gettimeofday(struct timeval *tp, void *tzp); +#endif + +#define INT64_FMT PRId64 +#define SIZE_T_FMT "u" + +/* + * ARM C Compiler doesn't have strdup, so we provide it + */ +#define CS_ENABLE_STRDUP defined(__ARMCC_VERSION) + +#endif /* CS_PLATFORM == CS_P_NRF51 */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_nrf52.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_ +#if CS_PLATFORM == CS_P_NRF52 + +#include +#include +#include +#include +#include +#include +#include +#include + +#define to64(x) strtoll(x, NULL, 10) + +#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL +#define MG_LWIP 1 +#define MG_ENABLE_IPV6 1 + +#if !defined(ENOSPC) +#define ENOSPC 28 /* No space left on device */ +#endif + +/* + * For ARM C Compiler, make lwip to export `struct timeval`; for other + * compilers, suppress it. + */ +#if !defined(__ARMCC_VERSION) +#define LWIP_TIMEVAL_PRIVATE 0 +#endif + +#define INT64_FMT PRId64 +#define SIZE_T_FMT "u" + +/* + * ARM C Compiler doesn't have strdup, so we provide it + */ +#define CS_ENABLE_STRDUP defined(__ARMCC_VERSION) + +#endif /* CS_PLATFORM == CS_P_NRF52 */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/simplelink/cs_simplelink.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_ +#define CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_ + +#if defined(MG_NET_IF) && MG_NET_IF == MG_NET_IF_SIMPLELINK + +/* If simplelink.h is already included, all bets are off. */ +#if !defined(__SIMPLELINK_H__) + +#include + +#ifndef __TI_COMPILER_VERSION__ +#undef __CONCAT +#undef FD_CLR +#undef FD_ISSET +#undef FD_SET +#undef FD_SETSIZE +#undef FD_ZERO +#undef fd_set +#endif + +#if CS_PLATFORM == CS_P_CC3220 +#include +#include +#include +#include +#else +/* We want to disable SL_INC_STD_BSD_API_NAMING, so we include user.h ourselves + * and undef it. */ +#define PROVISIONING_API_H_ +#include +#undef PROVISIONING_API_H_ +#undef SL_INC_STD_BSD_API_NAMING + +#include +#include +#endif /* CS_PLATFORM == CS_P_CC3220 */ + +/* Now define only the subset of the BSD API that we use. + * Notably, close(), read() and write() are not defined. */ +#define AF_INET SL_AF_INET + +#define socklen_t SlSocklen_t +#define sockaddr SlSockAddr_t +#define sockaddr_in SlSockAddrIn_t +#define in_addr SlInAddr_t + +#define SOCK_STREAM SL_SOCK_STREAM +#define SOCK_DGRAM SL_SOCK_DGRAM + +#define htonl sl_Htonl +#define ntohl sl_Ntohl +#define htons sl_Htons +#define ntohs sl_Ntohs + +#ifndef EACCES +#define EACCES SL_EACCES +#endif +#ifndef EAFNOSUPPORT +#define EAFNOSUPPORT SL_EAFNOSUPPORT +#endif +#ifndef EAGAIN +#define EAGAIN SL_EAGAIN +#endif +#ifndef EBADF +#define EBADF SL_EBADF +#endif +#ifndef EINVAL +#define EINVAL SL_EINVAL +#endif +#ifndef ENOMEM +#define ENOMEM SL_ENOMEM +#endif +#ifndef EWOULDBLOCK +#define EWOULDBLOCK SL_EWOULDBLOCK +#endif + +#define SOMAXCONN 8 + +#ifdef __cplusplus +extern "C" { +#endif + +const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); +char *inet_ntoa(struct in_addr in); +int inet_pton(int af, const char *src, void *dst); + +struct mg_mgr; +struct mg_connection; + +typedef void (*mg_init_cb)(struct mg_mgr *mgr); +bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init); + +void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg); + +int sl_fs_init(void); + +void sl_restart_cb(struct mg_mgr *mgr); + +int sl_set_ssl_opts(int sock, struct mg_connection *nc); + +#ifdef __cplusplus +} +#endif + +#endif /* !defined(__SIMPLELINK_H__) */ + +/* Compatibility with older versions of SimpleLink */ +#if SL_MAJOR_VERSION_NUM < 2 + +#define SL_ERROR_BSD_EAGAIN SL_EAGAIN +#define SL_ERROR_BSD_EALREADY SL_EALREADY +#define SL_ERROR_BSD_ENOPROTOOPT SL_ENOPROTOOPT +#define SL_ERROR_BSD_ESECDATEERROR SL_ESECDATEERROR +#define SL_ERROR_BSD_ESECSNOVERIFY SL_ESECSNOVERIFY +#define SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM SL_FS_ERR_FAILED_TO_ALLOCATE_MEM +#define SL_ERROR_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY \ + SL_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY +#define SL_ERROR_FS_FILE_NAME_EXIST SL_FS_FILE_NAME_EXIST +#define SL_ERROR_FS_FILE_NOT_EXISTS SL_FS_ERR_FILE_NOT_EXISTS +#define SL_ERROR_FS_NO_AVAILABLE_NV_INDEX SL_FS_ERR_NO_AVAILABLE_NV_INDEX +#define SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE SL_FS_ERR_NO_AVAILABLE_BLOCKS +#define SL_ERROR_FS_NOT_SUPPORTED SL_FS_ERR_NOT_SUPPORTED +#define SL_ERROR_FS_WRONG_FILE_NAME SL_FS_WRONG_FILE_NAME +#define SL_ERROR_FS_INVALID_HANDLE SL_FS_ERR_INVALID_HANDLE +#define SL_NETCFG_MAC_ADDRESS_GET SL_MAC_ADDRESS_GET +#define SL_SOCKET_FD_ZERO SL_FD_ZERO +#define SL_SOCKET_FD_SET SL_FD_SET +#define SL_SOCKET_FD_ISSET SL_FD_ISSET +#define SL_SO_SECURE_DOMAIN_NAME_VERIFICATION SO_SECURE_DOMAIN_NAME_VERIFICATION + +#define SL_FS_READ FS_MODE_OPEN_READ +#define SL_FS_WRITE FS_MODE_OPEN_WRITE + +#define SL_FI_FILE_SIZE(fi) ((fi).FileLen) +#define SL_FI_FILE_MAX_SIZE(fi) ((fi).AllocatedLen) + +#define SlDeviceVersion_t SlVersionFull +#define sl_DeviceGet sl_DevGet +#define SL_DEVICE_GENERAL SL_DEVICE_GENERAL_CONFIGURATION +#define SL_LEN_TYPE _u8 +#define SL_OPT_TYPE _u8 + +#else /* SL_MAJOR_VERSION_NUM >= 2 */ + +#define FS_MODE_OPEN_CREATE(max_size, flag) \ + (SL_FS_CREATE | SL_FS_CREATE_MAX_SIZE(max_size)) +#define SL_FI_FILE_SIZE(fi) ((fi).Len) +#define SL_FI_FILE_MAX_SIZE(fi) ((fi).MaxSize) + +#define SL_LEN_TYPE _u16 +#define SL_OPT_TYPE _u16 + +#endif /* SL_MAJOR_VERSION_NUM < 2 */ + +int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token); + +#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */ + +#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_wince.h" +#endif +#ifndef CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_ + +#if CS_PLATFORM == CS_P_WINCE + +/* + * MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) + * MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013) + * MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012) + * MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010) + * MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008) + * MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005) + * MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio 2003) + * MSVC++ 7.0 _MSC_VER == 1300 + * MSVC++ 6.0 _MSC_VER == 1200 + * MSVC++ 5.0 _MSC_VER == 1100 + */ +#pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */ +#pragma warning(disable : 4204) /* missing c99 support */ + +#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS +#define _WINSOCK_DEPRECATED_NO_WARNINGS 1 +#endif + +#ifndef _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include +#include +#include +#include +#include +#include + +#pragma comment(lib, "ws2.lib") /* Linking with WinCE winsock library */ + +#include +#include +#include + +#define strdup _strdup + +#ifndef EINPROGRESS +#define EINPROGRESS WSAEINPROGRESS +#endif + +#ifndef EWOULDBLOCK +#define EWOULDBLOCK WSAEWOULDBLOCK +#endif + +#ifndef EAGAIN +#define EAGAIN EWOULDBLOCK +#endif + +#ifndef __func__ +#define STRX(x) #x +#define STR(x) STRX(x) +#define __func__ __FILE__ ":" STR(__LINE__) +#endif + +#define snprintf _snprintf +#define fileno _fileno +#define vsnprintf _vsnprintf +#define sleep(x) Sleep((x) *1000) +#define to64(x) _atoi64(x) +#define rmdir _rmdir + +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#define fseeko(x, y, z) _fseeki64((x), (y), (z)) +#else +#define fseeko(x, y, z) fseek((x), (y), (z)) +#endif + +typedef int socklen_t; + +#if _MSC_VER >= 1700 +#include +#else +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef int int32_t; +typedef unsigned int uint32_t; +typedef short int16_t; +typedef unsigned short uint16_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +#endif + +typedef SOCKET sock_t; +typedef uint32_t in_addr_t; + +#ifndef UINT16_MAX +#define UINT16_MAX 65535 +#endif + +#ifndef UINT32_MAX +#define UINT32_MAX 4294967295 +#endif + +#ifndef pid_t +#define pid_t HANDLE +#endif + +#define INT64_FMT "I64d" +#define INT64_X_FMT "I64x" +/* TODO(alashkin): check if this is correct */ +#define SIZE_T_FMT "u" + +#define DIRSEP '\\' +#define CS_DEFINE_DIRENT + +#ifndef va_copy +#ifdef __va_copy +#define va_copy __va_copy +#else +#define va_copy(x, y) (x) = (y) +#endif +#endif + +#ifndef MG_MAX_HTTP_REQUEST_SIZE +#define MG_MAX_HTTP_REQUEST_SIZE 8192 +#endif + +#ifndef MG_MAX_HTTP_SEND_MBUF +#define MG_MAX_HTTP_SEND_MBUF 4096 +#endif + +#ifndef MG_MAX_HTTP_HEADERS +#define MG_MAX_HTTP_HEADERS 40 +#endif + +#ifndef CS_ENABLE_STDIO +#define CS_ENABLE_STDIO 1 +#endif + +#define abort() DebugBreak(); + +#ifndef BUFSIZ +#define BUFSIZ 4096 +#endif +/* + * Explicitly disabling MG_ENABLE_THREADS for WinCE + * because they are enabled for _WIN32 by default + */ +#ifndef MG_ENABLE_THREADS +#define MG_ENABLE_THREADS 0 +#endif + +#ifndef MG_ENABLE_FILESYSTEM +#define MG_ENABLE_FILESYSTEM 1 +#endif + +#ifndef MG_NET_IF +#define MG_NET_IF MG_NET_IF_SOCKET +#endif + +typedef struct _stati64 { + uint32_t st_mtime; + uint32_t st_size; + uint32_t st_mode; +} cs_stat_t; + +/* + * WinCE 6.0 has a lot of useful definitions in ATL (not windows.h) headers + * use #ifdefs to avoid conflicts + */ + +#ifndef ENOENT +#define ENOENT ERROR_PATH_NOT_FOUND +#endif + +#ifndef EACCES +#define EACCES ERROR_ACCESS_DENIED +#endif + +#ifndef ENOMEM +#define ENOMEM ERROR_NOT_ENOUGH_MEMORY +#endif + +#ifndef _UINTPTR_T_DEFINED +typedef unsigned int *uintptr_t; +#endif + +#define _S_IFREG 2 +#define _S_IFDIR 4 + +#ifndef S_ISDIR +#define S_ISDIR(x) (((x) &_S_IFDIR) != 0) +#endif + +#ifndef S_ISREG +#define S_ISREG(x) (((x) &_S_IFREG) != 0) +#endif + +int open(const char *filename, int oflag, int pmode); +int _wstati64(const wchar_t *path, cs_stat_t *st); +const char *strerror(); + +#endif /* CS_PLATFORM == CS_P_WINCE */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_nxp_lpc.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_ + +#if CS_PLATFORM == CS_P_NXP_LPC + +#include +#include +#include + +#define SIZE_T_FMT "u" +typedef struct stat cs_stat_t; +#define INT64_FMT "lld" +#define INT64_X_FMT "llx" +#define __cdecl + +#define MG_LWIP 1 + +#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL + +/* + * LPCXpress comes with 3 C library implementations: Newlib, NewlibNano and + *Redlib. + * See https://community.nxp.com/message/630860 for more details. + * + * Redlib is the default and lacks certain things, so we provide them. + */ +#ifdef __REDLIB_INTERFACE_VERSION__ + +/* Let LWIP define timeval for us. */ +#define LWIP_TIMEVAL_PRIVATE 1 + +#define va_copy(d, s) __builtin_va_copy(d, s) + +#define CS_ENABLE_TO64 1 +#define to64(x) cs_to64(x) + +#define CS_ENABLE_STRDUP 1 + +#else + +#include +#define LWIP_TIMEVAL_PRIVATE 0 +#define to64(x) strtoll(x, NULL, 10) + +#endif + +#endif /* CS_PLATFORM == CS_P_NXP_LPC */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_nxp_kinetis.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_ + +#if CS_PLATFORM == CS_P_NXP_KINETIS + +#include +#include +#include +#include + +#define SIZE_T_FMT "u" +typedef struct stat cs_stat_t; +#define to64(x) strtoll(x, NULL, 10) +#define INT64_FMT "lld" +#define INT64_X_FMT "llx" +#define __cdecl + +#define MG_LWIP 1 + +#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL + +/* struct timeval is defined in sys/time.h. */ +#define LWIP_TIMEVAL_PRIVATE 0 + +#endif /* CS_PLATFORM == CS_P_NXP_KINETIS */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_pic32.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_ + +#if CS_PLATFORM == CS_P_PIC32 + +#define MG_NET_IF MG_NET_IF_PIC32 + +#include +#include +#include +#include + +#include +#include + +#include + +typedef TCP_SOCKET sock_t; +#define to64(x) strtoll(x, NULL, 10) + +#define SIZE_T_FMT "lu" +#define INT64_FMT "lld" + +#ifndef CS_ENABLE_STDIO +#define CS_ENABLE_STDIO 1 +#endif + +char *inet_ntoa(struct in_addr in); + +#endif /* CS_PLATFORM == CS_P_PIC32 */ + +#endif /* CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/platform_stm32.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_PLATFORM_STM32_H_ +#define CS_COMMON_PLATFORMS_PLATFORM_STM32_H_ +#if CS_PLATFORM == CS_P_STM32 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define to64(x) strtoll(x, NULL, 10) +#define INT64_FMT "lld" +#define SIZE_T_FMT "u" +typedef struct stat cs_stat_t; +#define DIRSEP '/' + +#ifndef CS_ENABLE_STDIO +#define CS_ENABLE_STDIO 1 +#endif + +#ifndef MG_ENABLE_FILESYSTEM +#define MG_ENABLE_FILESYSTEM 1 +#endif + +#endif /* CS_PLATFORM == CS_P_STM32 */ +#endif /* CS_COMMON_PLATFORMS_PLATFORM_STM32_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/platforms/lwip/mg_lwip.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_ +#define CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_ + +#ifndef MG_LWIP +#define MG_LWIP 0 +#endif + +#if MG_LWIP + +/* + * When compiling for nRF5x chips with arm-none-eabi-gcc, it has BYTE_ORDER + * already defined, so in order to avoid warnings in lwip, we have to undefine + * it. + * + * TODO: Check if in the future versions of nRF5 SDK that changes. + * Current version of nRF51 SDK: 0.8.0 + * nRF5 SDK: 0.9.0 + */ +#if CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52 +#undef BYTE_ORDER +#endif + +#include +#include +#include +#include +#include +#include + +#ifndef LWIP_PROVIDE_ERRNO +#include +#endif + +#if LWIP_SOCKET +#include +#else +/* We really need the definitions from sockets.h. */ +#undef LWIP_SOCKET +#define LWIP_SOCKET 1 +#include +#undef LWIP_SOCKET +#define LWIP_SOCKET 0 +#endif + +#define INVALID_SOCKET (-1) +#define SOMAXCONN 10 +typedef int sock_t; + +#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL +struct mg_mgr; +struct mg_connection; +void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle, + int interval, int count); +#endif + +/* For older version of LWIP */ +#ifndef ipX_2_ip +#define ipX_2_ip(x) (x) +#endif + +#endif /* MG_LWIP */ + +#endif /* CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/cs_md5.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_MD5_H_ +#define CS_COMMON_MD5_H_ + +/* Amalgamated: #include "common/platform.h" */ + +#ifndef CS_DISABLE_MD5 +#define CS_DISABLE_MD5 0 +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +typedef struct { + uint32_t buf[4]; + uint32_t bits[2]; + unsigned char in[64]; +} cs_md5_ctx; + +void cs_md5_init(cs_md5_ctx *c); +void cs_md5_update(cs_md5_ctx *c, const unsigned char *data, size_t len); +void cs_md5_final(unsigned char *md, cs_md5_ctx *c); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* CS_COMMON_MD5_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/cs_sha1.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_SHA1_H_ +#define CS_COMMON_SHA1_H_ + +#ifndef CS_DISABLE_SHA1 +#define CS_DISABLE_SHA1 0 +#endif + +#if !CS_DISABLE_SHA1 + +/* Amalgamated: #include "common/platform.h" */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +typedef struct { + uint32_t state[5]; + uint32_t count[2]; + unsigned char buffer[64]; +} cs_sha1_ctx; + +void cs_sha1_init(cs_sha1_ctx *); +void cs_sha1_update(cs_sha1_ctx *, const unsigned char *data, uint32_t len); +void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *); +void cs_hmac_sha1(const unsigned char *key, size_t key_len, + const unsigned char *text, size_t text_len, + unsigned char out[20]); +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* CS_DISABLE_SHA1 */ + +#endif /* CS_COMMON_SHA1_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/cs_time.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_CS_TIME_H_ +#define CS_COMMON_CS_TIME_H_ + +#include + +/* Amalgamated: #include "common/platform.h" */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Sub-second granularity time(). */ +double cs_time(void); + +/* + * Similar to (non-standard) timegm, converts broken-down time into the number + * of seconds since Unix Epoch. + */ +double cs_timegm(const struct tm *tm); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* CS_COMMON_CS_TIME_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/mg_str.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_MG_STR_H_ +#define CS_COMMON_MG_STR_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Describes chunk of memory */ +struct mg_str { + const char *p; /* Memory chunk pointer */ + size_t len; /* Memory chunk length */ +}; + +/* + * Helper function for creating mg_str struct from plain C string. + * `NULL` is allowed and becomes `{NULL, 0}`. + */ +struct mg_str mg_mk_str(const char *s); + +/* + * Like `mg_mk_str`, but takes string length explicitly. + */ +struct mg_str mg_mk_str_n(const char *s, size_t len); + +/* Macro for initializing mg_str. */ +#define MG_MK_STR(str_literal) \ + { str_literal, sizeof(str_literal) - 1 } +#define MG_MK_STR_N(str_literal, len) \ + { str_literal, len } +#define MG_NULL_STR \ + { NULL, 0 } + +/* + * Cross-platform version of `strcmp()` where where first string is + * specified by `struct mg_str`. + */ +int mg_vcmp(const struct mg_str *str2, const char *str1); + +/* + * Cross-platform version of `strncasecmp()` where first string is + * specified by `struct mg_str`. + */ +int mg_vcasecmp(const struct mg_str *str2, const char *str1); + +/* Creates a copy of s (heap-allocated). */ +struct mg_str mg_strdup(const struct mg_str s); + +/* + * Creates a copy of s (heap-allocated). + * Resulting string is NUL-terminated (but NUL is not included in len). + */ +struct mg_str mg_strdup_nul(const struct mg_str s); + +/* + * Locates character in a string. + */ +const char *mg_strchr(const struct mg_str s, int c); + +/* + * Compare two `mg_str`s; return value is the same as `strcmp`. + */ +int mg_strcmp(const struct mg_str str1, const struct mg_str str2); + +/* + * Like `mg_strcmp`, but compares at most `n` characters. + */ +int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n); + +/* + * Free the string (assuming it was heap allocated). + */ +void mg_strfree(struct mg_str *s); + +/* + * Finds the first occurrence of a substring `needle` in the `haystack`. + */ +const char *mg_strstr(const struct mg_str haystack, const struct mg_str needle); + +/* Strip whitespace at the start and the end of s */ +struct mg_str mg_strstrip(struct mg_str s); + +/* Returns 1 if s starts with the given prefix. */ +int mg_str_starts_with(struct mg_str s, struct mg_str prefix); + +#ifdef __cplusplus +} +#endif + +#endif /* CS_COMMON_MG_STR_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/mbuf.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Mbufs are mutable/growing memory buffers, like C++ strings. + * Mbuf can append data to the end of a buffer or insert data into arbitrary + * position in the middle of a buffer. The buffer grows automatically when + * needed. + */ + +#ifndef CS_COMMON_MBUF_H_ +#define CS_COMMON_MBUF_H_ + +#include +/* Amalgamated: #include "common/platform.h" */ + +#if defined(__cplusplus) +extern "C" { +#endif + +#ifndef MBUF_SIZE_MULTIPLIER +#define MBUF_SIZE_MULTIPLIER 1.5 +#endif + +#ifndef MBUF_SIZE_MAX_HEADROOM +#ifdef BUFSIZ +#define MBUF_SIZE_MAX_HEADROOM BUFSIZ +#else +#define MBUF_SIZE_MAX_HEADROOM 1024 +#endif +#endif + +/* Memory buffer descriptor */ +struct mbuf { + char *buf; /* Buffer pointer */ + size_t len; /* Data length. Data is located between offset 0 and len. */ + size_t size; /* Buffer size allocated by realloc(1). Must be >= len */ +}; + +/* + * Initialises an Mbuf. + * `initial_capacity` specifies the initial capacity of the mbuf. + */ +void mbuf_init(struct mbuf *, size_t initial_capacity); + +/* Frees the space allocated for the mbuffer and resets the mbuf structure. */ +void mbuf_free(struct mbuf *); + +/* + * Appends data to the Mbuf. + * + * Returns the number of bytes appended or 0 if out of memory. + */ +size_t mbuf_append(struct mbuf *, const void *data, size_t data_size); + +/* + * Appends data to the Mbuf and frees it (data must be heap-allocated). + * + * Returns the number of bytes appended or 0 if out of memory. + * data is freed irrespective of return value. + */ +size_t mbuf_append_and_free(struct mbuf *, void *data, size_t data_size); + +/* + * Inserts data at a specified offset in the Mbuf. + * + * Existing data will be shifted forwards and the buffer will + * be grown if necessary. + * Returns the number of bytes inserted. + */ +size_t mbuf_insert(struct mbuf *, size_t, const void *, size_t); + +/* Removes `data_size` bytes from the beginning of the buffer. */ +void mbuf_remove(struct mbuf *, size_t data_size); + +/* + * Resizes an Mbuf. + * + * If `new_size` is smaller than buffer's `len`, the + * resize is not performed. + */ +void mbuf_resize(struct mbuf *, size_t new_size); + +/* Moves the state from one mbuf to the other. */ +void mbuf_move(struct mbuf *from, struct mbuf *to); + +/* Removes all the data from mbuf (if any). */ +void mbuf_clear(struct mbuf *); + +/* Shrinks an Mbuf by resizing its `size` to `len`. */ +void mbuf_trim(struct mbuf *); + +#if defined(__cplusplus) +} +#endif /* __cplusplus */ + +#endif /* CS_COMMON_MBUF_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/cs_base64.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_CS_BASE64_H_ +#define CS_COMMON_CS_BASE64_H_ + +#ifndef DISABLE_BASE64 +#define DISABLE_BASE64 0 +#endif + +#if !DISABLE_BASE64 + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*cs_base64_putc_t)(char, void *); + +struct cs_base64_ctx { + /* cannot call it putc because it's a macro on some environments */ + cs_base64_putc_t b64_putc; + unsigned char chunk[3]; + int chunk_size; + void *user_data; +}; + +void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t putc, + void *user_data); +void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len); +void cs_base64_finish(struct cs_base64_ctx *ctx); + +void cs_base64_encode(const unsigned char *src, int src_len, char *dst); +void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len); + +/* + * Decodes a base64 string `s` length `len` into `dst`. + * `dst` must have enough space to hold the result. + * `*dec_len` will contain the resulting length of the string in `dst` + * while return value will return number of processed bytes in `src`. + * Return value == len indicates successful processing of all the data. + */ +int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len); + +#ifdef __cplusplus +} +#endif + +#endif /* DISABLE_BASE64 */ + +#endif /* CS_COMMON_CS_BASE64_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/str_util.h" +#endif +/* + * Copyright (c) 2014-2018 Cesanta Software Limited + * All rights reserved + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CS_COMMON_STR_UTIL_H_ +#define CS_COMMON_STR_UTIL_H_ + +#include +#include + +/* Amalgamated: #include "common/mg_str.h" */ +/* Amalgamated: #include "common/platform.h" */ + +#ifndef CS_ENABLE_STRDUP +#define CS_ENABLE_STRDUP 0 +#endif + +#ifndef CS_ENABLE_TO64 +#define CS_ENABLE_TO64 0 +#endif + +/* + * Expands to a string representation of its argument: e.g. + * `CS_STRINGIFY_LIT(5) expands to "5"` + */ +#if !defined(_MSC_VER) || _MSC_VER >= 1900 +#define CS_STRINGIFY_LIT(...) #__VA_ARGS__ +#else +#define CS_STRINGIFY_LIT(x) #x +#endif + +/* + * Expands to a string representation of its argument, which is allowed + * to be a macro: e.g. + * + * #define FOO 123 + * CS_STRINGIFY_MACRO(FOO) + * + * expands to 123. + */ +#define CS_STRINGIFY_MACRO(x) CS_STRINGIFY_LIT(x) + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Equivalent of standard `strnlen()`. + */ +size_t c_strnlen(const char *s, size_t maxlen); + +/* + * Equivalent of standard `snprintf()`. + */ +int c_snprintf(char *buf, size_t buf_size, const char *format, ...) + PRINTF_LIKE(3, 4); + +/* + * Equivalent of standard `vsnprintf()`. + */ +int c_vsnprintf(char *buf, size_t buf_size, const char *format, va_list ap); + +/* + * Find the first occurrence of find in s, where the search is limited to the + * first slen characters of s. + */ +const char *c_strnstr(const char *s, const char *find, size_t slen); + +/* + * Stringify binary data. Output buffer size must be 2 * size_of_input + 1 + * because each byte of input takes 2 bytes in string representation + * plus 1 byte for the terminating \0 character. + */ +void cs_to_hex(char *to, const unsigned char *p, size_t len); + +/* + * Convert stringified binary data back to binary. + * Does the reverse of `cs_to_hex()`. + */ +void cs_from_hex(char *to, const char *p, size_t len); + +#if CS_ENABLE_STRDUP +/* + * Equivalent of standard `strdup()`, defined if only `CS_ENABLE_STRDUP` is 1. + */ +char *strdup(const char *src); +#endif + +#if CS_ENABLE_TO64 +#include +/* + * Simple string -> int64 conversion routine. + */ +int64_t cs_to64(const char *s); +#endif + +/* + * Cross-platform version of `strncasecmp()`. + */ +int mg_ncasecmp(const char *s1, const char *s2, size_t len); + +/* + * Cross-platform version of `strcasecmp()`. + */ +int mg_casecmp(const char *s1, const char *s2); + +/* + * Prints message to the buffer. If the buffer is large enough to hold the + * message, it returns buffer. If buffer is to small, it allocates a large + * enough buffer on heap and returns allocated buffer. + * This is a supposed use case: + * + * ```c + * char buf[5], *p = buf; + * mg_avprintf(&p, sizeof(buf), "%s", "hi there"); + * use_p_somehow(p); + * if (p != buf) { + * free(p); + * } + * ``` + * + * The purpose of this is to avoid malloc-ing if generated strings are small. + */ +int mg_asprintf(char **buf, size_t size, const char *fmt, ...) + PRINTF_LIKE(3, 4); + +/* Same as mg_asprintf, but takes varargs list. */ +int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap); + +/* + * A helper function for traversing a comma separated list of values. + * It returns a list pointer shifted to the next value or NULL if the end + * of the list found. + * The value is stored in a val vector. If the value has a form "x=y", then + * eq_val vector is initialised to point to the "y" part, and val vector length + * is adjusted to point only to "x". + * If the list is just a comma separated list of entries, like "aa,bb,cc" then + * `eq_val` will contain zero-length string. + * + * The purpose of this function is to parse comma separated string without + * any copying/memory allocation. + */ +const char *mg_next_comma_list_entry(const char *list, struct mg_str *val, + struct mg_str *eq_val); + +/* + * Like `mg_next_comma_list_entry()`, but takes `list` as `struct mg_str`. + * NB: Test return value's .p, not .len. On last itreation that yields result + * .len will be 0 but .p will not. When finished, .p will be NULL. + */ +struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val, + struct mg_str *eq_val); + +/* + * Matches 0-terminated string (mg_match_prefix) or string with given length + * mg_match_prefix_n against a glob pattern. Glob syntax: + * ``` + * - * matches zero or more characters until a slash character / + * - ** matches zero or more characters + * - ? Matches exactly one character which is not a slash / + * - | or , divides alternative patterns + * - any other character matches itself + * ``` + * Match is case-insensitive. Return number of bytes matched. + * Examples: + * ``` + * mg_match_prefix("a*f", len, "abcdefgh") == 6 + * mg_match_prefix("a*f", len, "abcdexgh") == 0 + * mg_match_prefix("a*f|de*,xy", len, "defgh") == 5 + * mg_match_prefix("?*", len, "abc") == 3 + * mg_match_prefix("?*", len, "") == 0 + * ``` + */ +size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str); + +/* + * Like `mg_match_prefix()`, but takes `pattern` and `str` as `struct mg_str`. + */ +size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str); + +#ifdef __cplusplus +} +#endif + +#endif /* CS_COMMON_STR_UTIL_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "common/queue.h" +#endif +/* clang-format off */ +/*- + * Copyright (c) 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)queue.h 8.5 (Berkeley) 8/20/94 + * $FreeBSD$ + */ + +#ifndef _SYS_QUEUE_H_ +#define _SYS_QUEUE_H_ + +/* + * This file defines four types of data structures: singly-linked lists, + * singly-linked tail queues, lists and tail queues. + * + * A singly-linked list is headed by a single forward pointer. The elements + * are singly linked for minimum space and pointer manipulation overhead at + * the expense of O(n) removal for arbitrary elements. New elements can be + * added to the list after an existing element or at the head of the list. + * Elements being removed from the head of the list should use the explicit + * macro for this purpose for optimum efficiency. A singly-linked list may + * only be traversed in the forward direction. Singly-linked lists are ideal + * for applications with large datasets and few or no removals or for + * implementing a LIFO queue. + * + * A singly-linked tail queue is headed by a pair of pointers, one to the + * head of the list and the other to the tail of the list. The elements are + * singly linked for minimum space and pointer manipulation overhead at the + * expense of O(n) removal for arbitrary elements. New elements can be added + * to the list after an existing element, at the head of the list, or at the + * end of the list. Elements being removed from the head of the tail queue + * should use the explicit macro for this purpose for optimum efficiency. + * A singly-linked tail queue may only be traversed in the forward direction. + * Singly-linked tail queues are ideal for applications with large datasets + * and few or no removals or for implementing a FIFO queue. + * + * A list is headed by a single forward pointer (or an array of forward + * pointers for a hash table header). The elements are doubly linked + * so that an arbitrary element can be removed without a need to + * traverse the list. New elements can be added to the list before + * or after an existing element or at the head of the list. A list + * may be traversed in either direction. + * + * A tail queue is headed by a pair of pointers, one to the head of the + * list and the other to the tail of the list. The elements are doubly + * linked so that an arbitrary element can be removed without a need to + * traverse the list. New elements can be added to the list before or + * after an existing element, at the head of the list, or at the end of + * the list. A tail queue may be traversed in either direction. + * + * For details on the use of these macros, see the queue(3) manual page. + * + * + * SLIST LIST STAILQ TAILQ + * _HEAD + + + + + * _CLASS_HEAD + + + + + * _HEAD_INITIALIZER + + + + + * _ENTRY + + + + + * _CLASS_ENTRY + + + + + * _INIT + + + + + * _EMPTY + + + + + * _FIRST + + + + + * _NEXT + + + + + * _PREV - + - + + * _LAST - - + + + * _FOREACH + + + + + * _FOREACH_FROM + + + + + * _FOREACH_SAFE + + + + + * _FOREACH_FROM_SAFE + + + + + * _FOREACH_REVERSE - - - + + * _FOREACH_REVERSE_FROM - - - + + * _FOREACH_REVERSE_SAFE - - - + + * _FOREACH_REVERSE_FROM_SAFE - - - + + * _INSERT_HEAD + + + + + * _INSERT_BEFORE - + - + + * _INSERT_AFTER + + + + + * _INSERT_TAIL - - + + + * _CONCAT - - + + + * _REMOVE_AFTER + - + - + * _REMOVE_HEAD + - + - + * _REMOVE + + + + + * _SWAP + + + + + * + */ +#ifdef QUEUE_MACRO_DEBUG +/* Store the last 2 places the queue element or head was altered */ +struct qm_trace { + unsigned long lastline; + unsigned long prevline; + const char *lastfile; + const char *prevfile; +}; + +#define TRACEBUF struct qm_trace trace; +#define TRACEBUF_INITIALIZER { __LINE__, 0, __FILE__, NULL } , +#define TRASHIT(x) do {(x) = (void *)-1;} while (0) +#define QMD_SAVELINK(name, link) void **name = (void *)&(link) + +#define QMD_TRACE_HEAD(head) do { \ + (head)->trace.prevline = (head)->trace.lastline; \ + (head)->trace.prevfile = (head)->trace.lastfile; \ + (head)->trace.lastline = __LINE__; \ + (head)->trace.lastfile = __FILE__; \ +} while (0) + +#define QMD_TRACE_ELEM(elem) do { \ + (elem)->trace.prevline = (elem)->trace.lastline; \ + (elem)->trace.prevfile = (elem)->trace.lastfile; \ + (elem)->trace.lastline = __LINE__; \ + (elem)->trace.lastfile = __FILE__; \ +} while (0) + +#else +#define QMD_TRACE_ELEM(elem) +#define QMD_TRACE_HEAD(head) +#define QMD_SAVELINK(name, link) +#define TRACEBUF +#define TRACEBUF_INITIALIZER +#define TRASHIT(x) +#endif /* QUEUE_MACRO_DEBUG */ + +#ifdef __cplusplus +/* + * In C++ there can be structure lists and class lists: + */ +#define QUEUE_TYPEOF(type) type +#else +#define QUEUE_TYPEOF(type) struct type +#endif + +/* + * Singly-linked List declarations. + */ +#define SLIST_HEAD(name, type) \ +struct name { \ + struct type *slh_first; /* first element */ \ +} + +#define SLIST_CLASS_HEAD(name, type) \ +struct name { \ + class type *slh_first; /* first element */ \ +} + +#define SLIST_HEAD_INITIALIZER(head) \ + { NULL } + +#define SLIST_ENTRY(type) \ +struct { \ + struct type *sle_next; /* next element */ \ +} + +#define SLIST_CLASS_ENTRY(type) \ +struct { \ + class type *sle_next; /* next element */ \ +} + +/* + * Singly-linked List functions. + */ +#define SLIST_EMPTY(head) ((head)->slh_first == NULL) + +#define SLIST_FIRST(head) ((head)->slh_first) + +#define SLIST_FOREACH(var, head, field) \ + for ((var) = SLIST_FIRST((head)); \ + (var); \ + (var) = SLIST_NEXT((var), field)) + +#define SLIST_FOREACH_FROM(var, head, field) \ + for ((var) = ((var) ? (var) : SLIST_FIRST((head))); \ + (var); \ + (var) = SLIST_NEXT((var), field)) + +#define SLIST_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = SLIST_FIRST((head)); \ + (var) && ((tvar) = SLIST_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define SLIST_FOREACH_FROM_SAFE(var, head, field, tvar) \ + for ((var) = ((var) ? (var) : SLIST_FIRST((head))); \ + (var) && ((tvar) = SLIST_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define SLIST_FOREACH_PREVPTR(var, varp, head, field) \ + for ((varp) = &SLIST_FIRST((head)); \ + ((var) = *(varp)) != NULL; \ + (varp) = &SLIST_NEXT((var), field)) + +#define SLIST_INIT(head) do { \ + SLIST_FIRST((head)) = NULL; \ +} while (0) + +#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ + SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field); \ + SLIST_NEXT((slistelm), field) = (elm); \ +} while (0) + +#define SLIST_INSERT_HEAD(head, elm, field) do { \ + SLIST_NEXT((elm), field) = SLIST_FIRST((head)); \ + SLIST_FIRST((head)) = (elm); \ +} while (0) + +#define SLIST_NEXT(elm, field) ((elm)->field.sle_next) + +#define SLIST_REMOVE(head, elm, type, field) do { \ + QMD_SAVELINK(oldnext, (elm)->field.sle_next); \ + if (SLIST_FIRST((head)) == (elm)) { \ + SLIST_REMOVE_HEAD((head), field); \ + } \ + else { \ + QUEUE_TYPEOF(type) *curelm = SLIST_FIRST(head); \ + while (SLIST_NEXT(curelm, field) != (elm)) \ + curelm = SLIST_NEXT(curelm, field); \ + SLIST_REMOVE_AFTER(curelm, field); \ + } \ + TRASHIT(*oldnext); \ +} while (0) + +#define SLIST_REMOVE_AFTER(elm, field) do { \ + SLIST_NEXT(elm, field) = \ + SLIST_NEXT(SLIST_NEXT(elm, field), field); \ +} while (0) + +#define SLIST_REMOVE_HEAD(head, field) do { \ + SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field); \ +} while (0) + +#define SLIST_SWAP(head1, head2, type) do { \ + QUEUE_TYPEOF(type) *swap_first = SLIST_FIRST(head1); \ + SLIST_FIRST(head1) = SLIST_FIRST(head2); \ + SLIST_FIRST(head2) = swap_first; \ +} while (0) + +/* + * Singly-linked Tail queue declarations. + */ +#define STAILQ_HEAD(name, type) \ +struct name { \ + struct type *stqh_first;/* first element */ \ + struct type **stqh_last;/* addr of last next element */ \ +} + +#define STAILQ_CLASS_HEAD(name, type) \ +struct name { \ + class type *stqh_first; /* first element */ \ + class type **stqh_last; /* addr of last next element */ \ +} + +#define STAILQ_HEAD_INITIALIZER(head) \ + { NULL, &(head).stqh_first } + +#define STAILQ_ENTRY(type) \ +struct { \ + struct type *stqe_next; /* next element */ \ +} + +#define STAILQ_CLASS_ENTRY(type) \ +struct { \ + class type *stqe_next; /* next element */ \ +} + +/* + * Singly-linked Tail queue functions. + */ +#define STAILQ_CONCAT(head1, head2) do { \ + if (!STAILQ_EMPTY((head2))) { \ + *(head1)->stqh_last = (head2)->stqh_first; \ + (head1)->stqh_last = (head2)->stqh_last; \ + STAILQ_INIT((head2)); \ + } \ +} while (0) + +#define STAILQ_EMPTY(head) ((head)->stqh_first == NULL) + +#define STAILQ_FIRST(head) ((head)->stqh_first) + +#define STAILQ_FOREACH(var, head, field) \ + for((var) = STAILQ_FIRST((head)); \ + (var); \ + (var) = STAILQ_NEXT((var), field)) + +#define STAILQ_FOREACH_FROM(var, head, field) \ + for ((var) = ((var) ? (var) : STAILQ_FIRST((head))); \ + (var); \ + (var) = STAILQ_NEXT((var), field)) + +#define STAILQ_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = STAILQ_FIRST((head)); \ + (var) && ((tvar) = STAILQ_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define STAILQ_FOREACH_FROM_SAFE(var, head, field, tvar) \ + for ((var) = ((var) ? (var) : STAILQ_FIRST((head))); \ + (var) && ((tvar) = STAILQ_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define STAILQ_INIT(head) do { \ + STAILQ_FIRST((head)) = NULL; \ + (head)->stqh_last = &STAILQ_FIRST((head)); \ +} while (0) + +#define STAILQ_INSERT_AFTER(head, tqelm, elm, field) do { \ + if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\ + (head)->stqh_last = &STAILQ_NEXT((elm), field); \ + STAILQ_NEXT((tqelm), field) = (elm); \ +} while (0) + +#define STAILQ_INSERT_HEAD(head, elm, field) do { \ + if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL) \ + (head)->stqh_last = &STAILQ_NEXT((elm), field); \ + STAILQ_FIRST((head)) = (elm); \ +} while (0) + +#define STAILQ_INSERT_TAIL(head, elm, field) do { \ + STAILQ_NEXT((elm), field) = NULL; \ + *(head)->stqh_last = (elm); \ + (head)->stqh_last = &STAILQ_NEXT((elm), field); \ +} while (0) + +#define STAILQ_LAST(head, type, field) \ + (STAILQ_EMPTY((head)) ? NULL : \ + __containerof((head)->stqh_last, \ + QUEUE_TYPEOF(type), field.stqe_next)) + +#define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next) + +#define STAILQ_REMOVE(head, elm, type, field) do { \ + QMD_SAVELINK(oldnext, (elm)->field.stqe_next); \ + if (STAILQ_FIRST((head)) == (elm)) { \ + STAILQ_REMOVE_HEAD((head), field); \ + } \ + else { \ + QUEUE_TYPEOF(type) *curelm = STAILQ_FIRST(head); \ + while (STAILQ_NEXT(curelm, field) != (elm)) \ + curelm = STAILQ_NEXT(curelm, field); \ + STAILQ_REMOVE_AFTER(head, curelm, field); \ + } \ + TRASHIT(*oldnext); \ +} while (0) + +#define STAILQ_REMOVE_AFTER(head, elm, field) do { \ + if ((STAILQ_NEXT(elm, field) = \ + STAILQ_NEXT(STAILQ_NEXT(elm, field), field)) == NULL) \ + (head)->stqh_last = &STAILQ_NEXT((elm), field); \ +} while (0) + +#define STAILQ_REMOVE_HEAD(head, field) do { \ + if ((STAILQ_FIRST((head)) = \ + STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL) \ + (head)->stqh_last = &STAILQ_FIRST((head)); \ +} while (0) + +#define STAILQ_SWAP(head1, head2, type) do { \ + QUEUE_TYPEOF(type) *swap_first = STAILQ_FIRST(head1); \ + QUEUE_TYPEOF(type) **swap_last = (head1)->stqh_last; \ + STAILQ_FIRST(head1) = STAILQ_FIRST(head2); \ + (head1)->stqh_last = (head2)->stqh_last; \ + STAILQ_FIRST(head2) = swap_first; \ + (head2)->stqh_last = swap_last; \ + if (STAILQ_EMPTY(head1)) \ + (head1)->stqh_last = &STAILQ_FIRST(head1); \ + if (STAILQ_EMPTY(head2)) \ + (head2)->stqh_last = &STAILQ_FIRST(head2); \ +} while (0) + + +/* + * List declarations. + */ +#define LIST_HEAD(name, type) \ +struct name { \ + struct type *lh_first; /* first element */ \ +} + +#define LIST_CLASS_HEAD(name, type) \ +struct name { \ + class type *lh_first; /* first element */ \ +} + +#define LIST_HEAD_INITIALIZER(head) \ + { NULL } + +#define LIST_ENTRY(type) \ +struct { \ + struct type *le_next; /* next element */ \ + struct type **le_prev; /* address of previous next element */ \ +} + +#define LIST_CLASS_ENTRY(type) \ +struct { \ + class type *le_next; /* next element */ \ + class type **le_prev; /* address of previous next element */ \ +} + +/* + * List functions. + */ + +#if (defined(_KERNEL) && defined(INVARIANTS)) +#define QMD_LIST_CHECK_HEAD(head, field) do { \ + if (LIST_FIRST((head)) != NULL && \ + LIST_FIRST((head))->field.le_prev != \ + &LIST_FIRST((head))) \ + panic("Bad list head %p first->prev != head", (head)); \ +} while (0) + +#define QMD_LIST_CHECK_NEXT(elm, field) do { \ + if (LIST_NEXT((elm), field) != NULL && \ + LIST_NEXT((elm), field)->field.le_prev != \ + &((elm)->field.le_next)) \ + panic("Bad link elm %p next->prev != elm", (elm)); \ +} while (0) + +#define QMD_LIST_CHECK_PREV(elm, field) do { \ + if (*(elm)->field.le_prev != (elm)) \ + panic("Bad link elm %p prev->next != elm", (elm)); \ +} while (0) +#else +#define QMD_LIST_CHECK_HEAD(head, field) +#define QMD_LIST_CHECK_NEXT(elm, field) +#define QMD_LIST_CHECK_PREV(elm, field) +#endif /* (_KERNEL && INVARIANTS) */ + +#define LIST_EMPTY(head) ((head)->lh_first == NULL) + +#define LIST_FIRST(head) ((head)->lh_first) + +#define LIST_FOREACH(var, head, field) \ + for ((var) = LIST_FIRST((head)); \ + (var); \ + (var) = LIST_NEXT((var), field)) + +#define LIST_FOREACH_FROM(var, head, field) \ + for ((var) = ((var) ? (var) : LIST_FIRST((head))); \ + (var); \ + (var) = LIST_NEXT((var), field)) + +#define LIST_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = LIST_FIRST((head)); \ + (var) && ((tvar) = LIST_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define LIST_FOREACH_FROM_SAFE(var, head, field, tvar) \ + for ((var) = ((var) ? (var) : LIST_FIRST((head))); \ + (var) && ((tvar) = LIST_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define LIST_INIT(head) do { \ + LIST_FIRST((head)) = NULL; \ +} while (0) + +#define LIST_INSERT_AFTER(listelm, elm, field) do { \ + QMD_LIST_CHECK_NEXT(listelm, field); \ + if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\ + LIST_NEXT((listelm), field)->field.le_prev = \ + &LIST_NEXT((elm), field); \ + LIST_NEXT((listelm), field) = (elm); \ + (elm)->field.le_prev = &LIST_NEXT((listelm), field); \ +} while (0) + +#define LIST_INSERT_BEFORE(listelm, elm, field) do { \ + QMD_LIST_CHECK_PREV(listelm, field); \ + (elm)->field.le_prev = (listelm)->field.le_prev; \ + LIST_NEXT((elm), field) = (listelm); \ + *(listelm)->field.le_prev = (elm); \ + (listelm)->field.le_prev = &LIST_NEXT((elm), field); \ +} while (0) + +#define LIST_INSERT_HEAD(head, elm, field) do { \ + QMD_LIST_CHECK_HEAD((head), field); \ + if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL) \ + LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\ + LIST_FIRST((head)) = (elm); \ + (elm)->field.le_prev = &LIST_FIRST((head)); \ +} while (0) + +#define LIST_NEXT(elm, field) ((elm)->field.le_next) + +#define LIST_PREV(elm, head, type, field) \ + ((elm)->field.le_prev == &LIST_FIRST((head)) ? NULL : \ + __containerof((elm)->field.le_prev, \ + QUEUE_TYPEOF(type), field.le_next)) + +#define LIST_REMOVE(elm, field) do { \ + QMD_SAVELINK(oldnext, (elm)->field.le_next); \ + QMD_SAVELINK(oldprev, (elm)->field.le_prev); \ + QMD_LIST_CHECK_NEXT(elm, field); \ + QMD_LIST_CHECK_PREV(elm, field); \ + if (LIST_NEXT((elm), field) != NULL) \ + LIST_NEXT((elm), field)->field.le_prev = \ + (elm)->field.le_prev; \ + *(elm)->field.le_prev = LIST_NEXT((elm), field); \ + TRASHIT(*oldnext); \ + TRASHIT(*oldprev); \ +} while (0) + +#define LIST_SWAP(head1, head2, type, field) do { \ + QUEUE_TYPEOF(type) *swap_tmp = LIST_FIRST(head1); \ + LIST_FIRST((head1)) = LIST_FIRST((head2)); \ + LIST_FIRST((head2)) = swap_tmp; \ + if ((swap_tmp = LIST_FIRST((head1))) != NULL) \ + swap_tmp->field.le_prev = &LIST_FIRST((head1)); \ + if ((swap_tmp = LIST_FIRST((head2))) != NULL) \ + swap_tmp->field.le_prev = &LIST_FIRST((head2)); \ +} while (0) + +/* + * Tail queue declarations. + */ +#define TAILQ_HEAD(name, type) \ +struct name { \ + struct type *tqh_first; /* first element */ \ + struct type **tqh_last; /* addr of last next element */ \ + TRACEBUF \ +} + +#define TAILQ_CLASS_HEAD(name, type) \ +struct name { \ + class type *tqh_first; /* first element */ \ + class type **tqh_last; /* addr of last next element */ \ + TRACEBUF \ +} + +#define TAILQ_HEAD_INITIALIZER(head) \ + { NULL, &(head).tqh_first, TRACEBUF_INITIALIZER } + +#define TAILQ_ENTRY(type) \ +struct { \ + struct type *tqe_next; /* next element */ \ + struct type **tqe_prev; /* address of previous next element */ \ + TRACEBUF \ +} + +#define TAILQ_CLASS_ENTRY(type) \ +struct { \ + class type *tqe_next; /* next element */ \ + class type **tqe_prev; /* address of previous next element */ \ + TRACEBUF \ +} + +/* + * Tail queue functions. + */ +#if (defined(_KERNEL) && defined(INVARIANTS)) +#define QMD_TAILQ_CHECK_HEAD(head, field) do { \ + if (!TAILQ_EMPTY(head) && \ + TAILQ_FIRST((head))->field.tqe_prev != \ + &TAILQ_FIRST((head))) \ + panic("Bad tailq head %p first->prev != head", (head)); \ +} while (0) + +#define QMD_TAILQ_CHECK_TAIL(head, field) do { \ + if (*(head)->tqh_last != NULL) \ + panic("Bad tailq NEXT(%p->tqh_last) != NULL", (head)); \ +} while (0) + +#define QMD_TAILQ_CHECK_NEXT(elm, field) do { \ + if (TAILQ_NEXT((elm), field) != NULL && \ + TAILQ_NEXT((elm), field)->field.tqe_prev != \ + &((elm)->field.tqe_next)) \ + panic("Bad link elm %p next->prev != elm", (elm)); \ +} while (0) + +#define QMD_TAILQ_CHECK_PREV(elm, field) do { \ + if (*(elm)->field.tqe_prev != (elm)) \ + panic("Bad link elm %p prev->next != elm", (elm)); \ +} while (0) +#else +#define QMD_TAILQ_CHECK_HEAD(head, field) +#define QMD_TAILQ_CHECK_TAIL(head, headname) +#define QMD_TAILQ_CHECK_NEXT(elm, field) +#define QMD_TAILQ_CHECK_PREV(elm, field) +#endif /* (_KERNEL && INVARIANTS) */ + +#define TAILQ_CONCAT(head1, head2, field) do { \ + if (!TAILQ_EMPTY(head2)) { \ + *(head1)->tqh_last = (head2)->tqh_first; \ + (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ + (head1)->tqh_last = (head2)->tqh_last; \ + TAILQ_INIT((head2)); \ + QMD_TRACE_HEAD(head1); \ + QMD_TRACE_HEAD(head2); \ + } \ +} while (0) + +#define TAILQ_EMPTY(head) ((head)->tqh_first == NULL) + +#define TAILQ_FIRST(head) ((head)->tqh_first) + +#define TAILQ_FOREACH(var, head, field) \ + for ((var) = TAILQ_FIRST((head)); \ + (var); \ + (var) = TAILQ_NEXT((var), field)) + +#define TAILQ_FOREACH_FROM(var, head, field) \ + for ((var) = ((var) ? (var) : TAILQ_FIRST((head))); \ + (var); \ + (var) = TAILQ_NEXT((var), field)) + +#define TAILQ_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = TAILQ_FIRST((head)); \ + (var) && ((tvar) = TAILQ_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define TAILQ_FOREACH_FROM_SAFE(var, head, field, tvar) \ + for ((var) = ((var) ? (var) : TAILQ_FIRST((head))); \ + (var) && ((tvar) = TAILQ_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ + for ((var) = TAILQ_LAST((head), headname); \ + (var); \ + (var) = TAILQ_PREV((var), headname, field)) + +#define TAILQ_FOREACH_REVERSE_FROM(var, head, headname, field) \ + for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname)); \ + (var); \ + (var) = TAILQ_PREV((var), headname, field)) + +#define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar) \ + for ((var) = TAILQ_LAST((head), headname); \ + (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1); \ + (var) = (tvar)) + +#define TAILQ_FOREACH_REVERSE_FROM_SAFE(var, head, headname, field, tvar) \ + for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname)); \ + (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1); \ + (var) = (tvar)) + +#define TAILQ_INIT(head) do { \ + TAILQ_FIRST((head)) = NULL; \ + (head)->tqh_last = &TAILQ_FIRST((head)); \ + QMD_TRACE_HEAD(head); \ +} while (0) + +#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ + QMD_TAILQ_CHECK_NEXT(listelm, field); \ + if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\ + TAILQ_NEXT((elm), field)->field.tqe_prev = \ + &TAILQ_NEXT((elm), field); \ + else { \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + QMD_TRACE_HEAD(head); \ + } \ + TAILQ_NEXT((listelm), field) = (elm); \ + (elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field); \ + QMD_TRACE_ELEM(&(elm)->field); \ + QMD_TRACE_ELEM(&(listelm)->field); \ +} while (0) + +#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ + QMD_TAILQ_CHECK_PREV(listelm, field); \ + (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ + TAILQ_NEXT((elm), field) = (listelm); \ + *(listelm)->field.tqe_prev = (elm); \ + (listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field); \ + QMD_TRACE_ELEM(&(elm)->field); \ + QMD_TRACE_ELEM(&(listelm)->field); \ +} while (0) + +#define TAILQ_INSERT_HEAD(head, elm, field) do { \ + QMD_TAILQ_CHECK_HEAD(head, field); \ + if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL) \ + TAILQ_FIRST((head))->field.tqe_prev = \ + &TAILQ_NEXT((elm), field); \ + else \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + TAILQ_FIRST((head)) = (elm); \ + (elm)->field.tqe_prev = &TAILQ_FIRST((head)); \ + QMD_TRACE_HEAD(head); \ + QMD_TRACE_ELEM(&(elm)->field); \ +} while (0) + +#define TAILQ_INSERT_TAIL(head, elm, field) do { \ + QMD_TAILQ_CHECK_TAIL(head, field); \ + TAILQ_NEXT((elm), field) = NULL; \ + (elm)->field.tqe_prev = (head)->tqh_last; \ + *(head)->tqh_last = (elm); \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + QMD_TRACE_HEAD(head); \ + QMD_TRACE_ELEM(&(elm)->field); \ +} while (0) + +#define TAILQ_LAST(head, headname) \ + (*(((struct headname *)((head)->tqh_last))->tqh_last)) + +#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) + +#define TAILQ_PREV(elm, headname, field) \ + (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) + +#define TAILQ_REMOVE(head, elm, field) do { \ + QMD_SAVELINK(oldnext, (elm)->field.tqe_next); \ + QMD_SAVELINK(oldprev, (elm)->field.tqe_prev); \ + QMD_TAILQ_CHECK_NEXT(elm, field); \ + QMD_TAILQ_CHECK_PREV(elm, field); \ + if ((TAILQ_NEXT((elm), field)) != NULL) \ + TAILQ_NEXT((elm), field)->field.tqe_prev = \ + (elm)->field.tqe_prev; \ + else { \ + (head)->tqh_last = (elm)->field.tqe_prev; \ + QMD_TRACE_HEAD(head); \ + } \ + *(elm)->field.tqe_prev = TAILQ_NEXT((elm), field); \ + TRASHIT(*oldnext); \ + TRASHIT(*oldprev); \ + QMD_TRACE_ELEM(&(elm)->field); \ +} while (0) + +#define TAILQ_SWAP(head1, head2, type, field) do { \ + QUEUE_TYPEOF(type) *swap_first = (head1)->tqh_first; \ + QUEUE_TYPEOF(type) **swap_last = (head1)->tqh_last; \ + (head1)->tqh_first = (head2)->tqh_first; \ + (head1)->tqh_last = (head2)->tqh_last; \ + (head2)->tqh_first = swap_first; \ + (head2)->tqh_last = swap_last; \ + if ((swap_first = (head1)->tqh_first) != NULL) \ + swap_first->field.tqe_prev = &(head1)->tqh_first; \ + else \ + (head1)->tqh_last = &(head1)->tqh_first; \ + if ((swap_first = (head2)->tqh_first) != NULL) \ + swap_first->field.tqe_prev = &(head2)->tqh_first; \ + else \ + (head2)->tqh_last = &(head2)->tqh_first; \ +} while (0) + +#endif /* !_SYS_QUEUE_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_features.h" +#endif +/* + * Copyright (c) 2014-2016 Cesanta Software Limited + * All rights reserved + */ + +#ifndef CS_MONGOOSE_SRC_FEATURES_H_ +#define CS_MONGOOSE_SRC_FEATURES_H_ + +#ifndef MG_DISABLE_HTTP_DIGEST_AUTH +#define MG_DISABLE_HTTP_DIGEST_AUTH 0 +#endif + +#ifndef MG_DISABLE_HTTP_KEEP_ALIVE +#define MG_DISABLE_HTTP_KEEP_ALIVE 0 +#endif + +#ifndef MG_DISABLE_PFS +#define MG_DISABLE_PFS 0 +#endif + +#ifndef MG_DISABLE_WS_RANDOM_MASK +#define MG_DISABLE_WS_RANDOM_MASK 0 +#endif + +#ifndef MG_ENABLE_ASYNC_RESOLVER +#define MG_ENABLE_ASYNC_RESOLVER 1 +#endif + +#ifndef MG_ENABLE_BROADCAST +#define MG_ENABLE_BROADCAST 0 +#endif + +#ifndef MG_ENABLE_COAP +#define MG_ENABLE_COAP 0 +#endif + +#ifndef MG_ENABLE_DEBUG +#define MG_ENABLE_DEBUG 0 +#endif + +#ifndef MG_ENABLE_DIRECTORY_LISTING +#define MG_ENABLE_DIRECTORY_LISTING 0 +#endif + +#ifndef MG_ENABLE_DNS +#define MG_ENABLE_DNS 1 +#endif + +#ifndef MG_ENABLE_DNS_SERVER +#define MG_ENABLE_DNS_SERVER 0 +#endif + +#ifndef MG_ENABLE_FAKE_DAVLOCK +#define MG_ENABLE_FAKE_DAVLOCK 0 +#endif + +#ifndef MG_ENABLE_FILESYSTEM +#define MG_ENABLE_FILESYSTEM 0 +#endif + +#ifndef MG_ENABLE_GETADDRINFO +#define MG_ENABLE_GETADDRINFO 0 +#endif + +#ifndef MG_ENABLE_HEXDUMP +#define MG_ENABLE_HEXDUMP CS_ENABLE_STDIO +#endif + +#ifndef MG_ENABLE_HTTP +#define MG_ENABLE_HTTP 1 +#endif + +#ifndef MG_ENABLE_HTTP_CGI +#define MG_ENABLE_HTTP_CGI 0 +#endif + +#ifndef MG_ENABLE_HTTP_SSI +#define MG_ENABLE_HTTP_SSI MG_ENABLE_FILESYSTEM +#endif + +#ifndef MG_ENABLE_HTTP_SSI_EXEC +#define MG_ENABLE_HTTP_SSI_EXEC 0 +#endif + +#ifndef MG_ENABLE_HTTP_STREAMING_MULTIPART +#define MG_ENABLE_HTTP_STREAMING_MULTIPART 0 +#endif + +#ifndef MG_ENABLE_HTTP_WEBDAV +#define MG_ENABLE_HTTP_WEBDAV 0 +#endif + +#ifndef MG_ENABLE_HTTP_WEBSOCKET +#define MG_ENABLE_HTTP_WEBSOCKET MG_ENABLE_HTTP +#endif + +#ifndef MG_ENABLE_IPV6 +#define MG_ENABLE_IPV6 0 +#endif + +#ifndef MG_ENABLE_MQTT +#define MG_ENABLE_MQTT 1 +#endif + +#ifndef MG_ENABLE_SOCKS +#define MG_ENABLE_SOCKS 0 +#endif + +#ifndef MG_ENABLE_MQTT_BROKER +#define MG_ENABLE_MQTT_BROKER 0 +#endif + +#ifndef MG_ENABLE_SSL +#define MG_ENABLE_SSL 0 +#endif + +#ifndef MG_ENABLE_SYNC_RESOLVER +#define MG_ENABLE_SYNC_RESOLVER 0 +#endif + +#ifndef MG_ENABLE_STDIO +#define MG_ENABLE_STDIO CS_ENABLE_STDIO +#endif + +#ifndef MG_NET_IF +#define MG_NET_IF MG_NET_IF_SOCKET +#endif + +#ifndef MG_SSL_IF +#define MG_SSL_IF MG_SSL_IF_OPENSSL +#endif + +#ifndef MG_ENABLE_THREADS /* ifdef-ok */ +#ifdef _WIN32 +#define MG_ENABLE_THREADS 1 +#else +#define MG_ENABLE_THREADS 0 +#endif +#endif + +#if MG_ENABLE_DEBUG && !defined(CS_ENABLE_DEBUG) +#define CS_ENABLE_DEBUG 1 +#endif + +/* MQTT broker requires MQTT */ +#if MG_ENABLE_MQTT_BROKER && !MG_ENABLE_MQTT +#undef MG_ENABLE_MQTT +#define MG_ENABLE_MQTT 1 +#endif + +#ifndef MG_ENABLE_HTTP_URL_REWRITES +#define MG_ENABLE_HTTP_URL_REWRITES \ + (CS_PLATFORM == CS_P_WINDOWS || CS_PLATFORM == CS_P_UNIX) +#endif + +#ifndef MG_ENABLE_SNTP +#define MG_ENABLE_SNTP 0 +#endif + +#ifndef MG_ENABLE_EXTRA_ERRORS_DESC +#define MG_ENABLE_EXTRA_ERRORS_DESC 0 +#endif + +#ifndef MG_ENABLE_CALLBACK_USERDATA +#define MG_ENABLE_CALLBACK_USERDATA 0 +#endif + +#if MG_ENABLE_CALLBACK_USERDATA +#define MG_UD_ARG(ud) , ud +#define MG_CB(cb, ud) cb, ud +#else +#define MG_UD_ARG(ud) +#define MG_CB(cb, ud) cb +#endif + +#endif /* CS_MONGOOSE_SRC_FEATURES_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_net_if.h" +#endif +/* + * Copyright (c) 2014-2016 Cesanta Software Limited + * All rights reserved + */ + +#ifndef CS_MONGOOSE_SRC_NET_IF_H_ +#define CS_MONGOOSE_SRC_NET_IF_H_ + +/* Amalgamated: #include "common/platform.h" */ + +/* + * Internal async networking core interface. + * Consists of calls made by the core, which should not block, + * and callbacks back into the core ("..._cb"). + * Callbacks may (will) cause methods to be invoked from within, + * but methods are not allowed to invoke callbacks inline. + * + * Implementation must ensure that only one callback is invoked at any time. + */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#define MG_MAIN_IFACE 0 + +struct mg_mgr; +struct mg_connection; +union socket_address; + +struct mg_iface_vtable; + +struct mg_iface { + struct mg_mgr *mgr; + void *data; /* Implementation-specific data */ + const struct mg_iface_vtable *vtable; +}; + +struct mg_iface_vtable { + void (*init)(struct mg_iface *iface); + void (*free)(struct mg_iface *iface); + void (*add_conn)(struct mg_connection *nc); + void (*remove_conn)(struct mg_connection *nc); + time_t (*poll)(struct mg_iface *iface, int timeout_ms); + + /* Set up a listening TCP socket on a given address. rv = 0 -> ok. */ + int (*listen_tcp)(struct mg_connection *nc, union socket_address *sa); + /* Request that a "listening" UDP socket be created. */ + int (*listen_udp)(struct mg_connection *nc, union socket_address *sa); + + /* Request that a TCP connection is made to the specified address. */ + void (*connect_tcp)(struct mg_connection *nc, const union socket_address *sa); + /* Open a UDP socket. Doesn't actually connect anything. */ + void (*connect_udp)(struct mg_connection *nc); + + /* Send functions for TCP and UDP. Sent data is copied before return. */ + int (*tcp_send)(struct mg_connection *nc, const void *buf, size_t len); + int (*udp_send)(struct mg_connection *nc, const void *buf, size_t len); + + int (*tcp_recv)(struct mg_connection *nc, void *buf, size_t len); + int (*udp_recv)(struct mg_connection *nc, void *buf, size_t len, + union socket_address *sa, size_t *sa_len); + + /* Perform interface-related connection initialization. Return 1 on ok. */ + int (*create_conn)(struct mg_connection *nc); + /* Perform interface-related cleanup on connection before destruction. */ + void (*destroy_conn)(struct mg_connection *nc); + + /* Associate a socket to a connection. */ + void (*sock_set)(struct mg_connection *nc, sock_t sock); + + /* Put connection's address into *sa, local (remote = 0) or remote. */ + void (*get_conn_addr)(struct mg_connection *nc, int remote, + union socket_address *sa); +}; + +extern const struct mg_iface_vtable *mg_ifaces[]; +extern int mg_num_ifaces; + +/* Creates a new interface instance. */ +struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable, + struct mg_mgr *mgr); + +/* + * Find an interface with a given implementation. The search is started from + * interface `from`, exclusive. Returns NULL if none is found. + */ +struct mg_iface *mg_find_iface(struct mg_mgr *mgr, + const struct mg_iface_vtable *vtable, + struct mg_iface *from); +/* + * Deliver a new TCP connection. Returns NULL in case on error (unable to + * create connection, in which case interface state should be discarded. + * This is phase 1 of the two-phase process - MG_EV_ACCEPT will be delivered + * when mg_if_accept_tcp_cb is invoked. + */ +struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc); +void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa, + size_t sa_len); + +/* Callback invoked by connect methods. err = 0 -> ok, != 0 -> error. */ +void mg_if_connect_cb(struct mg_connection *nc, int err); +/* + * Callback that tells the core that data can be received. + * Core will use tcp/udp_recv to retrieve the data. + */ +void mg_if_can_recv_cb(struct mg_connection *nc); +void mg_if_can_send_cb(struct mg_connection *nc); +/* + * Receive callback. + * buf must be heap-allocated and ownership is transferred to the core. + */ +void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len, + union socket_address *sa, size_t sa_len); + +/* void mg_if_close_conn(struct mg_connection *nc); */ + +/* Deliver a POLL event to the connection. */ +int mg_if_poll(struct mg_connection *nc, double now); + +/* + * Return minimal timer value amoung connections in the manager. + * Returns 0 if there aren't any timers. + */ +double mg_mgr_min_timer(const struct mg_mgr *mgr); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* CS_MONGOOSE_SRC_NET_IF_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_ssl_if.h" +#endif +/* + * Copyright (c) 2014-2016 Cesanta Software Limited + * All rights reserved + */ + +#ifndef CS_MONGOOSE_SRC_SSL_IF_H_ +#define CS_MONGOOSE_SRC_SSL_IF_H_ + +#if MG_ENABLE_SSL + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +struct mg_ssl_if_ctx; +struct mg_connection; + +void mg_ssl_if_init(); + +enum mg_ssl_if_result { + MG_SSL_OK = 0, + MG_SSL_WANT_READ = -1, + MG_SSL_WANT_WRITE = -2, + MG_SSL_ERROR = -3, +}; + +struct mg_ssl_if_conn_params { + const char *cert; + const char *key; + const char *ca_cert; + const char *server_name; + const char *cipher_suites; + const char *psk_identity; + const char *psk_key; +}; + +enum mg_ssl_if_result mg_ssl_if_conn_init( + struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, + const char **err_msg); +enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, + struct mg_connection *lc); +void mg_ssl_if_conn_close_notify(struct mg_connection *nc); +void mg_ssl_if_conn_free(struct mg_connection *nc); + +enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc); +int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size); +int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* MG_ENABLE_SSL */ + +#endif /* CS_MONGOOSE_SRC_SSL_IF_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_net.h" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + * This software is dual-licensed: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. For the terms of this + * license, see . + * + * You are free to use this software under the terms of the GNU General + * Public License, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * Alternatively, you can license this software under a commercial + * license, as set out in . + */ + +/* + * === Core API: TCP/UDP/SSL + * + * NOTE: Mongoose manager is single threaded. It does not protect + * its data structures by mutexes, therefore all functions that are dealing + * with a particular event manager should be called from the same thread, + * with exception of the `mg_broadcast()` function. It is fine to have different + * event managers handled by different threads. + */ + +#ifndef CS_MONGOOSE_SRC_NET_H_ +#define CS_MONGOOSE_SRC_NET_H_ + +/* Amalgamated: #include "mg_common.h" */ +/* Amalgamated: #include "mg_net_if.h" */ +/* Amalgamated: #include "common/mbuf.h" */ + +#ifndef MG_VPRINTF_BUFFER_SIZE +#define MG_VPRINTF_BUFFER_SIZE 100 +#endif + +#ifdef MG_USE_READ_WRITE +#define MG_RECV_FUNC(s, b, l, f) read(s, b, l) +#define MG_SEND_FUNC(s, b, l, f) write(s, b, l) +#else +#define MG_RECV_FUNC(s, b, l, f) recv(s, b, l, f) +#define MG_SEND_FUNC(s, b, l, f) send(s, b, l, f) +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +union socket_address { + struct sockaddr sa; + struct sockaddr_in sin; +#if MG_ENABLE_IPV6 + struct sockaddr_in6 sin6; +#else + struct sockaddr sin6; +#endif +}; + +struct mg_connection; + +/* + * Callback function (event handler) prototype. Must be defined by the user. + * Mongoose calls the event handler, passing the events defined below. + */ +typedef void (*mg_event_handler_t)(struct mg_connection *nc, int ev, + void *ev_data MG_UD_ARG(void *user_data)); + +/* Events. Meaning of event parameter (evp) is given in the comment. */ +#define MG_EV_POLL 0 /* Sent to each connection on each mg_mgr_poll() call */ +#define MG_EV_ACCEPT 1 /* New connection accepted. union socket_address * */ +#define MG_EV_CONNECT 2 /* connect() succeeded or failed. int * */ +#define MG_EV_RECV 3 /* Data has been received. int *num_bytes */ +#define MG_EV_SEND 4 /* Data has been written to a socket. int *num_bytes */ +#define MG_EV_CLOSE 5 /* Connection is closed. NULL */ +#define MG_EV_TIMER 6 /* now >= conn->ev_timer_time. double * */ + +/* + * Mongoose event manager. + */ +struct mg_mgr { + struct mg_connection *active_connections; +#if MG_ENABLE_HEXDUMP + const char *hexdump_file; /* Debug hexdump file path */ +#endif +#if MG_ENABLE_BROADCAST + sock_t ctl[2]; /* Socketpair for mg_broadcast() */ +#endif + void *user_data; /* User data */ + int num_ifaces; + int num_calls; + struct mg_iface **ifaces; /* network interfaces */ + const char *nameserver; /* DNS server to use */ +}; + +/* + * Mongoose connection. + */ +struct mg_connection { + struct mg_connection *next, *prev; /* mg_mgr::active_connections linkage */ + struct mg_connection *listener; /* Set only for accept()-ed connections */ + struct mg_mgr *mgr; /* Pointer to containing manager */ + + sock_t sock; /* Socket to the remote peer */ + int err; + union socket_address sa; /* Remote peer address */ + size_t recv_mbuf_limit; /* Max size of recv buffer */ + struct mbuf recv_mbuf; /* Received data */ + struct mbuf send_mbuf; /* Data scheduled for sending */ + time_t last_io_time; /* Timestamp of the last socket IO */ + double ev_timer_time; /* Timestamp of the future MG_EV_TIMER */ +#if MG_ENABLE_SSL + void *ssl_if_data; /* SSL library data. */ +#endif + mg_event_handler_t proto_handler; /* Protocol-specific event handler */ + void *proto_data; /* Protocol-specific data */ + void (*proto_data_destructor)(void *proto_data); + mg_event_handler_t handler; /* Event handler function */ + void *user_data; /* User-specific data */ + union { + void *v; + /* + * the C standard is fussy about fitting function pointers into + * void pointers, since some archs might have fat pointers for functions. + */ + mg_event_handler_t f; + } priv_1; + void *priv_2; + void *mgr_data; /* Implementation-specific event manager's data. */ + struct mg_iface *iface; + unsigned long flags; +/* Flags set by Mongoose */ +#define MG_F_LISTENING (1 << 0) /* This connection is listening */ +#define MG_F_UDP (1 << 1) /* This connection is UDP */ +#define MG_F_RESOLVING (1 << 2) /* Waiting for async resolver */ +#define MG_F_CONNECTING (1 << 3) /* connect() call in progress */ +#define MG_F_SSL (1 << 4) /* SSL is enabled on the connection */ +#define MG_F_SSL_HANDSHAKE_DONE (1 << 5) /* SSL hanshake has completed */ +#define MG_F_WANT_READ (1 << 6) /* SSL specific */ +#define MG_F_WANT_WRITE (1 << 7) /* SSL specific */ +#define MG_F_IS_WEBSOCKET (1 << 8) /* Websocket specific */ +#define MG_F_RECV_AND_CLOSE (1 << 9) /* Drain rx and close the connection. */ + +/* Flags that are settable by user */ +#define MG_F_SEND_AND_CLOSE (1 << 10) /* Push remaining data and close */ +#define MG_F_CLOSE_IMMEDIATELY (1 << 11) /* Disconnect */ +#define MG_F_WEBSOCKET_NO_DEFRAG (1 << 12) /* Websocket specific */ +#define MG_F_DELETE_CHUNK (1 << 13) /* HTTP specific */ +#define MG_F_ENABLE_BROADCAST (1 << 14) /* Allow broadcast address usage */ + +#define MG_F_USER_1 (1 << 20) /* Flags left for application */ +#define MG_F_USER_2 (1 << 21) +#define MG_F_USER_3 (1 << 22) +#define MG_F_USER_4 (1 << 23) +#define MG_F_USER_5 (1 << 24) +#define MG_F_USER_6 (1 << 25) +}; + +/* + * Initialise Mongoose manager. Side effect: ignores SIGPIPE signal. + * `mgr->user_data` field will be initialised with a `user_data` parameter. + * That is an arbitrary pointer, where the user code can associate some data + * with the particular Mongoose manager. For example, a C++ wrapper class + * could be written in which case `user_data` can hold a pointer to the + * class instance. + */ +void mg_mgr_init(struct mg_mgr *mgr, void *user_data); + +/* + * Optional parameters to `mg_mgr_init_opt()`. + * + * If `main_iface` is not NULL, it will be used as the main interface in the + * default interface set. The pointer will be free'd by `mg_mgr_free`. + * Otherwise, the main interface will be autodetected based on the current + * platform. + * + * If `num_ifaces` is 0 and `ifaces` is NULL, the default interface set will be + * used. + * This is an advanced option, as it requires you to construct a full interface + * set, including special networking interfaces required by some optional + * features such as TCP tunneling. Memory backing `ifaces` and each of the + * `num_ifaces` pointers it contains will be reclaimed by `mg_mgr_free`. + */ +struct mg_mgr_init_opts { + const struct mg_iface_vtable *main_iface; + int num_ifaces; + const struct mg_iface_vtable **ifaces; + const char *nameserver; +}; + +/* + * Like `mg_mgr_init` but with more options. + * + * Notably, this allows you to create a manger and choose + * dynamically which networking interface implementation to use. + */ +void mg_mgr_init_opt(struct mg_mgr *mgr, void *user_data, + struct mg_mgr_init_opts opts); + +/* + * De-initialises Mongoose manager. + * + * Closes and deallocates all active connections. + */ +void mg_mgr_free(struct mg_mgr *mgr); + +/* + * This function performs the actual IO and must be called in a loop + * (an event loop). It returns number of user events generated (except POLLs). + * `milli` is the maximum number of milliseconds to sleep. + * `mg_mgr_poll()` checks all connections for IO readiness. If at least one + * of the connections is IO-ready, `mg_mgr_poll()` triggers the respective + * event handlers and returns. + */ +int mg_mgr_poll(struct mg_mgr *mgr, int milli); + +#if MG_ENABLE_BROADCAST +/* + * Passes a message of a given length to all connections. + * + * Must be called from a thread that does NOT call `mg_mgr_poll()`. + * Note that `mg_broadcast()` is the only function + * that can be, and must be, called from a different (non-IO) thread. + * + * `func` callback function will be called by the IO thread for each + * connection. When called, the event will be `MG_EV_POLL`, and a message will + * be passed as the `ev_data` pointer. Maximum message size is capped + * by `MG_CTL_MSG_MESSAGE_SIZE` which is set to 8192 bytes by default. + */ +void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data, + size_t len); +#endif + +/* + * Iterates over all active connections. + * + * Returns the next connection from the list + * of active connections or `NULL` if there are no more connections. Below + * is the iteration idiom: + * + * ```c + * for (c = mg_next(srv, NULL); c != NULL; c = mg_next(srv, c)) { + * // Do something with connection `c` + * } + * ``` + */ +struct mg_connection *mg_next(struct mg_mgr *mgr, struct mg_connection *c); + +/* + * Optional parameters to `mg_add_sock_opt()`. + * + * `flags` is an initial `struct mg_connection::flags` bitmask to set, + * see `MG_F_*` flags definitions. + */ +struct mg_add_sock_opts { + void *user_data; /* Initial value for connection's user_data */ + unsigned int flags; /* Initial connection flags */ + const char **error_string; /* Placeholder for the error string */ + struct mg_iface *iface; /* Interface instance */ +}; + +/* + * Creates a connection, associates it with the given socket and event handler + * and adds it to the manager. + * + * For more options see the `mg_add_sock_opt` variant. + */ +struct mg_connection *mg_add_sock(struct mg_mgr *mgr, sock_t sock, + MG_CB(mg_event_handler_t handler, + void *user_data)); + +/* + * Creates a connection, associates it with the given socket and event handler + * and adds to the manager. + * + * See the `mg_add_sock_opts` structure for a description of the options. + */ +struct mg_connection *mg_add_sock_opt(struct mg_mgr *mgr, sock_t sock, + MG_CB(mg_event_handler_t handler, + void *user_data), + struct mg_add_sock_opts opts); + +/* + * Optional parameters to `mg_bind_opt()`. + * + * `flags` is an initial `struct mg_connection::flags` bitmask to set, + * see `MG_F_*` flags definitions. + */ +struct mg_bind_opts { + void *user_data; /* Initial value for connection's user_data */ + unsigned int flags; /* Extra connection flags */ + const char **error_string; /* Placeholder for the error string */ + struct mg_iface *iface; /* Interface instance */ +#if MG_ENABLE_SSL + /* + * SSL settings. + * + * Server certificate to present to clients or client certificate to + * present to tunnel dispatcher (for tunneled connections). + */ + const char *ssl_cert; + /* Private key corresponding to the certificate. If ssl_cert is set but + * ssl_key is not, ssl_cert is used. */ + const char *ssl_key; + /* CA bundle used to verify client certificates or tunnel dispatchers. */ + const char *ssl_ca_cert; + /* Colon-delimited list of acceptable cipher suites. + * Names depend on the library used, for example: + * + * ECDH-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256 (OpenSSL) + * TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256 + * (mbedTLS) + * + * For OpenSSL the list can be obtained by running "openssl ciphers". + * For mbedTLS, names can be found in library/ssl_ciphersuites.c + * If NULL, a reasonable default is used. + */ + const char *ssl_cipher_suites; +#endif +}; + +/* + * Creates a listening connection. + * + * See `mg_bind_opt` for full documentation. + */ +struct mg_connection *mg_bind(struct mg_mgr *mgr, const char *address, + MG_CB(mg_event_handler_t handler, + void *user_data)); +/* + * Creates a listening connection. + * + * The `address` parameter specifies which address to bind to. It's format is + * the same as for the `mg_connect()` call, where `HOST` part is optional. + * `address` can be just a port number, e.g. `:8000`. To bind to a specific + * interface, an IP address can be specified, e.g. `1.2.3.4:8000`. By default, + * a TCP connection is created. To create UDP connection, prepend `udp://` + * prefix, e.g. `udp://:8000`. To summarize, `address` parameter has following + * format: `[PROTO://][IP_ADDRESS]:PORT`, where `PROTO` could be `tcp` or + * `udp`. + * + * See the `mg_bind_opts` structure for a description of the optional + * parameters. + * + * Returns a new listening connection or `NULL` on error. + * NOTE: The connection remains owned by the manager, do not free(). + */ +struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address, + MG_CB(mg_event_handler_t handler, + void *user_data), + struct mg_bind_opts opts); + +/* Optional parameters to `mg_connect_opt()` */ +struct mg_connect_opts { + void *user_data; /* Initial value for connection's user_data */ + unsigned int flags; /* Extra connection flags */ + const char **error_string; /* Placeholder for the error string */ + struct mg_iface *iface; /* Interface instance */ + const char *nameserver; /* DNS server to use, NULL for default */ +#if MG_ENABLE_SSL + /* + * SSL settings. + * Client certificate to present to the server. + */ + const char *ssl_cert; + /* + * Private key corresponding to the certificate. + * If ssl_cert is set but ssl_key is not, ssl_cert is used. + */ + const char *ssl_key; + /* + * Verify server certificate using this CA bundle. If set to "*", then SSL + * is enabled but no cert verification is performed. + */ + const char *ssl_ca_cert; + /* Colon-delimited list of acceptable cipher suites. + * Names depend on the library used, for example: + * + * ECDH-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256 (OpenSSL) + * TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256 + * (mbedTLS) + * + * For OpenSSL the list can be obtained by running "openssl ciphers". + * For mbedTLS, names can be found in library/ssl_ciphersuites.c + * If NULL, a reasonable default is used. + */ + const char *ssl_cipher_suites; + /* + * Server name verification. If ssl_ca_cert is set and the certificate has + * passed verification, its subject will be verified against this string. + * By default (if ssl_server_name is NULL) hostname part of the address will + * be used. Wildcard matching is supported. A special value of "*" disables + * name verification. + */ + const char *ssl_server_name; + /* + * PSK identity and key. Identity is a NUL-terminated string and key is a hex + * string. Key must be either 16 or 32 bytes (32 or 64 hex digits) for AES-128 + * or AES-256 respectively. + * Note: Default list of cipher suites does not include PSK suites, if you + * want to use PSK you will need to set ssl_cipher_suites as well. + */ + const char *ssl_psk_identity; + const char *ssl_psk_key; +#endif +}; + +/* + * Connects to a remote host. + * + * See `mg_connect_opt()` for full documentation. + */ +struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address, + MG_CB(mg_event_handler_t handler, + void *user_data)); + +/* + * Connects to a remote host. + * + * The `address` format is `[PROTO://]HOST:PORT`. `PROTO` could be `tcp` or + * `udp`. `HOST` could be an IP address, + * IPv6 address (if Mongoose is compiled with `-DMG_ENABLE_IPV6`) or a host + * name. If `HOST` is a name, Mongoose will resolve it asynchronously. Examples + * of valid addresses: `google.com:80`, `udp://1.2.3.4:53`, `10.0.0.1:443`, + * `[::1]:80` + * + * See the `mg_connect_opts` structure for a description of the optional + * parameters. + * + * Returns a new outbound connection or `NULL` on error. + * + * NOTE: The connection remains owned by the manager, do not free(). + * + * NOTE: To enable IPv6 addresses `-DMG_ENABLE_IPV6` should be specified + * in the compilation flags. + * + * NOTE: The new connection will receive `MG_EV_CONNECT` as its first event + * which will report the connect success status. + * If the asynchronous resolution fails or the `connect()` syscall fails for + * whatever reason (e.g. with `ECONNREFUSED` or `ENETUNREACH`), then + * `MG_EV_CONNECT` event will report failure. Code example below: + * + * ```c + * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { + * int connect_status; + * + * switch (ev) { + * case MG_EV_CONNECT: + * connect_status = * (int *) ev_data; + * if (connect_status == 0) { + * // Success + * } else { + * // Error + * printf("connect() error: %s\n", strerror(connect_status)); + * } + * break; + * ... + * } + * } + * + * ... + * mg_connect(mgr, "my_site.com:80", ev_handler); + * ``` + */ +struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address, + MG_CB(mg_event_handler_t handler, + void *user_data), + struct mg_connect_opts opts); + +#if MG_ENABLE_SSL && MG_NET_IF != MG_NET_IF_SIMPLELINK +/* + * Note: This function is deprecated. Please, use SSL options in + * mg_connect_opt. + * + * Enables SSL for a given connection. + * `cert` is a server certificate file name for a listening connection + * or a client certificate file name for an outgoing connection. + * The certificate files must be in PEM format. The server certificate file + * must contain a certificate, concatenated with a private key, optionally + * concatenated with DH parameters. + * `ca_cert` is a CA certificate or NULL if peer verification is not + * required. + * Return: NULL on success or error message on error. + */ +const char *mg_set_ssl(struct mg_connection *nc, const char *cert, + const char *ca_cert); +#endif + +/* + * Sends data to the connection. + * + * Note that sending functions do not actually push data to the socket. + * They just append data to the output buffer. MG_EV_SEND will be delivered when + * the data has actually been pushed out. + */ +void mg_send(struct mg_connection *, const void *buf, int len); + +/* Enables format string warnings for mg_printf */ +#if defined(__GNUC__) +__attribute__((format(printf, 2, 3))) +#endif +/* don't separate from mg_printf declaration */ + +/* + * Sends `printf`-style formatted data to the connection. + * + * See `mg_send` for more details on send semantics. + */ +int mg_printf(struct mg_connection *, const char *fmt, ...); + +/* Same as `mg_printf()`, but takes `va_list ap` as an argument. */ +int mg_vprintf(struct mg_connection *, const char *fmt, va_list ap); + +/* + * Creates a socket pair. + * `sock_type` can be either `SOCK_STREAM` or `SOCK_DGRAM`. + * Returns 0 on failure and 1 on success. + */ +int mg_socketpair(sock_t[2], int sock_type); + +#if MG_ENABLE_SYNC_RESOLVER +/* + * Convert domain name into IP address. + * + * This is a utility function. If compilation flags have + * `-DMG_ENABLE_GETADDRINFO`, then `getaddrinfo()` call is used for name + * resolution. Otherwise, `gethostbyname()` is used. + * + * CAUTION: this function can block. + * Return 1 on success, 0 on failure. + */ +int mg_resolve(const char *domain_name, char *ip_addr_buf, size_t buf_len); +#endif + +/* + * Verify given IP address against the ACL. + * + * `remote_ip` - an IPv4 address to check, in host byte order + * `acl` - a comma separated list of IP subnets: `x.x.x.x/x` or `x.x.x.x`. + * Each subnet is + * prepended by either a - or a + sign. A plus sign means allow, where a + * minus sign means deny. If a subnet mask is omitted, such as `-1.2.3.4`, + * it means that only that single IP address is denied. + * Subnet masks may vary from 0 to 32, inclusive. The default setting + * is to allow all access. On each request the full list is traversed, + * and the last match wins. Example: + * + * `-0.0.0.0/0,+192.168/16` - deny all accesses, only allow 192.168/16 subnet + * + * To learn more about subnet masks, see this + * link:https://en.wikipedia.org/wiki/Subnetwork[Wikipedia page on Subnetwork]. + * + * Returns -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. + */ +int mg_check_ip_acl(const char *acl, uint32_t remote_ip); + +/* + * Schedules an MG_EV_TIMER event to be delivered at `timestamp` time. + * `timestamp` is UNIX time (the number of seconds since Epoch). It is + * `double` instead of `time_t` to allow for sub-second precision. + * Returns the old timer value. + * + * Example: set the connect timeout to 1.5 seconds: + * + * ``` + * c = mg_connect(&mgr, "cesanta.com", ev_handler); + * mg_set_timer(c, mg_time() + 1.5); + * ... + * + * void ev_handler(struct mg_connection *c, int ev, void *ev_data) { + * switch (ev) { + * case MG_EV_CONNECT: + * mg_set_timer(c, 0); // Clear connect timer + * break; + * case MG_EV_TIMER: + * log("Connect timeout"); + * c->flags |= MG_F_CLOSE_IMMEDIATELY; + * break; + * ``` + */ +double mg_set_timer(struct mg_connection *c, double timestamp); + +/* + * A sub-second precision version of time(). + */ +double mg_time(void); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* CS_MONGOOSE_SRC_NET_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_uri.h" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +/* + * === URI + */ + +#ifndef CS_MONGOOSE_SRC_URI_H_ +#define CS_MONGOOSE_SRC_URI_H_ + +/* Amalgamated: #include "mg_net.h" */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* + * Parses an URI and fills string chunks with locations of the respective + * uri components within the input uri string. NULL pointers will be + * ignored. + * + * General syntax: + * + * [scheme://[user_info@]]host[:port][/path][?query][#fragment] + * + * Example: + * + * foo.com:80 + * tcp://foo.com:1234 + * http://foo.com:80/bar?baz=1 + * https://user:pw@foo.com:443/blah + * + * `path` will include the leading slash. `query` won't include the leading `?`. + * `host` can contain embedded colons if surrounded by square brackets in order + * to support IPv6 literal addresses. + * + * + * Returns 0 on success, -1 on error. + */ +int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme, + struct mg_str *user_info, struct mg_str *host, + unsigned int *port, struct mg_str *path, struct mg_str *query, + struct mg_str *fragment); + +/* + * Assemble URI from parts. Any of the inputs can be NULL or zero-length mg_str. + * + * If normalize_path is true, path is normalized by resolving relative refs. + * + * Result is a heap-allocated string (uri->p must be free()d after use). + * + * Returns 0 on success, -1 on error. + */ +int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info, + const struct mg_str *host, unsigned int port, + const struct mg_str *path, const struct mg_str *query, + const struct mg_str *fragment, int normalize_path, + struct mg_str *uri); + +int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* CS_MONGOOSE_SRC_URI_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_util.h" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +/* + * === Utility API + */ + +#ifndef CS_MONGOOSE_SRC_UTIL_H_ +#define CS_MONGOOSE_SRC_UTIL_H_ + +#include + +/* Amalgamated: #include "mg_common.h" */ +/* Amalgamated: #include "mg_net_if.h" */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef MG_MAX_PATH +#ifdef PATH_MAX +#define MG_MAX_PATH PATH_MAX +#else +#define MG_MAX_PATH 256 +#endif +#endif + +/* + * Fetches substring from input string `s`, `end` into `v`. + * Skips initial delimiter characters. Records first non-delimiter character + * at the beginning of substring `v`. Then scans the rest of the string + * until a delimiter character or end-of-string is found. + * `delimiters` is a 0-terminated string containing delimiter characters. + * Either one of `delimiters` or `end_string` terminates the search. + * Returns an `s` pointer, advanced forward where parsing has stopped. + */ +const char *mg_skip(const char *s, const char *end_string, + const char *delimiters, struct mg_str *v); + +/* + * Decodes base64-encoded string `s`, `len` into the destination `dst`. + * The destination has to have enough space to hold the decoded buffer. + * Decoding stops either when all strings have been decoded or invalid an + * character appeared. + * Destination is '\0'-terminated. + * Returns the number of decoded characters. On success, that should be equal + * to `len`. On error (invalid character) the return value is smaller then + * `len`. + */ +int mg_base64_decode(const unsigned char *s, int len, char *dst); + +/* + * Base64-encode chunk of memory `src`, `src_len` into the destination `dst`. + * Destination has to have enough space to hold encoded buffer. + * Destination is '\0'-terminated. + */ +void mg_base64_encode(const unsigned char *src, int src_len, char *dst); + +#if MG_ENABLE_FILESYSTEM +/* + * Performs a 64-bit `stat()` call against a given file. + * + * `path` should be UTF8 encoded. + * + * Return value is the same as for `stat()` syscall. + */ +int mg_stat(const char *path, cs_stat_t *st); + +/* + * Opens the given file and returns a file stream. + * + * `path` and `mode` should be UTF8 encoded. + * + * Return value is the same as for the `fopen()` call. + */ +FILE *mg_fopen(const char *path, const char *mode); + +/* + * Opens the given file and returns a file stream. + * + * `path` should be UTF8 encoded. + * + * Return value is the same as for the `open()` syscall. + */ +int mg_open(const char *path, int flag, int mode); + +/* + * Reads data from the given file stream. + * + * Return value is a number of bytes readen. + */ +size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f); + +/* + * Writes data to the given file stream. + * + * Return value is a number of bytes wtitten. + */ +size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f); + +#endif /* MG_ENABLE_FILESYSTEM */ + +#if MG_ENABLE_THREADS +/* + * Starts a new detached thread. + * Arguments and semantics are the same as pthead's `pthread_create()`. + * `thread_func` is a thread function, `thread_func_param` is a parameter + * that is passed to the thread function. + */ +void *mg_start_thread(void *(*thread_func)(void *), void *thread_func_param); +#endif + +void mg_set_close_on_exec(sock_t); + +#define MG_SOCK_STRINGIFY_IP 1 +#define MG_SOCK_STRINGIFY_PORT 2 +#define MG_SOCK_STRINGIFY_REMOTE 4 +/* + * Converts a connection's local or remote address into string. + * + * The `flags` parameter is a bit mask that controls the behaviour, + * see `MG_SOCK_STRINGIFY_*` definitions. + * + * - MG_SOCK_STRINGIFY_IP - print IP address + * - MG_SOCK_STRINGIFY_PORT - print port number + * - MG_SOCK_STRINGIFY_REMOTE - print remote peer's IP/port, not local address + * + * If both port number and IP address are printed, they are separated by `:`. + * If compiled with `-DMG_ENABLE_IPV6`, IPv6 addresses are supported. + * Return length of the stringified address. + */ +int mg_conn_addr_to_str(struct mg_connection *c, char *buf, size_t len, + int flags); +#if MG_NET_IF == MG_NET_IF_SOCKET +/* Legacy interface. */ +void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags); +#endif + +/* + * Convert the socket's address into string. + * + * `flags` is MG_SOCK_STRINGIFY_IP and/or MG_SOCK_STRINGIFY_PORT. + */ +int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len, + int flags); + +#if MG_ENABLE_HEXDUMP +/* + * Generates a human-readable hexdump of memory chunk. + * + * Takes a memory buffer `buf` of length `len` and creates a hex dump of that + * buffer in `dst`. The generated output is a-la hexdump(1). + * Returns the length of generated string, excluding terminating `\0`. If + * returned length is bigger than `dst_len`, the overflow bytes are discarded. + */ +int mg_hexdump(const void *buf, int len, char *dst, int dst_len); + +/* Same as mg_hexdump, but with output going to file instead of a buffer. */ +void mg_hexdumpf(FILE *fp, const void *buf, int len); + +/* + * Generates human-readable hexdump of the data sent or received by the + * connection. `path` is a file name where hexdump should be written. + * `num_bytes` is a number of bytes sent/received. `ev` is one of the `MG_*` + * events sent to an event handler. This function is supposed to be called from + * the event handler. + */ +void mg_hexdump_connection(struct mg_connection *nc, const char *path, + const void *buf, int num_bytes, int ev); +#endif + +/* + * Returns true if target platform is big endian. + */ +int mg_is_big_endian(void); + +/* + * Use with cs_base64_init/update/finish in order to write out base64 in chunks. + */ +void mg_mbuf_append_base64_putc(char ch, void *user_data); + +/* + * Encode `len` bytes starting at `data` as base64 and append them to an mbuf. + */ +void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len); + +/* + * Generate a Basic Auth header and appends it to buf. + * If pass is NULL, then user is expected to contain the credentials pair + * already encoded as `user:pass`. + */ +void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass, + struct mbuf *buf); + +/* + * URL-escape the specified string. + * All characters acept letters, numbers and characters listed in + * `safe` are escaped. If `hex_upper`is true, `A-F` are used for hex digits. + * Input need not be NUL-terminated, but the returned string is. + * Returned string is heap-allocated and must be free()'d. + */ +#define MG_URL_ENCODE_F_SPACE_AS_PLUS (1 << 0) +#define MG_URL_ENCODE_F_UPPERCASE_HEX (1 << 1) +struct mg_str mg_url_encode_opt(const struct mg_str src, + const struct mg_str safe, unsigned int flags); + +/* Same as `mg_url_encode_opt(src, "._-$,;~()/", 0)`. */ +struct mg_str mg_url_encode(const struct mg_str src); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* CS_MONGOOSE_SRC_UTIL_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_http.h" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +/* + * === Common API reference + */ + +#ifndef CS_MONGOOSE_SRC_HTTP_H_ +#define CS_MONGOOSE_SRC_HTTP_H_ + +#if MG_ENABLE_HTTP + +/* Amalgamated: #include "mg_net.h" */ +/* Amalgamated: #include "common/mg_str.h" */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef MG_MAX_HTTP_HEADERS +#define MG_MAX_HTTP_HEADERS 20 +#endif + +#ifndef MG_MAX_HTTP_REQUEST_SIZE +#define MG_MAX_HTTP_REQUEST_SIZE 1024 +#endif + +#ifndef MG_MAX_HTTP_SEND_MBUF +#define MG_MAX_HTTP_SEND_MBUF 1024 +#endif + +#ifndef MG_CGI_ENVIRONMENT_SIZE +#define MG_CGI_ENVIRONMENT_SIZE 8192 +#endif + +/* HTTP message */ +struct http_message { + struct mg_str message; /* Whole message: request line + headers + body */ + struct mg_str body; /* Message body. 0-length for requests with no body */ + + /* HTTP Request line (or HTTP response line) */ + struct mg_str method; /* "GET" */ + struct mg_str uri; /* "/my_file.html" */ + struct mg_str proto; /* "HTTP/1.1" -- for both request and response */ + + /* For responses, code and response status message are set */ + int resp_code; + struct mg_str resp_status_msg; + + /* + * Query-string part of the URI. For example, for HTTP request + * GET /foo/bar?param1=val1¶m2=val2 + * | uri | query_string | + * + * Note that question mark character doesn't belong neither to the uri, + * nor to the query_string + */ + struct mg_str query_string; + + /* Headers */ + struct mg_str header_names[MG_MAX_HTTP_HEADERS]; + struct mg_str header_values[MG_MAX_HTTP_HEADERS]; +}; + +#if MG_ENABLE_HTTP_WEBSOCKET +/* WebSocket message */ +struct websocket_message { + unsigned char *data; + size_t size; + unsigned char flags; +}; +#endif + +/* HTTP multipart part */ +struct mg_http_multipart_part { + const char *file_name; + const char *var_name; + struct mg_str data; + int status; /* <0 on error */ + void *user_data; + /* + * User handler can indicate how much of the data was consumed + * by setting this variable. By default, it is assumed that all + * data has been consumed by the handler. + * If not all data was consumed, user's handler will be invoked again later + * with the remainder. + */ + size_t num_data_consumed; +}; + +/* SSI call context */ +struct mg_ssi_call_ctx { + struct http_message *req; /* The request being processed. */ + struct mg_str file; /* Filesystem path of the file being processed. */ + struct mg_str arg; /* The argument passed to the tag: . */ +}; + +/* HTTP and websocket events. void *ev_data is described in a comment. */ +#define MG_EV_HTTP_REQUEST 100 /* struct http_message * */ +#define MG_EV_HTTP_REPLY 101 /* struct http_message * */ +#define MG_EV_HTTP_CHUNK 102 /* struct http_message * */ +#define MG_EV_SSI_CALL 105 /* char * */ +#define MG_EV_SSI_CALL_CTX 106 /* struct mg_ssi_call_ctx * */ + +#if MG_ENABLE_HTTP_WEBSOCKET +#define MG_EV_WEBSOCKET_HANDSHAKE_REQUEST 111 /* struct http_message * */ +#define MG_EV_WEBSOCKET_HANDSHAKE_DONE 112 /* struct http_message * */ +#define MG_EV_WEBSOCKET_FRAME 113 /* struct websocket_message * */ +#define MG_EV_WEBSOCKET_CONTROL_FRAME 114 /* struct websocket_message * */ +#endif + +#if MG_ENABLE_HTTP_STREAMING_MULTIPART +#define MG_EV_HTTP_MULTIPART_REQUEST 121 /* struct http_message */ +#define MG_EV_HTTP_PART_BEGIN 122 /* struct mg_http_multipart_part */ +#define MG_EV_HTTP_PART_DATA 123 /* struct mg_http_multipart_part */ +#define MG_EV_HTTP_PART_END 124 /* struct mg_http_multipart_part */ +/* struct mg_http_multipart_part */ +#define MG_EV_HTTP_MULTIPART_REQUEST_END 125 +#endif + +/* + * Attaches a built-in HTTP event handler to the given connection. + * The user-defined event handler will receive following extra events: + * + * - MG_EV_HTTP_REQUEST: HTTP request has arrived. Parsed HTTP request + * is passed as + * `struct http_message` through the handler's `void *ev_data` pointer. + * - MG_EV_HTTP_REPLY: The HTTP reply has arrived. The parsed HTTP reply is + * passed as `struct http_message` through the handler's `void *ev_data` + * pointer. + * - MG_EV_HTTP_CHUNK: The HTTP chunked-encoding chunk has arrived. + * The parsed HTTP reply is passed as `struct http_message` through the + * handler's `void *ev_data` pointer. `http_message::body` would contain + * incomplete, reassembled HTTP body. + * It will grow with every new chunk that arrives, and it can + * potentially consume a lot of memory. An event handler may process + * the body as chunks are coming, and signal Mongoose to delete processed + * body by setting `MG_F_DELETE_CHUNK` in `mg_connection::flags`. When + * the last zero chunk is received, + * Mongoose sends `MG_EV_HTTP_REPLY` event with + * full reassembled body (if handler did not signal to delete chunks) or + * with empty body (if handler did signal to delete chunks). + * - MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: server has received the WebSocket + * handshake request. `ev_data` contains parsed HTTP request. + * - MG_EV_WEBSOCKET_HANDSHAKE_DONE: server has completed the WebSocket + * handshake. `ev_data` is a `struct http_message` containing the + * client's request (server mode) or server's response (client). + * In client mode handler can examine `resp_code`, which should be 101. + * - MG_EV_WEBSOCKET_FRAME: new WebSocket frame has arrived. `ev_data` is + * `struct websocket_message *` + * + * When compiled with MG_ENABLE_HTTP_STREAMING_MULTIPART, Mongoose parses + * multipart requests and splits them into separate events: + * - MG_EV_HTTP_MULTIPART_REQUEST: Start of the request. + * This event is sent before body is parsed. After this, the user + * should expect a sequence of PART_BEGIN/DATA/END requests. + * This is also the last time when headers and other request fields are + * accessible. + * - MG_EV_HTTP_PART_BEGIN: Start of a part of a multipart message. + * Argument: mg_http_multipart_part with var_name and file_name set + * (if present). No data is passed in this message. + * - MG_EV_HTTP_PART_DATA: new portion of data from the multipart message. + * Argument: mg_http_multipart_part. var_name and file_name are preserved, + * data is available in mg_http_multipart_part.data. + * - MG_EV_HTTP_PART_END: End of the current part. var_name, file_name are + * the same, no data in the message. If status is 0, then the part is + * properly terminated with a boundary, status < 0 means that connection + * was terminated. + * - MG_EV_HTTP_MULTIPART_REQUEST_END: End of the multipart request. + * Argument: mg_http_multipart_part, var_name and file_name are NULL, + * status = 0 means request was properly closed, < 0 means connection + * was terminated (note: in this case both PART_END and REQUEST_END are + * delivered). + */ +void mg_set_protocol_http_websocket(struct mg_connection *nc); + +#if MG_ENABLE_HTTP_WEBSOCKET +/* + * Send websocket handshake to the server. + * + * `nc` must be a valid connection, connected to a server. `uri` is an URI + * to fetch, extra_headers` is extra HTTP headers to send or `NULL`. + * + * This function is intended to be used by websocket client. + * + * Note that the Host header is mandatory in HTTP/1.1 and must be + * included in `extra_headers`. `mg_send_websocket_handshake2` offers + * a better API for that. + * + * Deprecated in favour of `mg_send_websocket_handshake2` + */ +void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri, + const char *extra_headers); + +/* + * Send websocket handshake to the server. + * + * `nc` must be a valid connection, connected to a server. `uri` is an URI + * to fetch, `host` goes into the `Host` header, `protocol` goes into the + * `Sec-WebSocket-Proto` header (NULL to omit), extra_headers` is extra HTTP + * headers to send or `NULL`. + * + * This function is intended to be used by websocket client. + */ +void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path, + const char *host, const char *protocol, + const char *extra_headers); + +/* Like mg_send_websocket_handshake2 but also passes basic auth header */ +void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path, + const char *host, const char *protocol, + const char *extra_headers, const char *user, + const char *pass); + +/* Same as mg_send_websocket_handshake3 but with strings not necessarily + * NUL-temrinated */ +void mg_send_websocket_handshake3v(struct mg_connection *nc, + const struct mg_str path, + const struct mg_str host, + const struct mg_str protocol, + const struct mg_str extra_headers, + const struct mg_str user, + const struct mg_str pass); + +/* + * Helper function that creates an outbound WebSocket connection. + * + * `url` is a URL to connect to. It must be properly URL-encoded, e.g. have + * no spaces, etc. By default, `mg_connect_ws()` sends Connection and + * Host headers. `extra_headers` is an extra HTTP header to send, e.g. + * `"User-Agent: my-app\r\n"`. + * If `protocol` is not NULL, then a `Sec-WebSocket-Protocol` header is sent. + * + * Examples: + * + * ```c + * nc1 = mg_connect_ws(mgr, ev_handler_1, "ws://echo.websocket.org", NULL, + * NULL); + * nc2 = mg_connect_ws(mgr, ev_handler_1, "wss://echo.websocket.org", NULL, + * NULL); + * nc3 = mg_connect_ws(mgr, ev_handler_1, "ws://api.cesanta.com", + * "clubby.cesanta.com", NULL); + * ``` + */ +struct mg_connection *mg_connect_ws(struct mg_mgr *mgr, + MG_CB(mg_event_handler_t event_handler, + void *user_data), + const char *url, const char *protocol, + const char *extra_headers); + +/* + * Helper function that creates an outbound WebSocket connection + * + * Mostly identical to `mg_connect_ws`, but allows to provide extra parameters + * (for example, SSL parameters) + */ +struct mg_connection *mg_connect_ws_opt( + struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), + struct mg_connect_opts opts, const char *url, const char *protocol, + const char *extra_headers); + +/* + * Send WebSocket frame to the remote end. + * + * `op_and_flags` specifies the frame's type. It's one of: + * + * - WEBSOCKET_OP_CONTINUE + * - WEBSOCKET_OP_TEXT + * - WEBSOCKET_OP_BINARY + * - WEBSOCKET_OP_CLOSE + * - WEBSOCKET_OP_PING + * - WEBSOCKET_OP_PONG + * + * Orred with one of the flags: + * + * - WEBSOCKET_DONT_FIN: Don't set the FIN flag on the frame to be sent. + * + * `data` and `data_len` contain frame data. + */ +void mg_send_websocket_frame(struct mg_connection *nc, int op_and_flags, + const void *data, size_t data_len); + +/* + * Like `mg_send_websocket_frame()`, but composes a single frame from multiple + * buffers. + */ +void mg_send_websocket_framev(struct mg_connection *nc, int op_and_flags, + const struct mg_str *strings, int num_strings); + +/* + * Sends WebSocket frame to the remote end. + * + * Like `mg_send_websocket_frame()`, but allows to create formatted messages + * with `printf()`-like semantics. + */ +void mg_printf_websocket_frame(struct mg_connection *nc, int op_and_flags, + const char *fmt, ...); + +/* Websocket opcodes, from http://tools.ietf.org/html/rfc6455 */ +#define WEBSOCKET_OP_CONTINUE 0 +#define WEBSOCKET_OP_TEXT 1 +#define WEBSOCKET_OP_BINARY 2 +#define WEBSOCKET_OP_CLOSE 8 +#define WEBSOCKET_OP_PING 9 +#define WEBSOCKET_OP_PONG 10 + +/* + * If set causes the FIN flag to not be set on outbound + * frames. This enables sending multiple fragments of a single + * logical message. + * + * The WebSocket protocol mandates that if the FIN flag of a data + * frame is not set, the next frame must be a WEBSOCKET_OP_CONTINUE. + * The last frame must have the FIN bit set. + * + * Note that mongoose will automatically defragment incoming messages, + * so this flag is used only on outbound messages. + */ +#define WEBSOCKET_DONT_FIN 0x100 + +#endif /* MG_ENABLE_HTTP_WEBSOCKET */ + +/* + * Decodes a URL-encoded string. + * + * Source string is specified by (`src`, `src_len`), and destination is + * (`dst`, `dst_len`). If `is_form_url_encoded` is non-zero, then + * `+` character is decoded as a blank space character. This function + * guarantees to NUL-terminate the destination. If destination is too small, + * then the source string is partially decoded and `-1` is returned. + *Otherwise, + * a length of the decoded string is returned, not counting final NUL. + */ +int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, + int is_form_url_encoded); + +extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[], + const size_t *msg_lens, uint8_t *digest); +extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[], + const size_t *msg_lens, uint8_t *digest); + +/* + * Flags for `mg_http_is_authorized()`. + */ +#define MG_AUTH_FLAG_IS_DIRECTORY (1 << 0) +#define MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE (1 << 1) +#define MG_AUTH_FLAG_ALLOW_MISSING_FILE (1 << 2) + +/* + * Checks whether an http request is authorized. `domain` is the authentication + * realm, `passwords_file` is a htdigest file (can be created e.g. with + * `htdigest` utility). If either `domain` or `passwords_file` is NULL, this + * function always returns 1; otherwise checks the authentication in the + * http request and returns 1 only if there is a match; 0 otherwise. + */ +int mg_http_is_authorized(struct http_message *hm, struct mg_str path, + const char *domain, const char *passwords_file, + int flags); + +/* + * Sends 401 Unauthorized response. + */ +void mg_http_send_digest_auth_request(struct mg_connection *c, + const char *domain); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* MG_ENABLE_HTTP */ + +#endif /* CS_MONGOOSE_SRC_HTTP_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_http_server.h" +#endif +/* + * === Server API reference + */ + +#ifndef CS_MONGOOSE_SRC_HTTP_SERVER_H_ +#define CS_MONGOOSE_SRC_HTTP_SERVER_H_ + +#if MG_ENABLE_HTTP + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* + * Parses a HTTP message. + * + * `is_req` should be set to 1 if parsing a request, 0 if reply. + * + * Returns the number of bytes parsed. If HTTP message is + * incomplete `0` is returned. On parse error, a negative number is returned. + */ +int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req); + +/* + * Searches and returns the header `name` in parsed HTTP message `hm`. + * If header is not found, NULL is returned. Example: + * + * struct mg_str *host_hdr = mg_get_http_header(hm, "Host"); + */ +struct mg_str *mg_get_http_header(struct http_message *hm, const char *name); + +/* + * Parses the HTTP header `hdr`. Finds variable `var_name` and stores its value + * in the buffer `*buf`, `buf_size`. If the buffer size is not enough, + * allocates a buffer of required size and writes it to `*buf`, similar to + * asprintf(). The caller should always check whether the buffer was updated, + * and free it if so. + * + * This function is supposed to parse cookies, authentication headers, etc. + * Example (error handling omitted): + * + * char user_buf[20]; + * char *user = user_buf; + * struct mg_str *hdr = mg_get_http_header(hm, "Authorization"); + * mg_http_parse_header2(hdr, "username", &user, sizeof(user_buf)); + * // ... do something useful with user + * if (user != user_buf) { + * free(user); + * } + * + * Returns the length of the variable's value. If variable is not found, 0 is + * returned. + */ +int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf, + size_t buf_size); + +/* + * DEPRECATED: use mg_http_parse_header2() instead. + * + * Same as mg_http_parse_header2(), but takes buffer as a `char *` (instead of + * `char **`), and thus it cannot allocate a new buffer if the provided one + * is not enough, and just returns 0 in that case. + */ +int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf, + size_t buf_size) +#ifdef __GNUC__ + __attribute__((deprecated)) +#endif + ; + +/* + * Gets and parses the Authorization: Basic header + * Returns -1 if no Authorization header is found, or if + * mg_parse_http_basic_auth + * fails parsing the resulting header. + */ +int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len, + char *pass, size_t pass_len); + +/* + * Parses the Authorization: Basic header + * Returns -1 iif the authorization type is not "Basic" or any other error such + * as incorrectly encoded base64 user password pair. + */ +int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len, + char *pass, size_t pass_len); + +/* + * Parses the buffer `buf`, `buf_len` that contains multipart form data chunks. + * Stores the chunk name in a `var_name`, `var_name_len` buffer. + * If a chunk is an uploaded file, then `file_name`, `file_name_len` is + * filled with an uploaded file name. `chunk`, `chunk_len` + * points to the chunk data. + * + * Return: number of bytes to skip to the next chunk or 0 if there are + * no more chunks. + * + * Usage example: + * + * ```c + * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { + * switch(ev) { + * case MG_EV_HTTP_REQUEST: { + * struct http_message *hm = (struct http_message *) ev_data; + * char var_name[100], file_name[100]; + * const char *chunk; + * size_t chunk_len, n1, n2; + * + * n1 = n2 = 0; + * while ((n2 = mg_parse_multipart(hm->body.p + n1, + * hm->body.len - n1, + * var_name, sizeof(var_name), + * file_name, sizeof(file_name), + * &chunk, &chunk_len)) > 0) { + * printf("var: %s, file_name: %s, size: %d, chunk: [%.*s]\n", + * var_name, file_name, (int) chunk_len, + * (int) chunk_len, chunk); + * n1 += n2; + * } + * } + * break; + * ``` + */ +size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name, + size_t var_name_len, char *file_name, + size_t file_name_len, const char **chunk, + size_t *chunk_len); + +/* + * Fetches a HTTP form variable. + * + * Fetches a variable `name` from a `buf` into a buffer specified by `dst`, + * `dst_len`. The destination is always zero-terminated. Returns the length of + * a fetched variable. If not found, 0 is returned. `buf` must be valid + * url-encoded buffer. If destination is too small or an error occured, + * negative number is returned. + */ +int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst, + size_t dst_len); + +#if MG_ENABLE_FILESYSTEM +/* + * This structure defines how `mg_serve_http()` works. + * Best practice is to set only required settings, and leave the rest as NULL. + */ +struct mg_serve_http_opts { + /* Path to web root directory */ + const char *document_root; + + /* List of index files. Default is "" */ + const char *index_files; + + /* + * Leave as NULL to disable authentication. + * To enable directory protection with authentication, set this to ".htpasswd" + * Then, creating ".htpasswd" file in any directory automatically protects + * it with digest authentication. + * Use `mongoose` web server binary, or `htdigest` Apache utility to + * create/manipulate passwords file. + * Make sure `auth_domain` is set to a valid domain name. + */ + const char *per_directory_auth_file; + + /* Authorization domain (domain name of this web server) */ + const char *auth_domain; + + /* + * Leave as NULL to disable authentication. + * Normally, only selected directories in the document root are protected. + * If absolutely every access to the web server needs to be authenticated, + * regardless of the URI, set this option to the path to the passwords file. + * Format of that file is the same as ".htpasswd" file. Make sure that file + * is located outside document root to prevent people fetching it. + */ + const char *global_auth_file; + + /* Set to "no" to disable directory listing. Enabled by default. */ + const char *enable_directory_listing; + + /* + * SSI files pattern. If not set, "**.shtml$|**.shtm$" is used. + * + * All files that match ssi_pattern are treated as SSI. + * + * Server Side Includes (SSI) is a simple interpreted server-side scripting + * language which is most commonly used to include the contents of a file + * into a web page. It can be useful when it is desirable to include a common + * piece of code throughout a website, for example, headers and footers. + * + * In order for a webpage to recognize an SSI-enabled HTML file, the + * filename should end with a special extension, by default the extension + * should be either .shtml or .shtm + * + * Unknown SSI directives are silently ignored by Mongoose. Currently, + * the following SSI directives are supported: + * <!--#include FILE_TO_INCLUDE --> + * <!--#exec "COMMAND_TO_EXECUTE" --> + * <!--#call COMMAND --> + * + * Note that <!--#include ...> directive supports three path + *specifications: + * + * <!--#include virtual="path" --> Path is relative to web server root + * <!--#include abspath="path" --> Path is absolute or relative to the + * web server working dir + * <!--#include file="path" -->, Path is relative to current document + * <!--#include "path" --> + * + * The include directive may be used to include the contents of a file or + * the result of running a CGI script. + * + * The exec directive is used to execute + * a command on a server, and show command's output. Example: + * + * <!--#exec "ls -l" --> + * + * The call directive is a way to invoke a C handler from the HTML page. + * On each occurence of <!--#call COMMAND OPTIONAL_PARAMS> directive, + * Mongoose calls a registered event handler with MG_EV_SSI_CALL event, + * and event parameter will point to the COMMAND OPTIONAL_PARAMS string. + * An event handler can output any text, for example by calling + * `mg_printf()`. This is a flexible way of generating a web page on + * server side by calling a C event handler. Example: + * + * <!--#call foo --> ... <!--#call bar --> + * + * In the event handler: + * case MG_EV_SSI_CALL: { + * const char *param = (const char *) ev_data; + * if (strcmp(param, "foo") == 0) { + * mg_printf(c, "hello from foo"); + * } else if (strcmp(param, "bar") == 0) { + * mg_printf(c, "hello from bar"); + * } + * break; + * } + */ + const char *ssi_pattern; + + /* IP ACL. By default, NULL, meaning all IPs are allowed to connect */ + const char *ip_acl; + +#if MG_ENABLE_HTTP_URL_REWRITES + /* URL rewrites. + * + * Comma-separated list of `uri_pattern=url_file_or_directory_path` rewrites. + * When HTTP request is received, Mongoose constructs a file name from the + * requested URI by combining `document_root` and the URI. However, if the + * rewrite option is used and `uri_pattern` matches requested URI, then + * `document_root` is ignored. Instead, `url_file_or_directory_path` is used, + * which should be a full path name or a path relative to the web server's + * current working directory. It can also be an URI (http:// or https://) + * in which case mongoose will behave as a reverse proxy for that destination. + * + * Note that `uri_pattern`, as all Mongoose patterns, is a prefix pattern. + * + * If uri_pattern starts with `@` symbol, then Mongoose compares it with the + * HOST header of the request. If they are equal, Mongoose sets document root + * to `file_or_directory_path`, implementing virtual hosts support. + * Example: `@foo.com=/document/root/for/foo.com` + * + * If `uri_pattern` starts with `%` symbol, then Mongoose compares it with + * the listening port. If they match, then Mongoose issues a 301 redirect. + * For example, to redirect all HTTP requests to the + * HTTPS port, do `%80=https://my.site.com`. Note that the request URI is + * automatically appended to the redirect location. + */ + const char *url_rewrites; +#endif + + /* DAV document root. If NULL, DAV requests are going to fail. */ + const char *dav_document_root; + + /* + * DAV passwords file. If NULL, DAV requests are going to fail. + * If passwords file is set to "-", then DAV auth is disabled. + */ + const char *dav_auth_file; + + /* Glob pattern for the files to hide. */ + const char *hidden_file_pattern; + + /* Set to non-NULL to enable CGI, e.g. **.cgi$|**.php$" */ + const char *cgi_file_pattern; + + /* If not NULL, ignore CGI script hashbang and use this interpreter */ + const char *cgi_interpreter; + + /* + * Comma-separated list of Content-Type overrides for path suffixes, e.g. + * ".txt=text/plain; charset=utf-8,.c=text/plain" + */ + const char *custom_mime_types; + + /* + * Extra HTTP headers to add to each server response. + * Example: to enable CORS, set this to "Access-Control-Allow-Origin: *". + */ + const char *extra_headers; +}; + +/* + * Serves given HTTP request according to the `options`. + * + * Example code snippet: + * + * ```c + * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { + * struct http_message *hm = (struct http_message *) ev_data; + * struct mg_serve_http_opts opts = { .document_root = "/var/www" }; // C99 + * + * switch (ev) { + * case MG_EV_HTTP_REQUEST: + * mg_serve_http(nc, hm, opts); + * break; + * default: + * break; + * } + * } + * ``` + */ +void mg_serve_http(struct mg_connection *nc, struct http_message *hm, + struct mg_serve_http_opts opts); + +/* + * Serves a specific file with a given MIME type and optional extra headers. + * + * Example code snippet: + * + * ```c + * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { + * switch (ev) { + * case MG_EV_HTTP_REQUEST: { + * struct http_message *hm = (struct http_message *) ev_data; + * mg_http_serve_file(nc, hm, "file.txt", + * mg_mk_str("text/plain"), mg_mk_str("")); + * break; + * } + * ... + * } + * } + * ``` + */ +void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm, + const char *path, const struct mg_str mime_type, + const struct mg_str extra_headers); + +#if MG_ENABLE_HTTP_STREAMING_MULTIPART + +/* Callback prototype for `mg_file_upload_handler()`. */ +typedef struct mg_str (*mg_fu_fname_fn)(struct mg_connection *nc, + struct mg_str fname); + +/* + * File upload handler. + * This handler can be used to implement file uploads with minimum code. + * This handler will process MG_EV_HTTP_PART_* events and store file data into + * a local file. + * `local_name_fn` will be invoked with whatever name was provided by the client + * and will expect the name of the local file to open. A return value of NULL + * will abort file upload (client will get a "403 Forbidden" response). If + * non-null, the returned string must be heap-allocated and will be freed by + * the caller. + * Exception: it is ok to return the same string verbatim. + * + * Example: + * + * ```c + * struct mg_str upload_fname(struct mg_connection *nc, struct mg_str fname) { + * // Just return the same filename. Do not actually do this except in test! + * // fname is user-controlled and needs to be sanitized. + * return fname; + * } + * void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { + * switch (ev) { + * ... + * case MG_EV_HTTP_PART_BEGIN: + * case MG_EV_HTTP_PART_DATA: + * case MG_EV_HTTP_PART_END: + * mg_file_upload_handler(nc, ev, ev_data, upload_fname); + * break; + * } + * } + * ``` + */ +void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data, + mg_fu_fname_fn local_name_fn + MG_UD_ARG(void *user_data)); +#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ +#endif /* MG_ENABLE_FILESYSTEM */ + +/* + * Registers a callback for a specified http endpoint + * Note: if callback is registered it is called instead of the + * callback provided in mg_bind + * + * Example code snippet: + * + * ```c + * static void handle_hello1(struct mg_connection *nc, int ev, void *ev_data) { + * (void) ev; (void) ev_data; + * mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello1]"); + * nc->flags |= MG_F_SEND_AND_CLOSE; + * } + * + * static void handle_hello2(struct mg_connection *nc, int ev, void *ev_data) { + * (void) ev; (void) ev_data; + * mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello2]"); + * nc->flags |= MG_F_SEND_AND_CLOSE; + * } + * + * void init() { + * nc = mg_bind(&mgr, local_addr, cb1); + * mg_register_http_endpoint(nc, "/hello1", handle_hello1); + * mg_register_http_endpoint(nc, "/hello1/hello2", handle_hello2); + * } + * ``` + */ +void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path, + MG_CB(mg_event_handler_t handler, + void *user_data)); + +struct mg_http_endpoint_opts { + void *user_data; + /* Authorization domain (realm) */ + const char *auth_domain; + const char *auth_file; +}; + +void mg_register_http_endpoint_opt(struct mg_connection *nc, + const char *uri_path, + mg_event_handler_t handler, + struct mg_http_endpoint_opts opts); + +/* + * Authenticates a HTTP request against an opened password file. + * Returns 1 if authenticated, 0 otherwise. + */ +int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain, + FILE *fp); + +/* + * Authenticates given response params against an opened password file. + * Returns 1 if authenticated, 0 otherwise. + * + * It's used by mg_http_check_digest_auth(). + */ +int mg_check_digest_auth(struct mg_str method, struct mg_str uri, + struct mg_str username, struct mg_str cnonce, + struct mg_str response, struct mg_str qop, + struct mg_str nc, struct mg_str nonce, + struct mg_str auth_domain, FILE *fp); + +/* + * Sends buffer `buf` of size `len` to the client using chunked HTTP encoding. + * This function sends the buffer size as hex number + newline first, then + * the buffer itself, then the newline. For example, + * `mg_send_http_chunk(nc, "foo", 3)` will append the `3\r\nfoo\r\n` string + * to the `nc->send_mbuf` output IO buffer. + * + * NOTE: The HTTP header "Transfer-Encoding: chunked" should be sent prior to + * using this function. + * + * NOTE: do not forget to send an empty chunk at the end of the response, + * to tell the client that everything was sent. Example: + * + * ``` + * mg_printf_http_chunk(nc, "%s", "my response!"); + * mg_send_http_chunk(nc, "", 0); // Tell the client we're finished + * ``` + */ +void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len); + +/* + * Sends a printf-formatted HTTP chunk. + * Functionality is similar to `mg_send_http_chunk()`. + */ +void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...); + +/* + * Sends the response status line. + * If `extra_headers` is not NULL, then `extra_headers` are also sent + * after the response line. `extra_headers` must NOT end end with new line. + * Example: + * + * mg_send_response_line(nc, 200, "Access-Control-Allow-Origin: *"); + * + * Will result in: + * + * HTTP/1.1 200 OK\r\n + * Access-Control-Allow-Origin: *\r\n + */ +void mg_send_response_line(struct mg_connection *nc, int status_code, + const char *extra_headers); + +/* + * Sends an error response. If reason is NULL, the message will be inferred + * from the error code (if supported). + */ +void mg_http_send_error(struct mg_connection *nc, int code, const char *reason); + +/* + * Sends a redirect response. + * `status_code` should be either 301 or 302 and `location` point to the + * new location. + * If `extra_headers` is not empty, then `extra_headers` are also sent + * after the response line. `extra_headers` must NOT end end with new line. + * + * Example: + * + * mg_http_send_redirect(nc, 302, mg_mk_str("/login"), mg_mk_str(NULL)); + */ +void mg_http_send_redirect(struct mg_connection *nc, int status_code, + const struct mg_str location, + const struct mg_str extra_headers); + +/* + * Sends the response line and headers. + * This function sends the response line with the `status_code`, and + * automatically + * sends one header: either "Content-Length" or "Transfer-Encoding". + * If `content_length` is negative, then "Transfer-Encoding: chunked" header + * is sent, otherwise, "Content-Length" header is sent. + * + * NOTE: If `Transfer-Encoding` is `chunked`, then message body must be sent + * using `mg_send_http_chunk()` or `mg_printf_http_chunk()` functions. + * Otherwise, `mg_send()` or `mg_printf()` must be used. + * Extra headers could be set through `extra_headers`. Note `extra_headers` + * must NOT be terminated by a new line. + */ +void mg_send_head(struct mg_connection *n, int status_code, + int64_t content_length, const char *extra_headers); + +/* + * Sends a printf-formatted HTTP chunk, escaping HTML tags. + */ +void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...); + +#if MG_ENABLE_HTTP_URL_REWRITES +/* + * Proxies a given request to a given upstream http server. The path prefix + * in `mount` will be stripped of the path requested to the upstream server, + * e.g. if mount is /api and upstream is http://localhost:8001/foo + * then an incoming request to /api/bar will cause a request to + * http://localhost:8001/foo/bar + * + * EXPERIMENTAL API. Please use http_serve_http + url_rewrites if a static + * mapping is good enough. + */ +void mg_http_reverse_proxy(struct mg_connection *nc, + const struct http_message *hm, struct mg_str mount, + struct mg_str upstream); +#endif + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* MG_ENABLE_HTTP */ + +#endif /* CS_MONGOOSE_SRC_HTTP_SERVER_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_http_client.h" +#endif +/* + * === Client API reference + */ + +#ifndef CS_MONGOOSE_SRC_HTTP_CLIENT_H_ +#define CS_MONGOOSE_SRC_HTTP_CLIENT_H_ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* + * Helper function that creates an outbound HTTP connection. + * + * `url` is the URL to fetch. It must be properly URL-encoded, e.g. have + * no spaces, etc. By default, `mg_connect_http()` sends the Connection and + * Host headers. `extra_headers` is an extra HTTP header to send, e.g. + * `"User-Agent: my-app\r\n"`. + * If `post_data` is NULL, then a GET request is created. Otherwise, a POST + * request is created with the specified POST data. Note that if the data being + * posted is a form submission, the `Content-Type` header should be set + * accordingly (see example below). + * + * Examples: + * + * ```c + * nc1 = mg_connect_http(mgr, ev_handler_1, "http://www.google.com", NULL, + * NULL); + * nc2 = mg_connect_http(mgr, ev_handler_1, "https://github.com", NULL, NULL); + * nc3 = mg_connect_http( + * mgr, ev_handler_1, "my_server:8000/form_submit/", + * "Content-Type: application/x-www-form-urlencoded\r\n", + * "var_1=value_1&var_2=value_2"); + * ``` + */ +struct mg_connection *mg_connect_http( + struct mg_mgr *mgr, + MG_CB(mg_event_handler_t event_handler, void *user_data), const char *url, + const char *extra_headers, const char *post_data); + +/* + * Helper function that creates an outbound HTTP connection. + * + * Mostly identical to mg_connect_http, but allows you to provide extra + *parameters + * (for example, SSL parameters) + */ +struct mg_connection *mg_connect_http_opt( + struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), + struct mg_connect_opts opts, const char *url, const char *extra_headers, + const char *post_data); + +/* Creates digest authentication header for a client request. */ +int mg_http_create_digest_auth_header(char *buf, size_t buf_len, + const char *method, const char *uri, + const char *auth_domain, const char *user, + const char *passwd, const char *nonce); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* CS_MONGOOSE_SRC_HTTP_CLIENT_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_mqtt.h" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + * This software is dual-licensed: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. For the terms of this + * license, see . + * + * You are free to use this software under the terms of the GNU General + * Public License, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * Alternatively, you can license this software under a commercial + * license, as set out in . + */ + +/* + * === MQTT API reference + */ + +#ifndef CS_MONGOOSE_SRC_MQTT_H_ +#define CS_MONGOOSE_SRC_MQTT_H_ + +/* Amalgamated: #include "mg_net.h" */ + +struct mg_mqtt_message { + int cmd; + int qos; + int len; /* message length in the IO buffer */ + struct mg_str topic; + struct mg_str payload; + + uint8_t connack_ret_code; /* connack */ + uint16_t message_id; /* puback */ + + /* connect */ + uint8_t protocol_version; + uint8_t connect_flags; + uint16_t keep_alive_timer; + struct mg_str protocol_name; + struct mg_str client_id; + struct mg_str will_topic; + struct mg_str will_message; + struct mg_str user_name; + struct mg_str password; +}; + +struct mg_mqtt_topic_expression { + const char *topic; + uint8_t qos; +}; + +struct mg_send_mqtt_handshake_opts { + unsigned char flags; /* connection flags */ + uint16_t keep_alive; + const char *will_topic; + const char *will_message; + const char *user_name; + const char *password; +}; + +/* mg_mqtt_proto_data should be in header to allow external access to it */ +struct mg_mqtt_proto_data { + uint16_t keep_alive; + double last_control_time; +}; + +/* Message types */ +#define MG_MQTT_CMD_CONNECT 1 +#define MG_MQTT_CMD_CONNACK 2 +#define MG_MQTT_CMD_PUBLISH 3 +#define MG_MQTT_CMD_PUBACK 4 +#define MG_MQTT_CMD_PUBREC 5 +#define MG_MQTT_CMD_PUBREL 6 +#define MG_MQTT_CMD_PUBCOMP 7 +#define MG_MQTT_CMD_SUBSCRIBE 8 +#define MG_MQTT_CMD_SUBACK 9 +#define MG_MQTT_CMD_UNSUBSCRIBE 10 +#define MG_MQTT_CMD_UNSUBACK 11 +#define MG_MQTT_CMD_PINGREQ 12 +#define MG_MQTT_CMD_PINGRESP 13 +#define MG_MQTT_CMD_DISCONNECT 14 + +/* MQTT event types */ +#define MG_MQTT_EVENT_BASE 200 +#define MG_EV_MQTT_CONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNECT) +#define MG_EV_MQTT_CONNACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNACK) +#define MG_EV_MQTT_PUBLISH (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBLISH) +#define MG_EV_MQTT_PUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBACK) +#define MG_EV_MQTT_PUBREC (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREC) +#define MG_EV_MQTT_PUBREL (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREL) +#define MG_EV_MQTT_PUBCOMP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBCOMP) +#define MG_EV_MQTT_SUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBSCRIBE) +#define MG_EV_MQTT_SUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBACK) +#define MG_EV_MQTT_UNSUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBSCRIBE) +#define MG_EV_MQTT_UNSUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBACK) +#define MG_EV_MQTT_PINGREQ (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGREQ) +#define MG_EV_MQTT_PINGRESP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGRESP) +#define MG_EV_MQTT_DISCONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_DISCONNECT) + +/* Message flags */ +#define MG_MQTT_RETAIN 0x1 +#define MG_MQTT_DUP 0x4 +#define MG_MQTT_QOS(qos) ((qos) << 1) +#define MG_MQTT_GET_QOS(flags) (((flags) &0x6) >> 1) +#define MG_MQTT_SET_QOS(flags, qos) (flags) = ((flags) & ~0x6) | ((qos) << 1) + +/* Connection flags */ +#define MG_MQTT_CLEAN_SESSION 0x02 +#define MG_MQTT_HAS_WILL 0x04 +#define MG_MQTT_WILL_RETAIN 0x20 +#define MG_MQTT_HAS_PASSWORD 0x40 +#define MG_MQTT_HAS_USER_NAME 0x80 +#define MG_MQTT_GET_WILL_QOS(flags) (((flags) &0x18) >> 3) +#define MG_MQTT_SET_WILL_QOS(flags, qos) \ + (flags) = ((flags) & ~0x18) | ((qos) << 3) + +/* CONNACK return codes */ +#define MG_EV_MQTT_CONNACK_ACCEPTED 0 +#define MG_EV_MQTT_CONNACK_UNACCEPTABLE_VERSION 1 +#define MG_EV_MQTT_CONNACK_IDENTIFIER_REJECTED 2 +#define MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE 3 +#define MG_EV_MQTT_CONNACK_BAD_AUTH 4 +#define MG_EV_MQTT_CONNACK_NOT_AUTHORIZED 5 + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* + * Attaches a built-in MQTT event handler to the given connection. + * + * The user-defined event handler will receive following extra events: + * + * - MG_EV_MQTT_CONNACK + * - MG_EV_MQTT_PUBLISH + * - MG_EV_MQTT_PUBACK + * - MG_EV_MQTT_PUBREC + * - MG_EV_MQTT_PUBREL + * - MG_EV_MQTT_PUBCOMP + * - MG_EV_MQTT_SUBACK + */ +void mg_set_protocol_mqtt(struct mg_connection *nc); + +/* Sends an MQTT handshake. */ +void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id); + +/* Sends an MQTT handshake with optional parameters. */ +void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id, + struct mg_send_mqtt_handshake_opts); + +/* Publishes a message to a given topic. */ +void mg_mqtt_publish(struct mg_connection *nc, const char *topic, + uint16_t message_id, int flags, const void *data, + size_t len); + +/* Subscribes to a bunch of topics. */ +void mg_mqtt_subscribe(struct mg_connection *nc, + const struct mg_mqtt_topic_expression *topics, + size_t topics_len, uint16_t message_id); + +/* Unsubscribes from a bunch of topics. */ +void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics, + size_t topics_len, uint16_t message_id); + +/* Sends a DISCONNECT command. */ +void mg_mqtt_disconnect(struct mg_connection *nc); + +/* Sends a CONNACK command with a given `return_code`. */ +void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code); + +/* Sends a PUBACK command with a given `message_id`. */ +void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id); + +/* Sends a PUBREC command with a given `message_id`. */ +void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id); + +/* Sends a PUBREL command with a given `message_id`. */ +void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id); + +/* Sends a PUBCOMP command with a given `message_id`. */ +void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id); + +/* + * Sends a SUBACK command with a given `message_id` + * and a sequence of granted QoSs. + */ +void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len, + uint16_t message_id); + +/* Sends a UNSUBACK command with a given `message_id`. */ +void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id); + +/* Sends a PINGREQ command. */ +void mg_mqtt_ping(struct mg_connection *nc); + +/* Sends a PINGRESP command. */ +void mg_mqtt_pong(struct mg_connection *nc); + +/* + * Extracts the next topic expression from a SUBSCRIBE command payload. + * + * The topic expression name will point to a string in the payload buffer. + * Returns the pos of the next topic expression or -1 when the list + * of topics is exhausted. + */ +int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg, + struct mg_str *topic, uint8_t *qos, int pos); + +/* + * Matches a topic against a topic expression + * + * Returns 1 if it matches; 0 otherwise. + */ +int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic); + +/* + * Same as `mg_mqtt_match_topic_expression()`, but takes `exp` as a + * NULL-terminated string. + */ +int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* CS_MONGOOSE_SRC_MQTT_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_mqtt_server.h" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + * This software is dual-licensed: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. For the terms of this + * license, see . + * + * You are free to use this software under the terms of the GNU General + * Public License, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * Alternatively, you can license this software under a commercial + * license, as set out in . + */ + +/* + * === MQTT Server API reference + */ + +#ifndef CS_MONGOOSE_SRC_MQTT_BROKER_H_ +#define CS_MONGOOSE_SRC_MQTT_BROKER_H_ + +#if MG_ENABLE_MQTT_BROKER + +/* Amalgamated: #include "common/queue.h" */ +/* Amalgamated: #include "mg_mqtt.h" */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef MG_MQTT_MAX_SESSION_SUBSCRIPTIONS +#define MG_MQTT_MAX_SESSION_SUBSCRIPTIONS 512 +#endif + +struct mg_mqtt_broker; + +/* MQTT session (Broker side). */ +struct mg_mqtt_session { + struct mg_mqtt_broker *brk; /* Broker */ + LIST_ENTRY(mg_mqtt_session) link; /* mg_mqtt_broker::sessions linkage */ + struct mg_connection *nc; /* Connection with the client */ + size_t num_subscriptions; /* Size of `subscriptions` array */ + void *user_data; /* User data */ + struct mg_mqtt_topic_expression *subscriptions; +}; + +/* MQTT broker. */ +struct mg_mqtt_broker { + LIST_HEAD(_mg_sesshead, mg_mqtt_session) sessions; /* Session list */ + void *user_data; /* User data */ +}; + +/* Initialises a MQTT broker. */ +void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data); + +/* + * Processes a MQTT broker message. + * + * The listening connection expects a pointer to an initialised + * `mg_mqtt_broker` structure in the `user_data` field. + * + * Basic usage: + * + * ```c + * mg_mqtt_broker_init(&brk, NULL); + * + * if ((nc = mg_bind(&mgr, address, mg_mqtt_broker)) == NULL) { + * // fail; + * } + * nc->user_data = &brk; + * ``` + * + * New incoming connections will receive a `mg_mqtt_session` structure + * in the connection `user_data`. The original `user_data` will be stored + * in the `user_data` field of the session structure. This allows the user + * handler to store user data before `mg_mqtt_broker` creates the session. + * + * Since only the MG_EV_ACCEPT message is processed by the listening socket, + * for most events the `user_data` will thus point to a `mg_mqtt_session`. + */ +void mg_mqtt_broker(struct mg_connection *brk, int ev, void *data); + +/* + * Iterates over all MQTT session connections. Example: + * + * ```c + * struct mg_mqtt_session *s; + * for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) { + * // Do something + * } + * ``` + */ +struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk, + struct mg_mqtt_session *s); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* MG_ENABLE_MQTT_BROKER */ +#endif /* CS_MONGOOSE_SRC_MQTT_BROKER_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_dns.h" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +/* + * === DNS API reference + */ + +#ifndef CS_MONGOOSE_SRC_DNS_H_ +#define CS_MONGOOSE_SRC_DNS_H_ + +/* Amalgamated: #include "mg_net.h" */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#define MG_DNS_A_RECORD 0x01 /* Lookup IP address */ +#define MG_DNS_CNAME_RECORD 0x05 /* Lookup CNAME */ +#define MG_DNS_PTR_RECORD 0x0c /* Lookup PTR */ +#define MG_DNS_TXT_RECORD 0x10 /* Lookup TXT */ +#define MG_DNS_AAAA_RECORD 0x1c /* Lookup IPv6 address */ +#define MG_DNS_SRV_RECORD 0x21 /* Lookup SRV */ +#define MG_DNS_MX_RECORD 0x0f /* Lookup mail server for domain */ +#define MG_DNS_ANY_RECORD 0xff +#define MG_DNS_NSEC_RECORD 0x2f + +#define MG_MAX_DNS_QUESTIONS 32 +#define MG_MAX_DNS_ANSWERS 32 + +#define MG_DNS_MESSAGE 100 /* High-level DNS message event */ + +enum mg_dns_resource_record_kind { + MG_DNS_INVALID_RECORD = 0, + MG_DNS_QUESTION, + MG_DNS_ANSWER +}; + +/* DNS resource record. */ +struct mg_dns_resource_record { + struct mg_str name; /* buffer with compressed name */ + int rtype; + int rclass; + int ttl; + enum mg_dns_resource_record_kind kind; + struct mg_str rdata; /* protocol data (can be a compressed name) */ +}; + +/* DNS message (request and response). */ +struct mg_dns_message { + struct mg_str pkt; /* packet body */ + uint16_t flags; + uint16_t transaction_id; + int num_questions; + int num_answers; + struct mg_dns_resource_record questions[MG_MAX_DNS_QUESTIONS]; + struct mg_dns_resource_record answers[MG_MAX_DNS_ANSWERS]; +}; + +struct mg_dns_resource_record *mg_dns_next_record( + struct mg_dns_message *msg, int query, struct mg_dns_resource_record *prev); + +/* + * Parses the record data from a DNS resource record. + * + * - A: struct in_addr *ina + * - AAAA: struct in6_addr *ina + * - CNAME: char buffer + * + * Returns -1 on error. + * + * TODO(mkm): MX + */ +int mg_dns_parse_record_data(struct mg_dns_message *msg, + struct mg_dns_resource_record *rr, void *data, + size_t data_len); + +/* + * Sends a DNS query to the remote end. + */ +void mg_send_dns_query(struct mg_connection *nc, const char *name, + int query_type); + +/* + * Inserts a DNS header to an IO buffer. + * + * Returns the number of bytes inserted. + */ +int mg_dns_insert_header(struct mbuf *io, size_t pos, + struct mg_dns_message *msg); + +/* + * Appends already encoded questions from an existing message. + * + * This is useful when generating a DNS reply message which includes + * all question records. + * + * Returns the number of appended bytes. + */ +int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg); + +/* + * Encodes and appends a DNS resource record to an IO buffer. + * + * The record metadata is taken from the `rr` parameter, while the name and data + * are taken from the parameters, encoded in the appropriate format depending on + * record type and stored in the IO buffer. The encoded values might contain + * offsets within the IO buffer. It's thus important that the IO buffer doesn't + * get trimmed while a sequence of records are encoded while preparing a DNS + * reply. + * + * This function doesn't update the `name` and `rdata` pointers in the `rr` + * struct because they might be invalidated as soon as the IO buffer grows + * again. + * + * Returns the number of bytes appended or -1 in case of error. + */ +int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr, + const char *name, size_t nlen, const void *rdata, + size_t rlen); + +/* + * Encodes a DNS name. + */ +int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len); + +/* Low-level: parses a DNS response. */ +int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg); + +/* + * Uncompresses a DNS compressed name. + * + * The containing DNS message is required because of the compressed encoding + * and reference suffixes present elsewhere in the packet. + * + * If the name is less than `dst_len` characters long, the remainder + * of `dst` is terminated with `\0` characters. Otherwise, `dst` is not + * terminated. + * + * If `dst_len` is 0 `dst` can be NULL. + * Returns the uncompressed name length. + */ +size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name, + char *dst, int dst_len); + +/* + * Attaches a built-in DNS event handler to the given listening connection. + * + * The DNS event handler parses the incoming UDP packets, treating them as DNS + * requests. If an incoming packet gets successfully parsed by the DNS event + * handler, a user event handler will receive an `MG_DNS_REQUEST` event, with + * `ev_data` pointing to the parsed `struct mg_dns_message`. + * + * See + * [captive_dns_server](https://github.com/cesanta/mongoose/tree/master/examples/captive_dns_server) + * example on how to handle DNS request and send DNS reply. + */ +void mg_set_protocol_dns(struct mg_connection *nc); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* CS_MONGOOSE_SRC_DNS_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_dns_server.h" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +/* + * === DNS server API reference + * + * Disabled by default; enable with `-DMG_ENABLE_DNS_SERVER`. + */ + +#ifndef CS_MONGOOSE_SRC_DNS_SERVER_H_ +#define CS_MONGOOSE_SRC_DNS_SERVER_H_ + +#if MG_ENABLE_DNS_SERVER + +/* Amalgamated: #include "mg_dns.h" */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#define MG_DNS_SERVER_DEFAULT_TTL 3600 + +struct mg_dns_reply { + struct mg_dns_message *msg; + struct mbuf *io; + size_t start; +}; + +/* + * Creates a DNS reply. + * + * The reply will be based on an existing query message `msg`. + * The query body will be appended to the output buffer. + * "reply + recursion allowed" will be added to the message flags and the + * message's num_answers will be set to 0. + * + * Answer records can be appended with `mg_dns_send_reply` or by lower + * level function defined in the DNS API. + * + * In order to send a reply use `mg_dns_send_reply`. + * It's possible to use a connection's send buffer as reply buffer, + * and it will work for both UDP and TCP connections. + * + * Example: + * + * ```c + * reply = mg_dns_create_reply(&nc->send_mbuf, msg); + * for (i = 0; i < msg->num_questions; i++) { + * rr = &msg->questions[i]; + * if (rr->rtype == MG_DNS_A_RECORD) { + * mg_dns_reply_record(&reply, rr, 3600, &dummy_ip_addr, 4); + * } + * } + * mg_dns_send_reply(nc, &reply); + * ``` + */ +struct mg_dns_reply mg_dns_create_reply(struct mbuf *io, + struct mg_dns_message *msg); + +/* + * Appends a DNS reply record to the IO buffer and to the DNS message. + * + * The message's num_answers field will be incremented. It's the caller's duty + * to ensure num_answers is properly initialised. + * + * Returns -1 on error. + */ +int mg_dns_reply_record(struct mg_dns_reply *reply, + struct mg_dns_resource_record *question, + const char *name, int rtype, int ttl, const void *rdata, + size_t rdata_len); + +/* + * Sends a DNS reply through a connection. + * + * The DNS data is stored in an IO buffer pointed by reply structure in `r`. + * This function mutates the content of that buffer in order to ensure that + * the DNS header reflects the size and flags of the message, that might have + * been updated either with `mg_dns_reply_record` or by direct manipulation of + * `r->message`. + * + * Once sent, the IO buffer will be trimmed unless the reply IO buffer + * is the connection's send buffer and the connection is not in UDP mode. + */ +void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* MG_ENABLE_DNS_SERVER */ +#endif /* CS_MONGOOSE_SRC_DNS_SERVER_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_resolv.h" +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +/* + * === API reference + */ + +#ifndef CS_MONGOOSE_SRC_RESOLV_H_ +#define CS_MONGOOSE_SRC_RESOLV_H_ + +/* Amalgamated: #include "mg_dns.h" */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +enum mg_resolve_err { + MG_RESOLVE_OK = 0, + MG_RESOLVE_NO_ANSWERS = 1, + MG_RESOLVE_EXCEEDED_RETRY_COUNT = 2, + MG_RESOLVE_TIMEOUT = 3 +}; + +typedef void (*mg_resolve_callback_t)(struct mg_dns_message *dns_message, + void *user_data, enum mg_resolve_err); + +/* Options for `mg_resolve_async_opt`. */ +struct mg_resolve_async_opts { + const char *nameserver; + int max_retries; /* defaults to 2 if zero */ + int timeout; /* in seconds; defaults to 5 if zero */ + int accept_literal; /* pseudo-resolve literal ipv4 and ipv6 addrs */ + int only_literal; /* only resolves literal addrs; sync cb invocation */ + struct mg_connection **dns_conn; /* return DNS connection */ +}; + +/* See `mg_resolve_async_opt()` */ +int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query, + mg_resolve_callback_t cb, void *data); + +/* Set default DNS server */ +void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver); + +/* + * Resolved a DNS name asynchronously. + * + * Upon successful resolution, the user callback will be invoked + * with the full DNS response message and a pointer to the user's + * context `data`. + * + * In case of timeout while performing the resolution the callback + * will receive a NULL `msg`. + * + * The DNS answers can be extracted with `mg_next_record` and + * `mg_dns_parse_record_data`: + * + * [source,c] + * ---- + * struct in_addr ina; + * struct mg_dns_resource_record *rr = mg_next_record(msg, MG_DNS_A_RECORD, + * NULL); + * mg_dns_parse_record_data(msg, rr, &ina, sizeof(ina)); + * ---- + */ +int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query, + mg_resolve_callback_t cb, void *data, + struct mg_resolve_async_opts opts); + +/* + * Resolve a name from `/etc/hosts`. + * + * Returns 0 on success, -1 on failure. + */ +int mg_resolve_from_hosts_file(const char *host, union socket_address *usa); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* CS_MONGOOSE_SRC_RESOLV_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_coap.h" +#endif +/* + * Copyright (c) 2015 Cesanta Software Limited + * All rights reserved + * This software is dual-licensed: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. For the terms of this + * license, see . + * + * You are free to use this software under the terms of the GNU General + * Public License, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * Alternatively, you can license this software under a commercial + * license, as set out in . + */ + +/* + * === CoAP API reference + * + * CoAP message format: + * + * ``` + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- + * |Ver| T | TKL | Code | Message ID | Token (if any, TKL bytes) ... + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- + * | Options (if any) ... |1 1 1 1 1 1 1 1| Payload (if any) ... + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- + * ``` + */ + +#ifndef CS_MONGOOSE_SRC_COAP_H_ +#define CS_MONGOOSE_SRC_COAP_H_ + +#if MG_ENABLE_COAP + +#define MG_COAP_MSG_TYPE_FIELD 0x2 +#define MG_COAP_CODE_CLASS_FIELD 0x4 +#define MG_COAP_CODE_DETAIL_FIELD 0x8 +#define MG_COAP_MSG_ID_FIELD 0x10 +#define MG_COAP_TOKEN_FIELD 0x20 +#define MG_COAP_OPTIOMG_FIELD 0x40 +#define MG_COAP_PAYLOAD_FIELD 0x80 + +#define MG_COAP_ERROR 0x10000 +#define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000) +#define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000) +#define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000) +#define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000) + +#define MG_COAP_MSG_CON 0 +#define MG_COAP_MSG_NOC 1 +#define MG_COAP_MSG_ACK 2 +#define MG_COAP_MSG_RST 3 +#define MG_COAP_MSG_MAX 3 + +#define MG_COAP_CODECLASS_REQUEST 0 +#define MG_COAP_CODECLASS_RESP_OK 2 +#define MG_COAP_CODECLASS_CLIENT_ERR 4 +#define MG_COAP_CODECLASS_SRV_ERR 5 + +#define MG_COAP_EVENT_BASE 300 +#define MG_EV_COAP_CON (MG_COAP_EVENT_BASE + MG_COAP_MSG_CON) +#define MG_EV_COAP_NOC (MG_COAP_EVENT_BASE + MG_COAP_MSG_NOC) +#define MG_EV_COAP_ACK (MG_COAP_EVENT_BASE + MG_COAP_MSG_ACK) +#define MG_EV_COAP_RST (MG_COAP_EVENT_BASE + MG_COAP_MSG_RST) + +/* + * CoAP options. + * Use mg_coap_add_option and mg_coap_free_options + * for creation and destruction. + */ +struct mg_coap_option { + struct mg_coap_option *next; + uint32_t number; + struct mg_str value; +}; + +/* CoAP message. See RFC 7252 for details. */ +struct mg_coap_message { + uint32_t flags; + uint8_t msg_type; + uint8_t code_class; + uint8_t code_detail; + uint16_t msg_id; + struct mg_str token; + struct mg_coap_option *options; + struct mg_str payload; + struct mg_coap_option *optiomg_tail; +}; + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Sets CoAP protocol handler - triggers CoAP specific events. */ +int mg_set_protocol_coap(struct mg_connection *nc); + +/* + * Adds a new option to mg_coap_message structure. + * Returns pointer to the newly created option. + * Note: options must be freed by using mg_coap_free_options + */ +struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm, + uint32_t number, char *value, + size_t len); + +/* + * Frees the memory allocated for options. + * If the cm parameter doesn't contain any option it does nothing. + */ +void mg_coap_free_options(struct mg_coap_message *cm); + +/* + * Composes a CoAP message from `mg_coap_message` + * and sends it into `nc` connection. + * Returns 0 on success. On error, it is a bitmask: + * + * - `#define MG_COAP_ERROR 0x10000` + * - `#define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000)` + * - `#define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000)` + * - `#define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000)` + * - `#define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000)` + */ +uint32_t mg_coap_send_message(struct mg_connection *nc, + struct mg_coap_message *cm); + +/* + * Composes CoAP acknowledgement from `mg_coap_message` + * and sends it into `nc` connection. + * Return value: see `mg_coap_send_message()` + */ +uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id); + +/* + * Parses CoAP message and fills mg_coap_message and returns cm->flags. + * This is a helper function. + * + * NOTE: usually CoAP works over UDP, so lack of data means format error. + * But, in theory, it is possible to use CoAP over TCP (according to RFC) + * + * The caller has to check results and treat COAP_NOT_ENOUGH_DATA according to + * underlying protocol: + * + * - in case of UDP COAP_NOT_ENOUGH_DATA means COAP_FORMAT_ERROR, + * - in case of TCP client can try to receive more data + * + * Return value: see `mg_coap_send_message()` + */ +uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm); + +/* + * Composes CoAP message from mg_coap_message structure. + * This is a helper function. + * Return value: see `mg_coap_send_message()` + */ +uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* MG_ENABLE_COAP */ + +#endif /* CS_MONGOOSE_SRC_COAP_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_sntp.h" +#endif +/* + * Copyright (c) 2016 Cesanta Software Limited + * All rights reserved + */ + +#ifndef CS_MONGOOSE_SRC_SNTP_H_ +#define CS_MONGOOSE_SRC_SNTP_H_ + +#if MG_ENABLE_SNTP + +#define MG_SNTP_EVENT_BASE 500 + +/* + * Received reply from time server. Event handler parameter contains + * pointer to mg_sntp_message structure + */ +#define MG_SNTP_REPLY (MG_SNTP_EVENT_BASE + 1) + +/* Received malformed SNTP packet */ +#define MG_SNTP_MALFORMED_REPLY (MG_SNTP_EVENT_BASE + 2) + +/* Failed to get time from server (timeout etc) */ +#define MG_SNTP_FAILED (MG_SNTP_EVENT_BASE + 3) + +struct mg_sntp_message { + /* if server sends this flags, user should not send requests to it */ + int kiss_of_death; + /* usual mg_time */ + double time; +}; + +/* Establishes connection to given sntp server */ +struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, + MG_CB(mg_event_handler_t event_handler, + void *user_data), + const char *sntp_server_name); + +/* Sends time request to given connection */ +void mg_sntp_send_request(struct mg_connection *c); + +/* + * Helper function + * Establishes connection to time server, tries to send request + * repeats sending SNTP_ATTEMPTS times every SNTP_TIMEOUT sec + * (if needed) + * See sntp_client example + */ +struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr, + mg_event_handler_t event_handler, + const char *sntp_server_name); + +#endif + +#endif /* CS_MONGOOSE_SRC_SNTP_H_ */ +#ifdef MG_MODULE_LINES +#line 1 "mongoose/src/mg_socks.h" +#endif +/* + * Copyright (c) 2017 Cesanta Software Limited + * All rights reserved + */ + +#ifndef CS_MONGOOSE_SRC_SOCKS_H_ +#define CS_MONGOOSE_SRC_SOCKS_H_ + +#if MG_ENABLE_SOCKS + +#define MG_SOCKS_VERSION 5 + +#define MG_SOCKS_HANDSHAKE_DONE MG_F_USER_1 +#define MG_SOCKS_CONNECT_DONE MG_F_USER_2 + +/* SOCKS5 handshake methods */ +enum mg_socks_handshake_method { + MG_SOCKS_HANDSHAKE_NOAUTH = 0, /* Handshake method - no authentication */ + MG_SOCKS_HANDSHAKE_GSSAPI = 1, /* Handshake method - GSSAPI auth */ + MG_SOCKS_HANDSHAKE_USERPASS = 2, /* Handshake method - user/password auth */ + MG_SOCKS_HANDSHAKE_FAILURE = 0xff, /* Handshake method - failure */ +}; + +/* SOCKS5 commands */ +enum mg_socks_command { + MG_SOCKS_CMD_CONNECT = 1, /* Command: CONNECT */ + MG_SOCKS_CMD_BIND = 2, /* Command: BIND */ + MG_SOCKS_CMD_UDP_ASSOCIATE = 3, /* Command: UDP ASSOCIATE */ +}; + +/* SOCKS5 address types */ +enum mg_socks_address_type { + MG_SOCKS_ADDR_IPV4 = 1, /* Address type: IPv4 */ + MG_SOCKS_ADDR_DOMAIN = 3, /* Address type: Domain name */ + MG_SOCKS_ADDR_IPV6 = 4, /* Address type: IPv6 */ +}; + +/* SOCKS5 response codes */ +enum mg_socks_response { + MG_SOCKS_SUCCESS = 0, /* Response: success */ + MG_SOCKS_FAILURE = 1, /* Response: failure */ + MG_SOCKS_NOT_ALLOWED = 2, /* Response: connection not allowed */ + MG_SOCKS_NET_UNREACHABLE = 3, /* Response: network unreachable */ + MG_SOCKS_HOST_UNREACHABLE = 4, /* Response: network unreachable */ + MG_SOCKS_CONN_REFUSED = 5, /* Response: network unreachable */ + MG_SOCKS_TTL_EXPIRED = 6, /* Response: network unreachable */ + MG_SOCKS_CMD_NOT_SUPPORTED = 7, /* Response: network unreachable */ + MG_SOCKS_ADDR_NOT_SUPPORTED = 8, /* Response: network unreachable */ +}; + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Turn the connection into the SOCKS server */ +void mg_set_protocol_socks(struct mg_connection *c); + +/* Create socks tunnel for the client connection */ +struct mg_iface *mg_socks_mk_iface(struct mg_mgr *, const char *proxy_addr); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif +#endif diff --git a/util/websocket.c b/util/websocket.c new file mode 100644 index 0000000..7c9eaa3 --- /dev/null +++ b/util/websocket.c @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ + +#include "mongoose.h" + +static sig_atomic_t s_signal_received = 0; +static const char *s_http_port = "8000"; +static struct mg_serve_http_opts s_http_server_opts; +static char server_pwd[100]; +static struct mg_connection *supernode_client = NULL; + +static void signal_handler(int sig_num) { + signal(sig_num, signal_handler); // Reinstantiate signal handler + s_signal_received = sig_num; +} + +//Display Message in console/terminal +static void display(struct mg_connection *nc, char type[25]){ + char addr[32]; + mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); + printf("%s\t%s\n", addr, type); +} + +//Broadcast incoming message (from nc to all) +static void broadcast(struct mg_connection *nc, const struct mg_str msg) { + char addr[32]; + mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); + printf("%s\tBroadcast\t[%d]\n", addr, (int)msg.len); + struct mg_connection *c; + for (c = mg_next(nc->mgr, NULL); c != NULL; c = mg_next(nc->mgr, c)) { + if (c == nc) continue; /* Don't send to the sender. */ + mg_send_websocket_frame(c, WEBSOCKET_OP_TEXT, msg.p, msg.len); + } +} + +//Unicast message (to nc) +static void unicast(struct mg_connection *nc, const struct mg_str msg) { + char addr[32]; + mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); + printf("%s\tUnicast\t[%d]\n", addr, (int)msg.len); + if(nc != NULL) + mg_send_websocket_frame(nc, WEBSOCKET_OP_TEXT, msg.p, msg.len); +} + +//Forward message (from nc to supernode) +static void unicast_forward(struct mg_connection *nc, const struct mg_str msg) { + char addr[32]; + mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); + printf("%s\tForward\t[%d]\n", addr, (int)msg.len); + if(supernode_client != NULL) + mg_send_websocket_frame(supernode_client, WEBSOCKET_OP_TEXT, msg.p, msg.len); + else + printf("SuperNode client is offline!\n"); +} + +//Request message (from nc to supernode) +static void unicast_request(struct mg_connection *nc, const struct mg_str msg) { + if(supernode_client == NULL){ + printf("SuperNode client is offline!\n"); + return; + } + char addr[32], buf[500]; + mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); + printf("%s\tRequest\t[%d]\n", addr, (int)msg.len-1); + snprintf(buf, sizeof(buf), "?%s %.*s", addr, (int) msg.len-1, msg.p+1); + mg_send_websocket_frame(supernode_client, WEBSOCKET_OP_TEXT, buf, strlen(buf)); +} + +//Reply message (from supernode) +static void unicast_reply(const struct mg_str msg) { + if(supernode_client == NULL){ + printf("SuperNode client is offline!\n"); + return; + } + //Get receiver address from msg + char receiverAddr[32]; + int index = (int)(strchr(msg.p, ' ') - msg.p) + 1; + snprintf(receiverAddr, sizeof(receiverAddr), "%.*s", index, msg.p); + printf("%s\tReply\t[%d]\n", receiverAddr, (int)msg.len - index); + //send msg to receiver + struct mg_connection *c; + for (c = mg_next(supernode_client->mgr, NULL); c != NULL; c = mg_next(supernode_client->mgr, c)) { + char addr[32]; + mg_sock_addr_to_str(&c->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); + if (!strcmp(receiverAddr,addr)) + mg_send_websocket_frame(c, WEBSOCKET_OP_TEXT, msg.p + index, msg.len - index); + } +} + +static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { + switch (ev) { + case MG_EV_WEBSOCKET_HANDSHAKE_DONE: { + /*New websocket connection*/ + display(nc, "+Connected+"); + break; + } + case MG_EV_WEBSOCKET_FRAME: { + struct websocket_message *wm = (struct websocket_message *) ev_data; + /* New websocket message*/ + struct mg_str d = {(char *) wm->data, wm->size}; + if (d.p[0] == '$'){ + char pass[100]; + snprintf(pass, sizeof(pass), "%.*s",(int)d.len-1, &d.p[1]); + if(!strcmp(pass,server_pwd)){ + if(supernode_client!=NULL) + unicast(supernode_client,mg_mk_str("$Another login is encountered! Please close/refresh this window")); + supernode_client = nc; + unicast(supernode_client,mg_mk_str("$Access Granted!")); + display(nc, "*Became SuperNode*"); + }else + unicast(nc,mg_mk_str("$Access Denied!")); + } + else if (d.p[0] == '?') + unicast_request(nc,d); + else if (nc == supernode_client) + unicast_reply(d); + else + unicast_forward(nc,d); + break; + } + case MG_EV_HTTP_REQUEST: { + mg_serve_http(nc, (struct http_message *) ev_data, s_http_server_opts); + break; + } + case MG_EV_CLOSE: { + /* Disconnect websocket*/ + if(nc == supernode_client){ + supernode_client = NULL; + display(nc,"!SuperNode Disconnected!"); + }else + display(nc, "-Disconnected-"); + break; + } + } +} + +int main(int argc, char** argv) { + + if(argc<=1){ + printf("Enter server password : "); + scanf("%s",server_pwd); + } + else + strcpy(server_pwd,argv[1]); + + struct mg_mgr mgr; + struct mg_connection *nc; + + signal(SIGTERM, signal_handler); + signal(SIGINT, signal_handler); + setvbuf(stdout, NULL, _IOLBF, 0); + setvbuf(stderr, NULL, _IOLBF, 0); + + mg_mgr_init(&mgr, NULL); + + nc = mg_bind(&mgr, s_http_port, ev_handler); + mg_set_protocol_http_websocket(nc); + s_http_server_opts.document_root = "."; // Serve current directory + s_http_server_opts.enable_directory_listing = "no"; + + printf("Started on port %s\n", s_http_port); + while (s_signal_received == 0) { + mg_mgr_poll(&mgr, 200); + } + mg_mgr_free(&mgr); + + return 0; +} From bd52c441695a41b27c1ee38d57ee1c28fa678d6c Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 29 Sep 2019 13:55:46 +0530 Subject: [PATCH 003/289] Added compactIDB operations and fixed bugs --- index.html | 4852 +++++++++++++++++++++++++++++++++++++++++++++- supernodeWSS | Bin 176456 -> 176456 bytes util/websocket.c | 2 +- 3 files changed, 4832 insertions(+), 22 deletions(-) diff --git a/index.html b/index.html index 1112ff3..29d0b25 100644 --- a/index.html +++ b/index.html @@ -7,7 +7,7 @@ @@ -80,11 +80,11 @@ + + \ No newline at end of file diff --git a/supernodeWSS b/supernodeWSS index 1b2ed59e35466dd31480cdae1fbf94f5a4e346a5..2a3d949b70cc7e9b9e604702933342b735893c5a 100644 GIT binary patch delta 15713 zcmcJWcU%-#+xO=hKmkEOL0FWgSP&FcuoqC!MKJ-p#@?~SUQiP>O5zGc%@{9iiAJnJ zBll_+J6JJMBgPsl#sX>*HRZ;(^Zd^4tkHd*_s^HlXXks))#mg$v+OCp<63;jb=f(W zq0MDU{0&`x^{`j;YqDhCP}xS;yhl1^OPv}Vh>3_hT($M^rLPv(JF?Q4BRf~8*UAPT zU!8o*>eaGyZHu?FW(}*iIX-JcU-TX>Z$Udn+NnzPkRJw!%(3 zLP>#kjHdPM@@}(ERTlXAy4bW06!P;`3Vc0vb2a-|JNpc!6wwTtwx6Ar6)!(u-5O0h z*-pDziSzSy*{Nw4D@C~1Y(G!kkD6q?o&9BH1EO8iv;}tB2TBRFk2LK$JMG^J>3q|l zYuYk9t;=oeAgi#GyK8bu|86Sw4u8XGC z+i3?YPoW*5X@}Zrrz;`;zPdC`JKIicP*UE~F0<2SD+{2tm3*t6cA1h7?Fub&p`CV% zQVQ+2n)ZsF_L$;T(^prlX`k3>?*k2(5}_A zyX>@iN)fcXG;Oh+_N?+0+Vh(Bww?Bd5)$C6yQ66oa9R zfN%OgnqLDuZKXTfVrwUN)#R~ua&JwZY$x~AAgKuQ)a}tE zi|r!pRYHP&bq6(Vj-9qhNrCpbrrm0%J*6yw_Kc=2u+x?(`Oqe7tyFBMEjE@0H}UZJ zVH-*MZ1RJ>RIaROzl9QwZ9AL@^WL6K(!R!(B>2QM zo+4b^HC1Y)2FJ}5ib$*C#bk@Z8TzuoqpGUUOt_-YjCIzxN;o$&2zN^q#!*(|Ggjl@ zlv%0fP~YVwJ@e>aG}@!FQ+1@LRe7fOh$z$>5}rJ&^UTB3-Mox=T?o}T7LKd#R&~P& zk}@4-{fKk=Y^N2*(wV8%>6y}PNf4bkj$iUAQ8(pTX6JC%_epwG877sG&}Vip&g^|b zpE;u}E+sBG(eOOcP;4mC8;+nZ&y*2a6;!GW%#IKFrn~0#6%rP6!}B;pvEF8T+E|p` zSEf)!w=9gN8apjZa-bc`GR50BSWi-c*wK`IwN+L3wRE*K*C)z;rKaqqSFR`xsI5XP zYSLw6z=~K$TBQum`O+<@6K-ShL}OK);*zBlp@gsMM2D0~t0E{zS-YwYjZm(v`kd}5 zV^;U1b;|zLO=-IF`|42YZLGfLIMGPu>e}WsNby`3Pi0E)b=?Cmwb!apf`qjSSKgGr z$XK{8UB-qic6}f!&nTQ;6|EGk&-U47T#;W{roGBqV+UGd zylzy8&M1@j)S?GU_MUt)D;>V~r#8v}T!WPv-*=>A#)9vMRua8-uobm7_B`0pk+vu+ zi)y2~dyBeKE5-3h8~V%`dt?_;lJfLuGOaOoJT{eRv9jlQ7unBGF(2O;xTZQuhaE*1 zcb}@ND3LBRWd5X1hVasTPBU8;_AervoBQpR2?qNT=$m$PKK zl9N(!HHOYBzh4cY?~QK1d`muc9mIe-S+=zT4VRs88&lTXK{S)bM@`j-tU+c@oIOQKX`-m4li%~6h;qbWwIFdJyU@`*YW z-TAB9L7q6iRFWQz!=f-%B!(d|NhJCqF+n8Ww@Er9F-=I?Au(MfqLG*@65&XEAriHb zSSb=ZBsPkKClZ@QLaaOayi}%U!Sj(vhgg?}8;TgtKJRr8!Td<5K<7;5J2FMm`&`X| z_RuCScA%E7{cdV83fR?=I#WESI8vE&!7WR>o#i+u3Lqm7aiUsugXcL>d-{a;J5g=w z$~T>;9z`)4Za!V(Pb*P8t>+&r(Pz|@dse2!G>orTrq(o%eVr+qdU297O{Y6toTQOIhZ6?hQu zs{)tW{IUvNr$W;eH;Q(oOm_F8o>XBP=0!JT*CFRM>kmwNZ%TEffA~Lsv;cL8)=?I{ z;vyX#^&4=^dZWT>mO1h<8mt%%mS9@zPiYQxm}>-5NX(`yZ#D0_*J$2_$2^lV-7_Fh z%5?fzs59HmvcP?^MHrCE69TDjVmIXCQq&oGb{n4f~jm=CgW@=G*a?T)oA+uiXB{}M=Rss~+{q-m8ckFH07V*XaW&WnT4 zC-wN-Agb?Q?XoCJMgxQu6ZFR_s+wpxo|IYlIX@1fmR`k|B&kPS??l6??gmU-_X3Uy zrZD=HhXm8WYR#ZciR-P;?!GIfC$ugn_>7PrzX*AELs6okLM-yxKHqSg5b9dP13mJ; z9;7c!YeJ|AVO*T4P0gu2JJz8vIp7#a)}aRUg8Ly$SNRhGBj?qjy0o0n3w&s*s6)LR zHsUg*&;T+Zw-Fb(<6}bcaQ$w0cFS%nl z)u(?p1{dkG zGlu>lRyCi1eVo~dqN+bXW3RczXB$yy^&kG1VkbK_rj|69+czd78sJ%DN~02<5Q)lV z@E4IZUv?{C?@j-!UcCFW3`MOk+GChtnbm}u6NDr8TSsZldZCECm!O_4q?x4|eg z+d4*$=nZEv{>E*&7EMHHd_9J~rXrr#oPy|A6Q24Ngm(P0B~5Z?lxMH?Mn22gs}``6>9baFSjk(2l=As(E82i)lUrli8O-ZjQzqTwh&B{Z^Tc=7BL3A>%(xi| zXz*QT(cm#-cw`$2rB!TbLqRo{YIa{*?fn0>o5x4nV8MxJ=e9JIo^Wbg+U}jOQ-n<@ z)SpZ!u54)xr`D$W?dUei4tXY*4)ln;b5Qzyp}{cBj%m9}pxr2wa~$m;s?T_WpA8zY z##*?Ou?T%0|B21Cc9Ahx|+DvYBaI| z`}u_*U6H2ipvA%$Q%%#}sHvoE@iSHHL5|oYn0$MZFHtT>_M(QU=zw0BVZ(TSFDwP` zn{st(7%3_r?SpmpI^XX@$*!kYYO6>Sj_r#c+hiKsm;NN$zyteZ$=bl%`%?l9 zH9hH1KRddb)2-G%U-6m2Sjw*PgTaW^)8smYM#yr_Y@RfX3TO;B7>?@bx#w`|AUkLA zis7iwGcFj8X>pxz3@87d=QB}-Y@c%$#8`5+#bEd=lsq#d$}(7e&R8uTEU+}X7|2pt z>^m06tro|*>j?69K48slSNqABB;&o8{5eyhWDbtrA2&f2)i!pT4c~wyI*SbL}oq zf-{~Tn@3X@+1bESfWKBBa9qAapHHLQ65z~sXG)$&R{LeV_p>GC%FrIYIP8p(mVicY?9_!(s zymmZw#8Pl;Jk@g9zR03;OJm0gG>wk)>Tqvsqy5o34`e0BfWhj$pO~u?F$D5{Ndvk-EPQ%#Q z!+oZq91VHqG-^vzO~z@|m#Cwu$_#4jKw&2RY;q@hz~Qz;i4P|Xvp8YnR2gjIJ; zz&6I`y5Y5VbOVc%%I%j>94#`s;9-j4e~1aj|*9Ol$;Q|wZ@h1Wb&@Ny#Ab>dKM@H2-i6h$#SP(foh zFwIl2&qR&Rt-u1G#a>_1Ad2QmU((mkt1WFI_8Kd(3^X&1TuJk2Kn3pe=G%lv;-+*? zy^V#(DAIZ}9?XMtFd&-qVnFuzfQ>mc zs@lBac2Ae_+;A1A(*O9wi^}AkgRr?!L z<@I!jFohp(pc9m3%KwH`8O@i!32z8p`2HrWEB?_Ox)~KRnDm>eD%H5(RFV!mh@~rM zxmmmniZAOl7Ai)dBOf#~JK~d>U}t8G7j3 zRLmAbLJr(>(0J#pJLyo~yvcBT6=P}5qa{hTt?9TlAd0JX!G3G_toW5qYT*r%lrieiax!K9sxFqbd zei4=JGYb}nP*>59)<;6`ewL}86OIbudn!DUE%oXNL#sik#lR`!<6vwWWBm@n*)j^Q zan%b{$Gi3+Ea=(2F?xjSB{4pnIN<_C);#^4Sn8cBX^yD&R?T1lFTH@rpCA9{0!?y> zu(Zp`vaa0lB27r&SPwyq8Lr_WGGL=BtVGCB1C`)VJOlYe%5DNw;9-7!|($he~Fs9&wB~`0AZi$ zbcMHHq7a(Sr!Qe$oX$@#kuJUR++azKc|J#6A6c$9EZ3hb*CNZ+Xt{2(T-kCpSgvy| z*NK+v5X&{ia_wZf#^92ib{VHY8yGOy+psoIEXuEw|n|VE~E1vVHPE< z$M)4(pNZh&yRBKYuVTYcmFjg+yw^+0+LUli2Rx_Qt!U@Cnp5@k% zZsypluAx$VX_zJ1fTWpAh7u`vZ)qf7^%t^YNv@fBwECO+ezo7G7#%<6U1!JDLd`=sWo zYHNJD;^U7`Lwp8s$)B{p?no?7BfeGDnmbi>B0fFrK9!;G!TEpDM%}y%s`~Jfs{R7@ zxu~jDke-H57t_SQ$yho4RfJj1sv=1Tnwr(!;AwCmc&V9LJq>0=o7Kl)e2iIjbCaYr zFak7#N#M%nW_1GCttH}s<*m$W9_Z2<{@~m;@CS=QH+M;@)dBus%~<%mOX*S*Bql%* z4`zV{U>@k+5dpw-@Gm@0QyXUKbQelfbFK5)mmPXG#P9QZUhIWBjGU3tj-4u!S!I$ zbhBCrE(33ap)<^?R85kugTY|ZOtTsb8o;68$yx9R;})3JT(I^hX7w1j6TAyHU1(Mv ztD^#7DCo2Z^9l?F)5jvQ5s57DCom7(m4T)Q$9;yT2Th=xw&nv?f5m!vgdDA)}vZ#;Mo90|Sz7lE}8!XJzQkAZsdE;s~qtSLz|!B8+8j0f|; zkzo3MBo-lY0?Y+3fXBdF;9c+`=vWK$_7DPq^}%>>4LB0q0WJdn1arZ#!|(^26`IvD zFrdh+ItNJ7e6Rs{6V!v@N6hNj0L*^_5{n^t0d56X9yP1Q;3lvPta1zi0x|E8WAK5) zPGI2x|0u?~0XF^tgBMi5JRt{9gD=3xpwo{Syg`!W2}XbnCV|E0;U9$gFaL}H5OfCf zz`GX_033e_0l-V3Td*XxxQqax8B7B2-#`HHyIb%F8~+M_a1MAHjJOMbuqWt--TO>1 z0^A2Cfz|H8KOKqwNMwOOgLz=*`v?GT0w06R$`GJ7^yLTu<~%|G@YmlF0Q~+B_=A`K zgg=<}H~hgt74QcM4;HsN7{p)%_?LsKCV`zDRW*GA5+jhv0*5-OY99C$JPp>Zq^gg> zA1kY>8}#63h)5vhaKu4`0lMG_%uLO2ZH&5syYvx z6RfIh!OJ14S_rlcRn;=^C(s!i^d(`c8U_9p4nHuvG5o-|$aFX&@w^Ef!Q;(T^)~n- z8egvACE~{xsu~PRtyDD@e6O{t4h1)MP}TY1Klr{U7aXQn)nnj3@Gj_*sH%=(SdhA@ zY6I|RFbQm)gcbwWfmz^h=}6=WK@U~E0N(9|CIelt!}r5`)6@Z~+7?v7f#97%C^`7+ zU{zfYmJUI|!T$I<@HQAf90d=@jYp#3V0SPUoHqdl2Y;A^f`hKp;18zHK%x){x9JD~ z4xNRPM_|y*Q`Jzg>qn{@4^9V1f?t7)z!ESQ?Da8f4lV}og1>=|jo_bwnu9e!J^1mb zsyY^|{+X&S2LA%LHp2Y(HmGVb1by*u>@v_b6MfbgV*qRbPR>RE@DMl_-1WJtt^kiN zQ`Oy|emTYp_|+Gx`U(tJRJB$lo(*7I@F_SDtg!+u2X+G2f-}Gak?9zfNL+{DJopM! z!CFz0RPRd!0B5X30I&j_2M%0?0N^t402sR({@{;m;Sc@_)@mY2Pr$Zd=sNg=Ip92S z&sXpV*Q|$sIuh5AxDL8)Kmf20SgR>ktSzWHIAuF(4rYOi!I*E+bl{3Sv>f;VdV70xN=U`j#F*q7@i$TkP5#T;B35?wbf3O0~0`vC6AMAVp^Zzsw za}Oc_xcD#vG{-b4LIBVcKaxoTZyrMcaPJ8O05=sQ0C)sE4F>%He^5RR{}#C6Pw)qi zfk|LV3H-sp^Y8~dgL&Zh=er;P5;;F30NCOJ0<@H*$6y3l4Lju|@YBl(0PgrjRhNNn zuVe6mdEhJX0H-+1^=T}pIm?m2Hj$IK#98(wnaiE!Abcn7;sQi*m_Pz23T)?8f!b^k zF!45l7(Qi1xxi=a;tK5MFhDMA!d+eEKzx0dDx?S5Ah3(K2{`g8fmU2DkjXAp027B* zL1F4~ipVYHDFWwsxquVrSCQ*bI$uQ2VQ(KZtD&-vJ>6tSd;{s@h8vpuadS60P;U7F zySmE$JXz>Q@eJr_K7T22llKVAyC3i+SUUVP*v$JQL>PD3Q7#?K4TIqqg$%x3jd6#= zcJ3{(foA~nks&2;_1RApg0Ze+ZQQoy3b@ zXC_~0I&p}=B#r}Qbpv;Gfx%xe7|9E)nhgRoxkwU*fmmK3 z5Xl<^{JBWLnM(or&kg*rCgQK~#OlN$I*6WVq6-jR<6#iNb%8(#ZxHB$A8i1GxKxL> z>cmd|=mPg#Gmo!_*%IrI;h)S25XztDS|{6lA=}RxLiRkDH~VAecje>A;=c^{1op5~ zO((g5%R~xnV6tz0QfqqEM*< zz1Sd>9~${)RaCOAw{`j3|A}f17;j><139OC&j^aJg;pa{lg~^M*_#fdh zfPLyfx|U-EzT@6?Fov=@P2?K!DuGM9R|q}$Mjb5pN$eB~;bE>Did+xw9x8{^GENgh z7hWZ>j`xPbp$Xp*xf}c%ke|76U|rmBBe$yyX#o!cv=m5YS(OD+{S z%Ty0GuYjZ}LL4h57Lm-r2 zH$bpn91@1yMUDexb24{rB322kf6lx>XsYoBfx28Iu$W5))-pAOd1(sQZir%*a00TJ zf};egat7eAu)oSbdSW6MHbf`J^Kl`J|3KyNAX&FE9I`R&6pkn_26DY{H05?qK$e1e z6j13sY~-Iw+&&Tyy7l3*Cn}RK)Rnm;9OWL%e+#T;U4%v0N?D_^T;{8Q{NE4xMPm$U=SkeY0qPPJiHCMmZWW2qSIDCxVM&|;$ggJc z=17zxgO3a8F}@cm*OC8BW7jB1>u^{UjPA|ht|IHjsmM}mHVCxkZ35f*lt5oD7g)nC zP0-}DP-V3$)`tUl51YY>kcpuvU|@rQf}bJ*>-dyFdoCByvrAK;2Zsp^FJ;)OHG|i54ik_$QQ!cl3XEfeKwaJj z$WNE^56$5H`*MB=;)e+?(GdT>f*VF7>&A)5;sKf}Fo+ETOL!aL@WpDCJD@O?2I6h& z&T4)r9CFzu1}11UfdWnhLJr}DWBNP$gh`ftf_T`!f^#)C#9&PM@D73bToNO9(QVzR zsxl00e|VTlxp*yGZ)(z9zU^*m5-922!xRT^(xnkq39X0xY$!#ap9PI3EC(-QV zXeZ7jCp&xXU|G6k3uHS{)<7$Ot?1!eK3=2E-gb(tx1HQ}er$xDe2kW#s?l0dL>t2? zUF4v+3_E+<*)X<~+fIdT*5sA7itXflgh{__XKp+8^}tSUJMi_lo!oZR%XYNOR$beX zF53|zum>_Y?CFFOS{S~Wa$@^e>b_RQ#0F9CflJU8*PV`Y=@HyE3B&(8kyH5%XJfN zXO8x2CxmRLjEc0p?Of3*EpIzXRHEhIoEL*x^L-R9n5@=_Ef zaX7?Ymgfb^f5-)kx>Qx#$K@mOjmALMjRKx<;wTg_nzxDEZPV3JD5vO;aTDavT`1V} ze1@D(G})9kOYY)8rKX}e@|LEuw4KN8kQ?)r9kM5H-62Q0*cv97OLxdET;3d#=8&Dp Q&UUueakgpLPWgfSKl^1tumAu6 delta 15720 zcmcJ$cUTnH8}~i;015~S3apDt5fBj+L^0SwMHj^cdx^1PK{56k6^(TRM0C{KnrNa? z5;f{Z7h4o7B=%S!cB2NOu|!RXW#{>x-P!zf-}m|R;kww*Id_}W&zXf&c*ni)j(hGo zw}d9LBz_W>lpON*c|+FBe^m15s?VMYl~dPbQH@b$E>*+*!za4M9~oy_DZ5sq>&gaS zo&L@Zn^%1M+E#B@>!&1LSI+zDGVR(_2kk@6YoLSNZa>07{zS8%>L9n<&vuZ%u-W&O zavc6F8MuHLsCG;vC>PN#3G z`IS3p+bUh4?VxGBI=tJYU6na+Y3n*@dnr4i{ZR8waL^7_ZtHYz>6*5;vO%X)s#o{Y zf1*joI@m8z607UIS2bo z3h8y3C7QO>L0hKD%N^u@YI4c&ZY#afJD;0n_OYNx87f~iE*$AQ3~`r zeYmDIIA~ibPxa_+y{q>?2TgY+*k7mbqxnsB(55S0-qPkeXh$n^ptYBJi-UHoveRFu z1o^vqA9m0zRBppBOM7OqgLb3hT|=keqG_KvXpbw2&=zT0*W`Cw_Np?jhA#Q0rVVn? zKG)Y!bsJcV|- zrd{NqU8MvE>GbO~?Mesj2Bk}o&TW&X-JVhB>6#J`j}U?k{3Ee z*kZaJ)UZmGeR(7qay;8w(Q=cgwJO= zB<*WZL4r?Q<#EEbWmUy5Jt(oKP(<4lzmBykN`caVqpE7iN-8#FCAb=zCY_rch^Ive z;~1OqHk9auEWg7L_0-{LeudMcwf4oo9gNiV@ zkAxwsb75AGi-xR8rHNe|s%zBtL0ez8SW_r<$gn`^MLU#THK z?VuDZb*ZL8%W9C>RBKs+Gfh+auUzh-w!veJUTCcHB0j&EqLj#0ZRrbT%&I7ws;phr zoZ2eIt3IdW%J9|QXr{7%bu4vP9<2_gI8(JX$BEi0C2N~dOT}wlJ1SIqtm_=Gr6=`qF)1O&KQjlT(;fa;eNplKdL+Oi8Ntv{#4Q({#?-^J@^xDCu zQb!eTk=cmSgu~qDGoIke4@rM738A&t>J*RXtrb z-M_k?sH(E?db0dXQZ8Iiq0Oei8~#Ldm1Z{^Qhz1mW)HeyI&w3=BJEc``8^nm!Mfki z&^c2^X*Z%Q<#1UT4OQ;rv%cc-$9?LpJo_V;b}RE9BvYnx=7B$rFqJ(p%Ji)=;ZbAS zu57_)f^z*)Bn>gSJ$~)v!zkXq>U!(ksPwx)%b|+?*>0aRG89oZMVtFp#WvHOXD$_J zr&9WF9h9WX%h_V8z4W2V%BGjoWXlaD=v6p z7ivX=dA|$Qrh0tCh3b$Oqv2-LeqK<4+R<$OxdJVus@$z2EuuueR*{-fKi0WYV`|JP zt~8O3aDgjzp&4AwjqcG}{@0BrQxcDLrvwV;o$iQPiHqH-zI*Af*7}qd4(8kL2G#U9kynMSdvH+7?8^B`}!F1xqBpjkIJ8+<6;nJ)9L z>NE#+XsoAfy2b^1I$FKiG24R)xPw z=N|J)$?_Zuc}kW`f1%E5*~<#gRI9L7GG_!(SaKwCiCxr526gvXRaFyHQ*vB%LYAsd zidT0}g{&9Gr!z#o)Jb*KNwd3P8+&m@lHgQ5*;vvUYg>-z-7EZS0IjK}UX`Q?6|Gy> zg8(sqA6?}|f#{P8{9Pc0`~P)W6lH#0gcTF?=Sr%YY&@Ql6;{Fz11a8n3-nzRdn6l+ zIvX)nVCN8ukl!5T=n$$)zjAM6X)k{&pzziZ3Zrp+ zLEwFJc?flPlGQ`}emK3R3*4zLb*3ZcRdq>El+UIJ44)C~QjbEY4M)^NcOK#IL~bpg ztw-bODz}NGaEj-VkyM{<@XAP<>^f#2+9b!fg#DuEw0p@;ZCvc;KclDzMrzyo)Y!-O zjD+(+{{lnK{DF_fs^i@j1IRpm_R_TQwjP8sM)6 zG>vw0Ml>onl$S=+Z26&?ePT$VNxUV7q9}$h#ZbS1(mfbRIW8{&H2WwN5e4XKMciL| z_=ASjhqiKFLuwg*!wjW;s%K+k5OW+g6fSXJY_%#&Pu<`h$yA3M#ZtNaWRJOiBT6S) zz}%RkeXr)hC@aS{MvfSaXE6RcZob->i2CrgIQo({@QfxDNJq`s^~(wExICW5cuqli z_SzogJC41ZQkZ;yJ;yht_c8hwHig4v-YlfIckr2}v;on^Hp8;hiq|)zEIPzd&8b$6 zZ@#w`@p-J6ag&nJ;5#g$!Q(n`T5}4eX>4pxfi=cxcFS#c{{OS<$48rE!3ky87BrB~ zae52-)+cPc2%B`+a5AZ|qO~zx{LSGl@t!LG_MO?SH9a7osVM!v&>$G*#MN9S&@##F znn>G-Dl&HPGl9+4*b0|iPZX}oynJh<`Ke+$<-`S;zix|;pdfzJjyljsoRowmOEPC9 zVTqJqZRF3|Q(G$HGwo44=4u_VNR8p{9cYgH`!2rH0n6hQ9$=skD2~53(73AIcR9@F zwj7&`@%uIRO{N6b3tw4_+L^yfruH>=iX7(jy%6hCRYUZDU~|$_4jEyT{QRpfI8988lQ`(N#bxQ&OehX zVN;p2)+!5vEZ#2bXOqQ4Hr6g1Vv~)9EWs`tV3Q?4R^2We%C23=)H-&VtpZhRT6_LI znCw8|T{Lmi)o5fR&hv9;7E2TL&|=|>`%AGoU9X{Z*<9URwJSN}kYLtzBOTE^j_ywN zP|?2KF~bshc6TfV(dLcasW*9MBCdV7PGh&8G+H0INCcbTTXg5#g98C+Qe{-Q8ZYii zegQhDOAGz1#W-v*_9#Rd@=#b3!ll*nIPdUi6G; z4)^PWC2J0U+lP`U!Th8T{o?F?BhzN>JBv^E$5OVRfA5c2jm+)?XoxJo%H}bHD4#lT z-NC3%UG6rRTFa$bylgP)bAj^*V_F>G>x0R^+pa8BA;))z6>-*_eK8pP8YRz~A7dS? zzT0dTC+Aq(PYh(KG~peKO*V^7+;Ir`yRNn6=5odmdJik|#v#|NB-M zG0W!^vN_!P=cCOV7U(G?&K> zC*MA^H07pul%qB2;&-I|HR-f>q^X*8$UD*wd~-PcKwp`cji5m?eZYT@L?8Y$k3Sqm zde?jNMEAr^;2EQ^9{$2>M^PIr1vf`gO}Ec%x`$KQIfEw9CZ3u>0R(LZZKV=!HyUF& zhewX4uP|plKc+WCYs{6#V(FwB%;Qk+hJ0omMPh|{IS!lW&m1})xp|yA9?Q@uo-!VD zzawuNkK@fjj-7z9vz&WQKsnrb@&sx@UCpKm)QhOLxzZ$R;Y4m`!&LGlI>|k!QK0Vm z6iIuzJblC>wiR&_dNGQ#r(uO($5*GJD!t4B(`ldV(|8t^(purx%Eo^r(9*;YXV5Zg z!EG-;C}1DspLpQ4cUWDk(@k#m86{GhdG=@2NR}UU;oaFdcvR-!v&lf) zIVK02PZAFl@aEhctQbqoTXN`A@@tu9-ETX7C<1vlLJo7PjX7a4-NY-SIcN!y?B02x zHu$G-q(U*|%l#BIrmJ~|f^#NnbZ!|I_zd=5P9NcnI%YY2={nuo7UHb20?R-(bJ_}; zL4Awyod3Q}_*p!Z&Z)Ps@F*f}oIe6%{y}Tx7rd2^Mt<5``9S0|-pW@&egHRHiEeJi z{a0c@`0*k@e%zN$D`{xeeuEu$mrh)773O7K{$v#f)%)g(t4Su0lf6Y5lEfDsq3pYc zGH_J+bPa8H&+nzx|1dXOO9yKDATKtc+h;85gW=-6Zy#Cr$GF!$x#~KaN;=M3hb=k8 z{BRw4%9R&)f2-P`nk%lSJA^6x#|An<8Rnf|kt(D4c5cEOLO9>wgmvX*BM$ur6-qZ7 zzM;zGcOq7j4mpXXYvmG)co`Niv4hMRo9Sz8xE?6D%>bSx|Ot3@du!B^=&9!wfil5Wc%#BXa5K3b{K`GRL@1CHIu6F{hy3aZHB#ohn z6@_#L=ghN(^h4k(FBHL96k*gDYZ3enSv~Tzk~Ugj$XD}MMHF9oa^zbzO*fYoQMwc6 zXV=p>4ZR5GX{YHAT~#q#j7cluz7mah&UTV^Hcvl;eOSI5$tTa!OteSRIl7JM7Ji<- zpelUgJT)FUm1zo;7clO$JRjio4k21x{ zIQ7i(9R2^}weBsioVe~V7sZIfwoo<=GXNpFi4Z{|gt5S2{Kb%EJ7eHz4a5HY@nwqj z%zOp=TEafd<`nkpWx!U@fZT*~O{Tyrk9BlpUZvAX;{fx(_)+59E<1N%M_u=dZ9Z@t_ zJkrqATK-8PhLbMOVJLp=b;^mW8ipL|b?zUmT7LhNSJUMAkmu%N|0qo}G;$8ZV3H=f zl$LYx6^a@0OQ?Npd3F~)8&^RTB&X%Y|Ku*{-UpauN$YXCbv0z+S>mg&8`FZM(p6op zKF)Z;p(==5+PjBU@a%60WFhDv1X(U)d2BKHxt7^-OpRLA8hyNSKv{x8=R+=h` zfOm%+-^b`A@kWH|UAqLO5eGnV2t=Oo!h|)lG74%ix_oc-aglAgB9Y5-IWh&XmiEsO zdo?R`Lv^rhB^}QEu~4)lLZu$Cs97$Z;e>H}&-!Rc^Y&R(>$JmcDM!=!*qd%5YF%`6 zSZ-pk#Gc8xwe=X|bmlpN4`T7k~eSD1@RkbgEN8+~`emmlK zIzN3z`@`m8!J7M>sy5%QsyX-_@9-NA{dhkAoW9nty{M}0S5);SIQf#QMqXA`1;4}1 zIWNdmF|%fUi<(_YlCH&C)E~fyU_bEhMi%uHxTeF&z-SyT@XNm>O)fdNe{Y6`dq z%m7ElBM#`+%%W}uBfwMOn&$8aOF<7$Novs={$TS2_qV!D4VLSicPd zfM0?S!3Us6Wl8$9vqfzTR{FrAb_X*sbS8oY;4*N)Pz+3PFIWsd8fH<;!B!(IYIRJ* zl_M=`Ja`Z6T_sbJf<{@?sStbtt^|*P`QX`)5db9Yq~+jRusZfv_pt~727|r9!QfQz zOK>H49Lxvf#=#%l1eSvzjkl;Zy(K9ZYylnx`(+{#GQpzG25*7u!HkI(^)R>tyal$K zWKpH6lJpu30y8FC)C4dO90>kC1^(cmITm#z*ydAD`AX95r4}^?yrIA!{Cb%sQyq&$)#V5P7O%h{1k+bq)Qeyl z_#9lj%A)%CNz$~{=zFl|8uUH*5S$2p{RR3S3|S9<(0K!z9!v(yLGxGWI-Mk40OP@) z8_{)OgDsgBbp{e2err+Jg6ZF(>A^``(R5(z?P$8{l5_wJ1=sAfsO>=SU6{Av)gLVC zJW$$=rUxtSLDPfL;9YQy8UA`n`X(R#;0v%F_zG)z8rV2<9|9mT7TgHl1doAT_agu} z26Xn9r2SwhI0}n#JMamZ2G%$Tf3OX>5$pjT14n>&!A#J(h9s>3L&0reJMa{k24-GG zVjdFr!HwW^@EE9qcR}|b5uhgKEf@-R0Na84!8GtRI1j9L2>xI)cns`z*rJw#EekBF zYb{Ay57q@OpaJZ3#G;OuOv1mPR+D+mAv6e9pw;RXVLXK%tEeE&E2gR8+)V9H(igA+gx9OqYnQQ)s& z3K)A2{+UQjLn0e|25tq1-A4fMIQS6UQHlVyp)W%KF#iDpfKHDQ0K5!lga15(Ke*}z z{K1*!@CSpjv3OvMKLAF7KF+F|0uBQ+Gmw~zL^e3vMOC+g-W62!6qp1)1RqpXRS%pU zCcCO?6xhNI0l@iS26!CI28X!AA8b_x{-Eros?WhF{Jo+&&RZv|scJkp#z$3qgFAfH zOm!*}Pjsrf5{&j&)qLk}$>Ok;lYgL^M`X#FBMsN-e!pFd0!Mk8YvZ^}cJt(A;s@4Ucfhl0m z6toz45X=TWGdrWngrKXcUId+cpvk}pocgQRlcc46RkZ~e_#sLT%KcGt&}o3Gt_KO< z3myiifw#c4!6G5;GIRkaX;Dfqi~DOfKHebxYD0IUn<<{$ug0~`UK`&?C*fxqRd>JQ+E zB^WENT)qMU!0L*%%~-5hn^ALc$+xIExD{Lk_V^A>2mY`XEeBTIhG`1+0zDc@ zQd67;qrmxK3V3EG1|9fh7X}?T>j#WEu+whL|5HeOzXt)pI5Pq?mZTyu3Va5pfVJ`w z0PFx}gX6%hVC-JZbFd%y5L^Iy#Gz%tDDYP>1su2!{$Ta}@CQ$UTft!m)J*jh5^D}3 z0J!B40yM!iDL?=)2LCma0$PqC09bMY0l?#h2msyzPl2s}fO2R}cXF=~uihf+^Q9 z_`n0;Yw#40bCtts5wCKUqk$rk3*x7)vW{xAo0}YnzpOG8^37k=x7>0v9VWq`MqIzq3(DuXCQjIW7_i{bc*jw1xFaB?LS zrag}nx$k+2z!Tmn5XR>#$szc|@eAafN_tv2Fih5SjEC$@k2uZ)4-DwTJw4!7mjV{4u?UCmep_ zNdg7D9FXq};8|5*aZXsMd`ZY$26BHP^Qw#xJ**i&j;buX;*03G$|!PE?o$~dQh1uc z0A3}8YxtnZ#q)K6jr>NSkZV-|T5wB&i~Ny5D9;o~si4m zn>;GIN;qvvY3`Dg!`{_k{U9wd;*b8Ny50$aF1;27Tq$LpV`jF%JUdz^{0u8w{SqU>uv;yZn)g`vW?fnDvKFd4oD3O-aJm2%G=Zg@C(xXW1XgpI zzzKE>0D5zTzyMALXKJZ$$15*9yY}t9o*)Fg)-me}pU*^GqSFP?f(B(&l_H3@#)2wovY7sslXYU_h=F z#BJ(e5I*Cfbzt))8-?-?=Ltk`kw70VtApa)X76x#xJGhpIGV++0rvzke5XN-zc;TE zn8ka;5$8j`E^TEd^fjM*?9yQ=l=g6Bx_~1wQ5L0;l%Dsqvqkw(fG|DRMBd~?131Acm?Bcxwhqy%GJpU{3 z8|&)>kGQG8EA9ix@=%^$A0=qWtAunJ?-eNK5`l;OufPn}HvoR;rUEy)kH9IOCUA>a z2{h)t0u8xD;2-`Mkac6&KN>^2?ilW07j;RE#+Kcc`$S{(-QxMtungu+fLwDbpMWK{ zg?mDJmtA7y5V_iPt``GoTTYIFk;^AMQe+#l5n1ZXc>?{oNZ=pf-DDWBQ2_$h5AbT(6 zKN`Wi@=|thjOumbh{h0CUd|mwHj2}c#rA0wn8|qp-*OS)v}?7>15lU>{qU|OuVME% zI2_}MIGCW(1d2Hw2)=>W4g6>NTc?B!>nTBO^{?R^&3SPcQ?YznAeW!U$sP3hU#qGN z1N#p)Gif7U%66E$G?8z4^4KPFkhx(y`7veUOKPi?vu10*6!w3U+i$BmIoR88r8&mY zZl6gm4))q5vrNez$bP%bRlBofFMlO1AF9!AUsub=Imqqz$=W)|J81c?8f^u|>ylm3 z%fZ2ZeQce{b( z*{^ij<@QTa+SRT9n$v!LD@40;WVg3p+-hZ$XG-=CYpWS{*Jzjb(emjU?Sbs_(VE=e zU-klxb+DhP>S7 zNjXnp!S*{&_DOHQ+hm_B&V0M0{GR-z#O&WmuI!R&zujcN$7HAd{*wK^()x1SVr4Bf zKI}J@jM_aR``x4^THbyeX_c0@-#^-*<+U3}JUms_yVme_$fPWOHe)0$6|A@PM zBdk4vjQIzDt5PMs<3l#Q8H|#A^Wy#ECY4|#$1?z_bw>Wty3h2XmB6rSQG8E+$ zT`@94{@e}!S^DoJIg{`YF4LyS9h~TfxnR1yIaYp>$0N7N4czUm@}z{n+9o&QmD^-5 fF5M=_xczrmnuE8?@45AMwN Date: Sun, 29 Sep 2019 22:04:11 +0530 Subject: [PATCH 004/289] Update README.md --- README.md | 86 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/README.md b/README.md index d2a77ba..1f8bd33 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,88 @@ # Standard_Operations Standard operations required for FLO Crypto, Blockchain API, Supernode WS, IndexedDB + +This template contains standard operations that can be used for the following: +1. FLO Globals +2. FLO Crypto Operations +3. FLO Blockchain API Operations +4. FLO SuperNode Websocket Operations +5. compact IndexedDB Operations + +## FLO Globals +`floGlobals` object contains the global variables and constants required for the operations. Make sure to add this object before any other scripts. +`floGlobals` contains the following properties : +1. `blockchain` : Indicates the blockchain (`"FLO"` or `"FLO_TEST"`). +2. `apiURL` : Indicates the URL for blockchain API calls. +3. `adminID` : Indicates the master admin FLO ID for the project. +4. `sendAmt` : Indicates the default flo amount to be sent while sending transactions into the blockchain +5. `fee` : Indicates the default fee amount to be deduced while sending transactions into the blockchain +6. `supernodes` : Holder for the supernode list. Can be updated in runtime while retriving data from blockchain using API. Stored in the Object format, + + { + : { + uri : + ...(otherProperties) + } + ...(Other Supernodes) + } + +## FLO Crypto Operations +`floCrypto` operations can be used to perform blockchain-cryptography methods. `floCrypto` operations are synchronized and return a value. Contains the following Operations. +#### Generate New FLO ID pair + floCrypto.generateNewID() + `generateNewID` generates a new flo ID and returns private-key, public-key and floID + +#### Calculate Public Key Hex + floCrypto.getPubKeyHex(privateKey) +`getPubKeyHex` returns public-key from given private-key +Arguments : +1. privateKey - private key in WIF format (Hex) + +#### Calculate FLO ID + floCrypto.getFloIDfromPubkeyHex(publicKey) +`getFloIDfromPubkeyHex` returns flo-ID from public-key +Arguments : +1. publicKey - public key hex value + +#### Verify Private Key + floCrypto.verifyPrivKey(privateKey, pubKey_floID, *isfloID) +`verifyPrivKey` verify the private-key for the given public-key or flo-ID +Arguments : +1. privateKey - private key in WIF format (Hex) +2. pubKey_floID - public Key or flo ID +3. isfloID - boolean value (true - compare as flo ID, false - compare as public key) (optional, default is true) + +#### Validate FLO ID + floCrypto.validateAddr(floID) +`validateAddr` check if the given Address is valid or not +Arguments : +1. floID - flo ID to validate + +#### Data Encryption + floCrypto.encryptData(data, publicKey) +`encryptData` encrypts the given data using public-key +Arguments : +1. data - data to encrypt +2. publicKey - public key of the recipient + +#### Data Decryption + floCrypto.decryptData(data, privateKey) +`decryptData` decrypts the given data using private-key +Arguments : +1. data - encrypted data to decrypt (Object that was returned from encryptData) +2. privateKey - private key of the recipient + +#### Sign Data + floCrypto.signData(data, privateKey) +`signData` signs the data using the private key +Arguments : +1. data - data to sign +2. privateKey - private key of the signer + +#### Verify Signature + floCrypto.decryptData(data, signature, publicKey) +`decryptData` verifies signatue of the data using public-key +Arguments : +1. data - data of the given signature +2. signature - signature of the data +3. publicKey - public key of the signer From e2948b1db565f8490002bbf8ff266f88f9b8315e Mon Sep 17 00:00:00 2001 From: Sai Raj <39055732+sairajzero@users.noreply.github.com> Date: Sun, 29 Sep 2019 22:07:01 +0530 Subject: [PATCH 005/289] Update README.md --- README.md | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/README.md b/README.md index 1f8bd33..0115093 100644 --- a/README.md +++ b/README.md @@ -33,21 +33,18 @@ This template contains standard operations that can be used for the following: `generateNewID` generates a new flo ID and returns private-key, public-key and floID #### Calculate Public Key Hex - floCrypto.getPubKeyHex(privateKey) `getPubKeyHex` returns public-key from given private-key -Arguments : + floCrypto.getPubKeyHex(privateKey) 1. privateKey - private key in WIF format (Hex) #### Calculate FLO ID floCrypto.getFloIDfromPubkeyHex(publicKey) `getFloIDfromPubkeyHex` returns flo-ID from public-key -Arguments : 1. publicKey - public key hex value #### Verify Private Key floCrypto.verifyPrivKey(privateKey, pubKey_floID, *isfloID) `verifyPrivKey` verify the private-key for the given public-key or flo-ID -Arguments : 1. privateKey - private key in WIF format (Hex) 2. pubKey_floID - public Key or flo ID 3. isfloID - boolean value (true - compare as flo ID, false - compare as public key) (optional, default is true) @@ -55,34 +52,29 @@ Arguments : #### Validate FLO ID floCrypto.validateAddr(floID) `validateAddr` check if the given Address is valid or not -Arguments : 1. floID - flo ID to validate #### Data Encryption floCrypto.encryptData(data, publicKey) `encryptData` encrypts the given data using public-key -Arguments : 1. data - data to encrypt 2. publicKey - public key of the recipient #### Data Decryption floCrypto.decryptData(data, privateKey) `decryptData` decrypts the given data using private-key -Arguments : 1. data - encrypted data to decrypt (Object that was returned from encryptData) 2. privateKey - private key of the recipient #### Sign Data floCrypto.signData(data, privateKey) `signData` signs the data using the private key -Arguments : 1. data - data to sign 2. privateKey - private key of the signer #### Verify Signature floCrypto.decryptData(data, signature, publicKey) `decryptData` verifies signatue of the data using public-key -Arguments : 1. data - data of the given signature 2. signature - signature of the data 3. publicKey - public key of the signer From 268ffe4197aa866deb01a3132d1692207723c37a Mon Sep 17 00:00:00 2001 From: Sai Raj <39055732+sairajzero@users.noreply.github.com> Date: Thu, 3 Oct 2019 00:20:20 +0530 Subject: [PATCH 006/289] Update index.html --- index.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/index.html b/index.html index 29d0b25..3f8a7d1 100644 --- a/index.html +++ b/index.html @@ -82,9 +82,9 @@ /* FLO Crypto Operators*/ const floCrypto = { - //p: BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16), + p: BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16), - //ecparams: EllipticCurve.getSECCurveByName("secp256k1"), + ecparams: EllipticCurve.getSECCurveByName("secp256k1"), exponent1: function () { return this.p.add(BigInteger.ONE).divide(BigInteger("4")) @@ -5933,4 +5933,4 @@ } }; - \ No newline at end of file + From 2ea373ef2d1f651cef88cdb45aa6a897fb62b746 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 4 Oct 2019 20:31:56 +0530 Subject: [PATCH 007/289] improved reading floData via API --- index.html | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/index.html b/index.html index 29d0b25..39da444 100644 --- a/index.html +++ b/index.html @@ -424,7 +424,7 @@ }, //Read Txs of Address between from and to - readData: function (addr, from, to) { + readTxs: function (addr, from, to) { return new Promise((resolve, reject) => { this.promisedAJAX("GET", `api/addrs/${addr}/txs?from=${from}&to=${to}`).then(response => { resolve(JSON.parse(response)); @@ -435,7 +435,7 @@ }, //Read All Txs of Address (newest first) - readAllData: function (addr) { + readAllTxs: function (addr) { return new Promise((resolve, reject) => { this.promisedAJAX("GET", `api/addrs/${addr}/txs?from=0&to=1`).then(response => { var totalItems = JSON.parse(response).totalItems; @@ -453,12 +453,12 @@ //Read Data Sent from Address (if limit is specified, only return newest sent data) readSentData: function (addr, limit = 0) { return new Promise((resolve, reject) => { - this.readAllData(addr).then(items => { + this.readAllTxs(addr).then(items => { var filteredItems = []; if (limit <= 0) limit = items.length; for (i = 0; i < items.length && filteredItems.length < limit; i++) if (items[i].vin[0].addr === addr) - filteredItems.push(items[i]); + filteredItems.push(items[i].floData); console.log(filteredItems); resolve(filteredItems); }).catch(error => { @@ -470,12 +470,12 @@ //Read newest 'limit' Data matching 'pattern' readDataPattern: function (addr, pattern, jsonType = false, limit = 1000) { return new Promise((resolve, reject) => { - this.readAllData(addr).then(items => { + this.readAllTxs(addr).then(items => { var filteredItems = []; var pos = (jsonType ? 2 : 0); for (i = 0; i < items.length && filteredItems.length < limit; i++) if (items[i].floData.startsWith(pattern, pos)) - filteredItems.push(items[i]); + filteredItems.push(items[i].floData); resolve(filteredItems); }).catch(error => { reject(error) @@ -486,12 +486,12 @@ //Read newest 'limit' Data Sent from Address and matching 'pattern' readSentDataPattern: function (addr, pattern, jsonType = false, limit = 1000) { return new Promise((resolve, reject) => { - this.readAllData(addr).then(items => { + this.readAllTxs(addr).then(items => { var filteredItems = []; var pos = (jsonType ? 2 : 0); for (i = 0; i < items.length && filteredItems.length < limit; i++) if (items[i].vin[0].addr === addr && items[i].floData.startsWith(pattern, pos)) - filteredItems.push(items[i]); + filteredItems.push(items[i].floData); resolve(filteredItems); }).catch(error => { reject(error) @@ -502,11 +502,11 @@ //Read newest 'limit' Data containing 'keyword' readDataContains: function (addr, keyword, limit = 1000) { return new Promise((resolve, reject) => { - this.readAllData(addr).then(items => { + this.readAllTxs(addr).then(items => { var filteredItems = []; for (i = 0; i < items.length && filteredItems.length < limit; i++) if (items[i].floData.includes(keyword)) - filteredItems.push(items[i]); + filteredItems.push(items[i].floData); resolve(filteredItems); }).catch(error => { reject(error) @@ -517,11 +517,11 @@ //Read newest 'limit' Data Sent from Address and containing 'keyword' readSentDataContains: function (addr, keyword, limit = 1000) { return new Promise((resolve, reject) => { - this.readAllData(addr).then(items => { + this.readAllTxs(addr).then(items => { var filteredItems = []; for (i = 0; i < items.length && filteredItems.length < limit; i++) if (items[i].vin[0].addr === addr && items[i].floData.includes(keyword)) - filteredItems.push(items[i]); + filteredItems.push(items[i].floData); resolve(filteredItems); }).catch(error => { reject(error) From 9bdac8b0424716552ca29351e0e5a860438483a7 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 4 Oct 2019 20:34:26 +0530 Subject: [PATCH 008/289] fixing some bugs --- index.html | 4670 +--------------------------------------------------- 1 file changed, 3 insertions(+), 4667 deletions(-) diff --git a/index.html b/index.html index 39da444..4d6c1a2 100644 --- a/index.html +++ b/index.html @@ -28,7 +28,6 @@ use console - - - - + \ No newline at end of file From ae71390df4ed6cf0654bdfa700a9ef810c6ea287 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 4 Oct 2019 20:35:10 +0530 Subject: [PATCH 009/289] fixing bugs --- index.html | 4665 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 4665 insertions(+) diff --git a/index.html b/index.html index 4d6c1a2..8808880 100644 --- a/index.html +++ b/index.html @@ -28,6 +28,4671 @@ use console + + + + "; - - mg_send_response_line(nc, 200, opts->extra_headers); - mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked", - "Content-Type", "text/html; charset=utf-8"); - - mg_printf_http_chunk( - nc, - "Index of %.*s%s%s" - "\n" - "

Index of %.*s

\n" - "" - "\n" - "\n" - "", - (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2, - (int) hm->uri.len, hm->uri.p); - mg_scan_directory(nc, dir, opts, mg_print_dir_entry); - mg_printf_http_chunk(nc, - "\n" - "
Name" - "Modified" - "Size


\n" - "
%s
\n" - "", - mg_version_header); - mg_send_http_chunk(nc, "", 0); - /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */ - nc->flags |= MG_F_SEND_AND_CLOSE; -} -#endif /* MG_ENABLE_DIRECTORY_LISTING */ - -/* - * Given a directory path, find one of the files specified in the - * comma-separated list of index files `list`. - * First found index file wins. If an index file is found, then gets - * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`. - * If index file is not found, then `path` and `stp` remain unchanged. - */ -MG_INTERNAL void mg_find_index_file(const char *path, const char *list, - char **index_file, cs_stat_t *stp) { - struct mg_str vec; - size_t path_len = strlen(path); - int found = 0; - *index_file = NULL; - - /* Traverse index files list. For each entry, append it to the given */ - /* path and see if the file exists. If it exists, break the loop */ - while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) { - cs_stat_t st; - size_t len = path_len + 1 + vec.len + 1; - *index_file = (char *) MG_REALLOC(*index_file, len); - if (*index_file == NULL) break; - snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p); - - /* Does it exist? Is it a file? */ - if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) { - /* Yes it does, break the loop */ - *stp = st; - found = 1; - break; - } - } - if (!found) { - MG_FREE(*index_file); - *index_file = NULL; - } - LOG(LL_DEBUG, ("[%s] [%s]", path, (*index_file ? *index_file : ""))); -} - -#if MG_ENABLE_HTTP_URL_REWRITES -static int mg_http_send_port_based_redirect( - struct mg_connection *c, struct http_message *hm, - const struct mg_serve_http_opts *opts) { - const char *rewrites = opts->url_rewrites; - struct mg_str a, b; - char local_port[20] = {'%'}; - - mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1, - MG_SOCK_STRINGIFY_PORT); - - while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { - if (mg_vcmp(&a, local_port) == 0) { - mg_send_response_line(c, 301, NULL); - mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n", - (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1), - hm->uri.p); - return 1; - } - } - - return 0; -} - -static void mg_reverse_proxy_handler(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { - struct http_message *hm = (struct http_message *) ev_data; - struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); - - if (pd == NULL || pd->reverse_proxy_data.linked_conn == NULL) { - DBG(("%p: upstream closed", nc)); - return; - } - - switch (ev) { - case MG_EV_CONNECT: - if (*(int *) ev_data != 0) { - mg_http_send_error(pd->reverse_proxy_data.linked_conn, 502, NULL); - } - break; - /* TODO(mkm): handle streaming */ - case MG_EV_HTTP_REPLY: - mg_send(pd->reverse_proxy_data.linked_conn, hm->message.p, - hm->message.len); - pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE; - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - break; - case MG_EV_CLOSE: - pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE; - break; - } - -#if MG_ENABLE_CALLBACK_USERDATA - (void) user_data; -#endif -} - -void mg_http_reverse_proxy(struct mg_connection *nc, - const struct http_message *hm, struct mg_str mount, - struct mg_str upstream) { - struct mg_connection *be; - char burl[256], *purl = burl; - int i; - const char *error; - struct mg_connect_opts opts; - struct mg_str path = MG_NULL_STR, user_info = MG_NULL_STR, host = MG_NULL_STR; - memset(&opts, 0, sizeof(opts)); - opts.error_string = &error; - - mg_asprintf(&purl, sizeof(burl), "%.*s%.*s", (int) upstream.len, upstream.p, - (int) (hm->uri.len - mount.len), hm->uri.p + mount.len); - - be = mg_connect_http_base(nc->mgr, MG_CB(mg_reverse_proxy_handler, NULL), - opts, "http", NULL, "https", NULL, purl, &path, - &user_info, &host); - LOG(LL_DEBUG, ("Proxying %.*s to %s (rule: %.*s)", (int) hm->uri.len, - hm->uri.p, purl, (int) mount.len, mount.p)); - - if (be == NULL) { - LOG(LL_ERROR, ("Error connecting to %s: %s", purl, error)); - mg_http_send_error(nc, 502, NULL); - goto cleanup; - } - - /* link connections to each other, they must live and die together */ - mg_http_get_proto_data(be)->reverse_proxy_data.linked_conn = nc; - mg_http_get_proto_data(nc)->reverse_proxy_data.linked_conn = be; - - /* send request upstream */ - mg_printf(be, "%.*s %.*s HTTP/1.1\r\n", (int) hm->method.len, hm->method.p, - (int) path.len, path.p); - - mg_printf(be, "Host: %.*s\r\n", (int) host.len, host.p); - for (i = 0; i < MG_MAX_HTTP_HEADERS && hm->header_names[i].len > 0; i++) { - struct mg_str hn = hm->header_names[i]; - struct mg_str hv = hm->header_values[i]; - - /* we rewrite the host header */ - if (mg_vcasecmp(&hn, "Host") == 0) continue; - /* - * Don't pass chunked transfer encoding to the client because hm->body is - * already dechunked when we arrive here. - */ - if (mg_vcasecmp(&hn, "Transfer-encoding") == 0 && - mg_vcasecmp(&hv, "chunked") == 0) { - mg_printf(be, "Content-Length: %" SIZE_T_FMT "\r\n", hm->body.len); - continue; - } - /* We don't support proxying Expect: 100-continue. */ - if (mg_vcasecmp(&hn, "Expect") == 0 && - mg_vcasecmp(&hv, "100-continue") == 0) { - continue; - } - - mg_printf(be, "%.*s: %.*s\r\n", (int) hn.len, hn.p, (int) hv.len, hv.p); - } - - mg_send(be, "\r\n", 2); - mg_send(be, hm->body.p, hm->body.len); - -cleanup: - if (purl != burl) MG_FREE(purl); -} - -static int mg_http_handle_forwarding(struct mg_connection *nc, - struct http_message *hm, - const struct mg_serve_http_opts *opts) { - const char *rewrites = opts->url_rewrites; - struct mg_str a, b; - struct mg_str p1 = MG_MK_STR("http://"), p2 = MG_MK_STR("https://"); - - while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { - if (mg_strncmp(a, hm->uri, a.len) == 0) { - if (mg_strncmp(b, p1, p1.len) == 0 || mg_strncmp(b, p2, p2.len) == 0) { - mg_http_reverse_proxy(nc, hm, a, b); - return 1; - } - } - } - - return 0; -} -#endif /* MG_ENABLE_FILESYSTEM */ - -MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm, - const struct mg_serve_http_opts *opts, - char **local_path, - struct mg_str *remainder) { - int ok = 1; - const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len; - struct mg_str root = {NULL, 0}; - const char *file_uri_start = cp; - *local_path = NULL; - remainder->p = NULL; - remainder->len = 0; - - { /* 1. Determine which root to use. */ - -#if MG_ENABLE_HTTP_URL_REWRITES - const char *rewrites = opts->url_rewrites; -#else - const char *rewrites = ""; -#endif - struct mg_str *hh = mg_get_http_header(hm, "Host"); - struct mg_str a, b; - /* Check rewrites first. */ - while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { - if (a.len > 1 && a.p[0] == '@') { - /* Host rewrite. */ - if (hh != NULL && hh->len == a.len - 1 && - mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) { - root = b; - break; - } - } else { - /* Regular rewrite, URI=directory */ - size_t match_len = mg_match_prefix_n(a, hm->uri); - if (match_len > 0) { - file_uri_start = hm->uri.p + match_len; - if (*file_uri_start == '/' || file_uri_start == cp_end) { - /* Match ended at component boundary, ok. */ - } else if (*(file_uri_start - 1) == '/') { - /* Pattern ends with '/', backtrack. */ - file_uri_start--; - } else { - /* No match: must fall on the component boundary. */ - continue; - } - root = b; - break; - } - } - } - /* If no rewrite rules matched, use DAV or regular document root. */ - if (root.p == NULL) { -#if MG_ENABLE_HTTP_WEBDAV - if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) { - root.p = opts->dav_document_root; - root.len = strlen(opts->dav_document_root); - } else -#endif - { - root.p = opts->document_root; - root.len = strlen(opts->document_root); - } - } - assert(root.p != NULL && root.len > 0); - } - - { /* 2. Find where in the canonical URI path the local path ends. */ - const char *u = file_uri_start + 1; - char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1); - char *lp_end = lp + root.len + hm->uri.len + 1; - char *p = lp, *ps; - int exists = 1; - if (lp == NULL) { - ok = 0; - goto out; - } - memcpy(p, root.p, root.len); - p += root.len; - if (*(p - 1) == DIRSEP) p--; - *p = '\0'; - ps = p; - - /* Chop off URI path components one by one and build local path. */ - while (u <= cp_end) { - const char *next = u; - struct mg_str component; - if (exists) { - cs_stat_t st; - exists = (mg_stat(lp, &st) == 0); - if (exists && S_ISREG(st.st_mode)) { - /* We found the terminal, the rest of the URI (if any) is path_info. - */ - if (*(u - 1) == '/') u--; - break; - } - } - if (u >= cp_end) break; - parse_uri_component((const char **) &next, cp_end, "/", &component); - if (component.len > 0) { - int len; - memmove(p + 1, component.p, component.len); - len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0); - if (len <= 0) { - ok = 0; - break; - } - component.p = p + 1; - component.len = len; - if (mg_vcmp(&component, ".") == 0) { - /* Yum. */ - } else if (mg_vcmp(&component, "..") == 0) { - while (p > ps && *p != DIRSEP) p--; - *p = '\0'; - } else { - size_t i; -#ifdef _WIN32 - /* On Windows, make sure it's valid Unicode (no funny stuff). */ - wchar_t buf[MG_MAX_PATH * 2]; - if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) { - DBG(("[%.*s] smells funny", (int) component.len, component.p)); - ok = 0; - break; - } -#endif - *p++ = DIRSEP; - /* No NULs and DIRSEPs in the component (percent-encoded). */ - for (i = 0; i < component.len; i++, p++) { - if (*p == '\0' || *p == DIRSEP -#ifdef _WIN32 - /* On Windows, "/" is also accepted, so check for that too. */ - || - *p == '/' -#endif - ) { - ok = 0; - break; - } - } - } - } - u = next; - } - if (ok) { - *local_path = lp; - if (u > cp_end) u = cp_end; - remainder->p = u; - remainder->len = cp_end - u; - } else { - MG_FREE(lp); - } - } - -out: - LOG(LL_DEBUG, - ("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p, - *local_path ? *local_path : "", (int) remainder->len, remainder->p)); - return ok; -} - -static int mg_get_month_index(const char *s) { - static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; - size_t i; - - for (i = 0; i < ARRAY_SIZE(month_names); i++) - if (!strcmp(s, month_names[i])) return (int) i; - - return -1; -} - -static int mg_num_leap_years(int year) { - return year / 4 - year / 100 + year / 400; -} - -/* Parse UTC date-time string, and return the corresponding time_t value. */ -MG_INTERNAL time_t mg_parse_date_string(const char *datetime) { - static const unsigned short days_before_month[] = { - 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; - char month_str[32]; - int second, minute, hour, day, month, year, leap_days, days; - time_t result = (time_t) 0; - - if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour, - &minute, &second) == 6) || - (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour, - &minute, &second) == 6) || - (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year, - &hour, &minute, &second) == 6) || - (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour, - &minute, &second) == 6)) && - year > 1970 && (month = mg_get_month_index(month_str)) != -1) { - leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970); - year -= 1970; - days = year * 365 + days_before_month[month] + (day - 1) + leap_days; - result = days * 24 * 3600 + hour * 3600 + minute * 60 + second; - } - - return result; -} - -MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) { - struct mg_str *hdr; - if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) { - char etag[64]; - mg_http_construct_etag(etag, sizeof(etag), st); - return mg_vcasecmp(hdr, etag) == 0; - } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) { - return st->st_mtime <= mg_parse_date_string(hdr->p); - } else { - return 0; - } -} - -void mg_http_send_digest_auth_request(struct mg_connection *c, - const char *domain) { - mg_printf(c, - "HTTP/1.1 401 Unauthorized\r\n" - "WWW-Authenticate: Digest qop=\"auth\", " - "realm=\"%s\", nonce=\"%lx\"\r\n" - "Content-Length: 0\r\n\r\n", - domain, (unsigned long) mg_time()); -} - -static void mg_http_send_options(struct mg_connection *nc, - struct mg_serve_http_opts *opts) { - mg_send_response_line(nc, 200, opts->extra_headers); - mg_printf(nc, "%s", - "Allow: GET, POST, HEAD, CONNECT, OPTIONS" -#if MG_ENABLE_HTTP_WEBDAV - ", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2" -#endif - "\r\n\r\n"); - nc->flags |= MG_F_SEND_AND_CLOSE; -} - -static int mg_is_creation_request(const struct http_message *hm) { - return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0; -} - -MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path, - const struct mg_str *path_info, - struct http_message *hm, - struct mg_serve_http_opts *opts) { - int exists, is_directory, is_cgi; -#if MG_ENABLE_HTTP_WEBDAV - int is_dav = mg_is_dav_request(&hm->method); -#else - int is_dav = 0; -#endif - char *index_file = NULL; - cs_stat_t st; - - exists = (mg_stat(path, &st) == 0); - is_directory = exists && S_ISDIR(st.st_mode); - - if (is_directory) - mg_find_index_file(path, opts->index_files, &index_file, &st); - - is_cgi = - (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern), - index_file ? index_file : path) > 0); - - LOG(LL_DEBUG, - ("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc, - (int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav, - is_cgi, index_file ? index_file : "")); - - if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) { - mg_printf(nc, - "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n" - "Content-Length: 0\r\n\r\n", - (int) hm->uri.len, hm->uri.p); - MG_FREE(index_file); - return; - } - - /* If we have path_info, the only way to handle it is CGI. */ - if (path_info->len > 0 && !is_cgi) { - mg_http_send_error(nc, 501, NULL); - MG_FREE(index_file); - return; - } - - if (is_dav && opts->dav_document_root == NULL) { - mg_http_send_error(nc, 501, NULL); - } else if (!mg_http_is_authorized( - hm, mg_mk_str(path), opts->auth_domain, opts->global_auth_file, - ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | - MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE | - MG_AUTH_FLAG_ALLOW_MISSING_FILE)) || - !mg_http_is_authorized( - hm, mg_mk_str(path), opts->auth_domain, - opts->per_directory_auth_file, - ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | - MG_AUTH_FLAG_ALLOW_MISSING_FILE))) { - mg_http_send_digest_auth_request(nc, opts->auth_domain); - } else if (is_cgi) { -#if MG_ENABLE_HTTP_CGI - mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts); -#else - mg_http_send_error(nc, 501, NULL); -#endif /* MG_ENABLE_HTTP_CGI */ - } else if ((!exists || - mg_is_file_hidden(path, opts, 0 /* specials are ok */)) && - !mg_is_creation_request(hm)) { - mg_http_send_error(nc, 404, NULL); -#if MG_ENABLE_HTTP_WEBDAV - } else if (!mg_vcmp(&hm->method, "PROPFIND")) { - mg_handle_propfind(nc, path, &st, hm, opts); -#if !MG_DISABLE_DAV_AUTH - } else if (is_dav && - (opts->dav_auth_file == NULL || - (strcmp(opts->dav_auth_file, "-") != 0 && - !mg_http_is_authorized( - hm, mg_mk_str(path), opts->auth_domain, opts->dav_auth_file, - ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | - MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE | - MG_AUTH_FLAG_ALLOW_MISSING_FILE))))) { - mg_http_send_digest_auth_request(nc, opts->auth_domain); -#endif - } else if (!mg_vcmp(&hm->method, "MKCOL")) { - mg_handle_mkcol(nc, path, hm); - } else if (!mg_vcmp(&hm->method, "DELETE")) { - mg_handle_delete(nc, opts, path); - } else if (!mg_vcmp(&hm->method, "PUT")) { - mg_handle_put(nc, path, hm); - } else if (!mg_vcmp(&hm->method, "MOVE")) { - mg_handle_move(nc, opts, path, hm); -#if MG_ENABLE_FAKE_DAVLOCK - } else if (!mg_vcmp(&hm->method, "LOCK")) { - mg_handle_lock(nc, path); -#endif -#endif /* MG_ENABLE_HTTP_WEBDAV */ - } else if (!mg_vcmp(&hm->method, "OPTIONS")) { - mg_http_send_options(nc, opts); - } else if (is_directory && index_file == NULL) { -#if MG_ENABLE_DIRECTORY_LISTING - if (strcmp(opts->enable_directory_listing, "yes") == 0) { - mg_send_directory_listing(nc, path, hm, opts); - } else { - mg_http_send_error(nc, 403, NULL); - } -#else - mg_http_send_error(nc, 501, NULL); -#endif - } else if (mg_is_not_modified(hm, &st)) { - mg_http_send_error(nc, 304, "Not Modified"); - } else { - mg_http_serve_file2(nc, index_file ? index_file : path, hm, opts); - } - MG_FREE(index_file); -} - -void mg_serve_http(struct mg_connection *nc, struct http_message *hm, - struct mg_serve_http_opts opts) { - char *path = NULL; - struct mg_str *hdr, path_info; - uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr); - - if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) { - /* Not allowed to connect */ - mg_http_send_error(nc, 403, NULL); - nc->flags |= MG_F_SEND_AND_CLOSE; - return; - } - -#if MG_ENABLE_HTTP_URL_REWRITES - if (mg_http_handle_forwarding(nc, hm, &opts)) { - return; - } - - if (mg_http_send_port_based_redirect(nc, hm, &opts)) { - return; - } -#endif - - if (opts.document_root == NULL) { - opts.document_root = "."; - } - if (opts.per_directory_auth_file == NULL) { - opts.per_directory_auth_file = ".htpasswd"; - } - if (opts.enable_directory_listing == NULL) { - opts.enable_directory_listing = "yes"; - } - if (opts.cgi_file_pattern == NULL) { - opts.cgi_file_pattern = "**.cgi$|**.php$"; - } - if (opts.ssi_pattern == NULL) { - opts.ssi_pattern = "**.shtml$|**.shtm$"; - } - if (opts.index_files == NULL) { - opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php"; - } - /* Normalize path - resolve "." and ".." (in-place). */ - if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) { - mg_http_send_error(nc, 400, NULL); - return; - } - if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) { - mg_http_send_error(nc, 404, NULL); - return; - } - mg_send_http_file(nc, path, &path_info, hm, &opts); - - MG_FREE(path); - path = NULL; - - /* Close connection for non-keep-alive requests */ - if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 || - ((hdr = mg_get_http_header(hm, "Connection")) != NULL && - mg_vcmp(hdr, "keep-alive") != 0)) { -#if 0 - nc->flags |= MG_F_SEND_AND_CLOSE; -#endif - } -} - -#if MG_ENABLE_HTTP_STREAMING_MULTIPART -void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data, - mg_fu_fname_fn local_name_fn - MG_UD_ARG(void *user_data)) { - switch (ev) { - case MG_EV_HTTP_PART_BEGIN: { - struct mg_http_multipart_part *mp = - (struct mg_http_multipart_part *) ev_data; - struct file_upload_state *fus; - struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name)); - mp->user_data = NULL; - if (lfn.p == NULL || lfn.len == 0) { - LOG(LL_ERROR, ("%p Not allowed to upload %s", nc, mp->file_name)); - mg_printf(nc, - "HTTP/1.1 403 Not Allowed\r\n" - "Content-Type: text/plain\r\n" - "Connection: close\r\n\r\n" - "Not allowed to upload %s\r\n", - mp->file_name); - nc->flags |= MG_F_SEND_AND_CLOSE; - return; - } - fus = (struct file_upload_state *) MG_CALLOC(1, sizeof(*fus)); - if (fus == NULL) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - return; - } - fus->lfn = (char *) MG_MALLOC(lfn.len + 1); - memcpy(fus->lfn, lfn.p, lfn.len); - fus->lfn[lfn.len] = '\0'; - if (lfn.p != mp->file_name) MG_FREE((char *) lfn.p); - LOG(LL_DEBUG, - ("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn)); - fus->fp = mg_fopen(fus->lfn, "wb"); - if (fus->fp == NULL) { - mg_printf(nc, - "HTTP/1.1 500 Internal Server Error\r\n" - "Content-Type: text/plain\r\n" - "Connection: close\r\n\r\n"); - LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, mg_get_errno())); - mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, mg_get_errno()); - /* Do not close the connection just yet, discard remainder of the data. - * This is because at the time of writing some browsers (Chrome) fail to - * render response before all the data is sent. */ - } - mp->user_data = (void *) fus; - break; - } - case MG_EV_HTTP_PART_DATA: { - struct mg_http_multipart_part *mp = - (struct mg_http_multipart_part *) ev_data; - struct file_upload_state *fus = - (struct file_upload_state *) mp->user_data; - if (fus == NULL || fus->fp == NULL) break; - if (mg_fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) { - LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn, - mg_get_errno(), (int) fus->num_recd)); - if (mg_get_errno() == ENOSPC -#ifdef SPIFFS_ERR_FULL - || mg_get_errno() == SPIFFS_ERR_FULL -#endif - ) { - mg_printf(nc, - "HTTP/1.1 413 Payload Too Large\r\n" - "Content-Type: text/plain\r\n" - "Connection: close\r\n\r\n"); - mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n", - fus->lfn, (int) fus->num_recd); - } else { - mg_printf(nc, - "HTTP/1.1 500 Internal Server Error\r\n" - "Content-Type: text/plain\r\n" - "Connection: close\r\n\r\n"); - mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name, - mg_get_errno(), (int) fus->num_recd); - } - fclose(fus->fp); - remove(fus->lfn); - fus->fp = NULL; - /* Do not close the connection just yet, discard remainder of the data. - * This is because at the time of writing some browsers (Chrome) fail to - * render response before all the data is sent. */ - return; - } - fus->num_recd += mp->data.len; - LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", nc, (int) mp->data.len, - (int) fus->num_recd)); - break; - } - case MG_EV_HTTP_PART_END: { - struct mg_http_multipart_part *mp = - (struct mg_http_multipart_part *) ev_data; - struct file_upload_state *fus = - (struct file_upload_state *) mp->user_data; - if (fus == NULL) break; - if (mp->status >= 0 && fus->fp != NULL) { - LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", nc, mp->file_name, - fus->lfn, (int) fus->num_recd)); - } else { - LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn)); - /* - * mp->status < 0 means connection was terminated, so no reason to send - * HTTP reply - */ - } - if (fus->fp != NULL) fclose(fus->fp); - MG_FREE(fus->lfn); - MG_FREE(fus); - mp->user_data = NULL; - /* Don't close the connection yet, there may be more files to come. */ - break; - } - case MG_EV_HTTP_MULTIPART_REQUEST_END: { - mg_printf(nc, - "HTTP/1.1 200 OK\r\n" - "Content-Type: text/plain\r\n" - "Connection: close\r\n\r\n" - "Ok.\r\n"); - nc->flags |= MG_F_SEND_AND_CLOSE; - break; - } - } - -#if MG_ENABLE_CALLBACK_USERDATA - (void) user_data; -#endif -} - -#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ -#endif /* MG_ENABLE_FILESYSTEM */ - -struct mg_connection *mg_connect_http_base( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - struct mg_connect_opts opts, const char *scheme1, const char *scheme2, - const char *scheme_ssl1, const char *scheme_ssl2, const char *url, - struct mg_str *path, struct mg_str *user_info, struct mg_str *host) { - struct mg_connection *nc = NULL; - unsigned int port_i = 0; - int use_ssl = 0; - struct mg_str scheme, query, fragment; - char conn_addr_buf[2]; - char *conn_addr = conn_addr_buf; - - if (mg_parse_uri(mg_mk_str(url), &scheme, user_info, host, &port_i, path, - &query, &fragment) != 0) { - MG_SET_PTRPTR(opts.error_string, "cannot parse url"); - goto out; - } - - /* If query is present, do not strip it. Pass to the caller. */ - if (query.len > 0) path->len += query.len + 1; - - if (scheme.len == 0 || mg_vcmp(&scheme, scheme1) == 0 || - (scheme2 != NULL && mg_vcmp(&scheme, scheme2) == 0)) { - use_ssl = 0; - if (port_i == 0) port_i = 80; - } else if (mg_vcmp(&scheme, scheme_ssl1) == 0 || - (scheme2 != NULL && mg_vcmp(&scheme, scheme_ssl2) == 0)) { - use_ssl = 1; - if (port_i == 0) port_i = 443; - } else { - goto out; - } - - mg_asprintf(&conn_addr, sizeof(conn_addr_buf), "tcp://%.*s:%u", - (int) host->len, host->p, port_i); - if (conn_addr == NULL) goto out; - - LOG(LL_DEBUG, ("%s use_ssl? %d %s", url, use_ssl, conn_addr)); - if (use_ssl) { -#if MG_ENABLE_SSL - /* - * Schema requires SSL, but no SSL parameters were provided in opts. - * In order to maintain backward compatibility, use a faux-SSL with no - * verification. - */ - if (opts.ssl_ca_cert == NULL) { - opts.ssl_ca_cert = "*"; - } -#else - MG_SET_PTRPTR(opts.error_string, "ssl is disabled"); - goto out; -#endif - } - - if ((nc = mg_connect_opt(mgr, conn_addr, MG_CB(ev_handler, user_data), - opts)) != NULL) { - mg_set_protocol_http_websocket(nc); - } - -out: - if (conn_addr != NULL && conn_addr != conn_addr_buf) MG_FREE(conn_addr); - return nc; -} - -struct mg_connection *mg_connect_http_opt( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - struct mg_connect_opts opts, const char *url, const char *extra_headers, - const char *post_data) { - struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR; - struct mg_str host = MG_NULL_STR, path = MG_NULL_STR; - struct mbuf auth; - struct mg_connection *nc = - mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http", - NULL, "https", NULL, url, &path, &user, &host); - - if (nc == NULL) { - return NULL; - } - - mbuf_init(&auth, 0); - if (user.len > 0) { - mg_basic_auth_header(user, null_str, &auth); - } - - if (post_data == NULL) post_data = ""; - if (extra_headers == NULL) extra_headers = ""; - if (path.len == 0) path = mg_mk_str("/"); - if (host.len == 0) host = mg_mk_str(""); - - mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT - "\r\n%.*s%s\r\n%s", - (post_data[0] == '\0' ? "GET" : "POST"), (int) path.len, path.p, - (int) (path.p - host.p), host.p, strlen(post_data), (int) auth.len, - (auth.buf == NULL ? "" : auth.buf), extra_headers, post_data); - - mbuf_free(&auth); - return nc; -} - -struct mg_connection *mg_connect_http( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - const char *url, const char *extra_headers, const char *post_data) { - struct mg_connect_opts opts; - memset(&opts, 0, sizeof(opts)); - return mg_connect_http_opt(mgr, MG_CB(ev_handler, user_data), opts, url, - extra_headers, post_data); -} - -size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name, - size_t var_name_len, char *file_name, - size_t file_name_len, const char **data, - size_t *data_len) { - static const char cd[] = "Content-Disposition: "; - size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1; - int shl; - - if (buf == NULL || buf_len <= 0) return 0; - if ((shl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0; - hl = shl; - if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0; - - /* Get boundary length */ - bl = mg_get_line_len(buf, buf_len); - - /* Loop through headers, fetch variable name and file name */ - var_name[0] = file_name[0] = '\0'; - for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) { - if (mg_ncasecmp(cd, buf + n, cdl) == 0) { - struct mg_str header; - header.p = buf + n + cdl; - header.len = ll - (cdl + 2); - { - char *var_name2 = var_name; - mg_http_parse_header2(&header, "name", &var_name2, var_name_len); - /* TODO: handle reallocated buffer correctly */ - if (var_name2 != var_name) { - MG_FREE(var_name2); - var_name[0] = '\0'; - } - } - { - char *file_name2 = file_name; - mg_http_parse_header2(&header, "filename", &file_name2, file_name_len); - /* TODO: handle reallocated buffer correctly */ - if (file_name2 != file_name) { - MG_FREE(file_name2); - file_name[0] = '\0'; - } - } - } - } - - /* Scan through the body, search for terminating boundary */ - for (pos = hl; pos + (bl - 2) < buf_len; pos++) { - if (buf[pos] == '-' && !strncmp(buf, &buf[pos], bl - 2)) { - if (data_len != NULL) *data_len = (pos - 2) - hl; - if (data != NULL) *data = buf + hl; - return pos; - } - } - - return 0; -} - -void mg_register_http_endpoint_opt(struct mg_connection *nc, - const char *uri_path, - mg_event_handler_t handler, - struct mg_http_endpoint_opts opts) { - struct mg_http_proto_data *pd = NULL; - struct mg_http_endpoint *new_ep = NULL; - - if (nc == NULL) return; - new_ep = (struct mg_http_endpoint *) MG_CALLOC(1, sizeof(*new_ep)); - if (new_ep == NULL) return; - - pd = mg_http_get_proto_data(nc); - new_ep->uri_pattern = mg_strdup(mg_mk_str(uri_path)); - if (opts.auth_domain != NULL && opts.auth_file != NULL) { - new_ep->auth_domain = strdup(opts.auth_domain); - new_ep->auth_file = strdup(opts.auth_file); - } - new_ep->handler = handler; -#if MG_ENABLE_CALLBACK_USERDATA - new_ep->user_data = opts.user_data; -#endif - new_ep->next = pd->endpoints; - pd->endpoints = new_ep; -} - -static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev, - struct http_message *hm) { - struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); - void *user_data = nc->user_data; - - if (ev == MG_EV_HTTP_REQUEST -#if MG_ENABLE_HTTP_STREAMING_MULTIPART - || ev == MG_EV_HTTP_MULTIPART_REQUEST -#endif - ) { - struct mg_http_endpoint *ep = - mg_http_get_endpoint_handler(nc->listener, &hm->uri); - if (ep != NULL) { -#if MG_ENABLE_FILESYSTEM && !MG_DISABLE_HTTP_DIGEST_AUTH - if (!mg_http_is_authorized(hm, hm->uri, ep->auth_domain, ep->auth_file, - MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE)) { - mg_http_send_digest_auth_request(nc, ep->auth_domain); - return; - } -#endif - pd->endpoint_handler = ep->handler; -#if MG_ENABLE_CALLBACK_USERDATA - user_data = ep->user_data; -#endif - } - } - mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler, - user_data, ev, hm); -} - -void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path, - MG_CB(mg_event_handler_t handler, - void *user_data)) { - struct mg_http_endpoint_opts opts; - memset(&opts, 0, sizeof(opts)); -#if MG_ENABLE_CALLBACK_USERDATA - opts.user_data = user_data; -#endif - mg_register_http_endpoint_opt(nc, uri_path, handler, opts); -} - -#endif /* MG_ENABLE_HTTP */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http_cgi.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef _WIN32 -#include -#endif - -#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI - -#ifndef MG_MAX_CGI_ENVIR_VARS -#define MG_MAX_CGI_ENVIR_VARS 64 -#endif - -#ifndef MG_ENV_EXPORT_TO_CGI -#define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI" -#endif - -#define MG_F_HTTP_CGI_PARSE_HEADERS MG_F_USER_1 - -/* - * This structure helps to create an environment for the spawned CGI program. - * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings, - * last element must be NULL. - * However, on Windows there is a requirement that all these VARIABLE=VALUE\0 - * strings must reside in a contiguous buffer. The end of the buffer is - * marked by two '\0' characters. - * We satisfy both worlds: we create an envp array (which is vars), all - * entries are actually pointers inside buf. - */ -struct mg_cgi_env_block { - struct mg_connection *nc; - char buf[MG_CGI_ENVIRONMENT_SIZE]; /* Environment buffer */ - const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */ - int len; /* Space taken */ - int nvars; /* Number of variables in envp[] */ -}; - -#ifdef _WIN32 -struct mg_threadparam { - sock_t s; - HANDLE hPipe; -}; - -static int mg_wait_until_ready(sock_t sock, int for_read) { - fd_set set; - FD_ZERO(&set); - FD_SET(sock, &set); - return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1; -} - -static void *mg_push_to_stdin(void *arg) { - struct mg_threadparam *tp = (struct mg_threadparam *) arg; - int n, sent, stop = 0; - DWORD k; - char buf[BUFSIZ]; - - while (!stop && mg_wait_until_ready(tp->s, 1) && - (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) { - if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue; - for (sent = 0; !stop && sent < n; sent += k) { - if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1; - } - } - DBG(("%s", "FORWARED EVERYTHING TO CGI")); - CloseHandle(tp->hPipe); - MG_FREE(tp); - return NULL; -} - -static void *mg_pull_from_stdout(void *arg) { - struct mg_threadparam *tp = (struct mg_threadparam *) arg; - int k = 0, stop = 0; - DWORD n, sent; - char buf[BUFSIZ]; - - while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) { - for (sent = 0; !stop && sent < n; sent += k) { - if (mg_wait_until_ready(tp->s, 0) && - (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) - stop = 1; - } - } - DBG(("%s", "EOF FROM CGI")); - CloseHandle(tp->hPipe); - shutdown(tp->s, 2); // Without this, IO thread may get truncated data - closesocket(tp->s); - MG_FREE(tp); - return NULL; -} - -static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe, - void *(*func)(void *)) { - struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp)); - if (tp != NULL) { - tp->s = sock; - tp->hPipe = hPipe; - mg_start_thread(func, tp); - } -} - -static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) { - wchar_t buf[MG_MAX_PATH], buf2[MG_MAX_PATH]; - to_wchar(utf8_path, buf, ARRAY_SIZE(buf)); - GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL); - WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0); -} - -static int mg_start_process(const char *interp, const char *cmd, - const char *env, const char *envp[], - const char *dir, sock_t sock) { - STARTUPINFOW si; - PROCESS_INFORMATION pi; - HANDLE a[2], b[2], me = GetCurrentProcess(); - wchar_t wcmd[MG_MAX_PATH], full_dir[MG_MAX_PATH]; - char buf[MG_MAX_PATH], buf2[MG_MAX_PATH], buf5[MG_MAX_PATH], - buf4[MG_MAX_PATH], cmdline[MG_MAX_PATH]; - DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS; - FILE *fp; - - memset(&si, 0, sizeof(si)); - memset(&pi, 0, sizeof(pi)); - - si.cb = sizeof(si); - si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; - si.wShowWindow = SW_HIDE; - si.hStdError = GetStdHandle(STD_ERROR_HANDLE); - - CreatePipe(&a[0], &a[1], NULL, 0); - CreatePipe(&b[0], &b[1], NULL, 0); - DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags); - DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags); - - if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) { - buf[0] = buf[1] = '\0'; - fgets(buf, sizeof(buf), fp); - buf[sizeof(buf) - 1] = '\0'; - if (buf[0] == '#' && buf[1] == '!') { - interp = buf + 2; - /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */ - while (*interp != '\0' && isspace(*(unsigned char *) interp)) { - interp++; - } - } - fclose(fp); - } - - snprintf(buf, sizeof(buf), "%s/%s", dir, cmd); - mg_abs_path(buf, buf2, ARRAY_SIZE(buf2)); - - mg_abs_path(dir, buf5, ARRAY_SIZE(buf5)); - to_wchar(dir, full_dir, ARRAY_SIZE(full_dir)); - - if (interp != NULL) { - mg_abs_path(interp, buf4, ARRAY_SIZE(buf4)); - snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2); - } else { - snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2); - } - to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd)); - - if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP, - (void *) env, full_dir, &si, &pi) != 0) { - mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin); - mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout); - - CloseHandle(si.hStdOutput); - CloseHandle(si.hStdInput); - - CloseHandle(pi.hThread); - CloseHandle(pi.hProcess); - } else { - CloseHandle(a[1]); - CloseHandle(b[0]); - closesocket(sock); - } - DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess)); - - /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */ - (void) envp; - return (pi.hProcess != NULL); -} -#else -static int mg_start_process(const char *interp, const char *cmd, - const char *env, const char *envp[], - const char *dir, sock_t sock) { - char buf[500]; - pid_t pid = fork(); - (void) env; - - if (pid == 0) { - /* - * In Linux `chdir` declared with `warn_unused_result` attribute - * To shutup compiler we have yo use result in some way - */ - int tmp = chdir(dir); - (void) tmp; - (void) dup2(sock, 0); - (void) dup2(sock, 1); - closesocket(sock); - - /* - * After exec, all signal handlers are restored to their default values, - * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's - * implementation, SIGCHLD's handler will leave unchanged after exec - * if it was set to be ignored. Restore it to default action. - */ - signal(SIGCHLD, SIG_DFL); - - if (interp == NULL) { - execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */ - } else { - execle(interp, interp, cmd, (char *) 0, envp); - } - snprintf(buf, sizeof(buf), - "Status: 500\r\n\r\n" - "500 Server Error: %s%s%s: %s", - interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd, - strerror(errno)); - send(1, buf, strlen(buf), 0); - _exit(EXIT_FAILURE); /* exec call failed */ - } - - return (pid != 0); -} -#endif /* _WIN32 */ - -/* - * Append VARIABLE=VALUE\0 string to the buffer, and add a respective - * pointer into the vars array. - */ -static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) { - int n, space; - char *added = block->buf + block->len; - va_list ap; - - /* Calculate how much space is left in the buffer */ - space = sizeof(block->buf) - (block->len + 2); - if (space > 0) { - /* Copy VARIABLE=VALUE\0 string into the free space */ - va_start(ap, fmt); - n = vsnprintf(added, (size_t) space, fmt, ap); - va_end(ap); - - /* Make sure we do not overflow buffer and the envp array */ - if (n > 0 && n + 1 < space && - block->nvars < (int) ARRAY_SIZE(block->vars) - 2) { - /* Append a pointer to the added string into the envp array */ - block->vars[block->nvars++] = added; - /* Bump up used length counter. Include \0 terminator */ - block->len += n + 1; - } - } - - return added; -} - -static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) { - const char *s; - if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s); -} - -static void mg_prepare_cgi_environment(struct mg_connection *nc, - const char *prog, - const struct mg_str *path_info, - const struct http_message *hm, - const struct mg_serve_http_opts *opts, - struct mg_cgi_env_block *blk) { - const char *s; - struct mg_str *h; - char *p; - size_t i; - char buf[100]; - size_t path_info_len = path_info != NULL ? path_info->len : 0; - - blk->len = blk->nvars = 0; - blk->nc = nc; - - if ((s = getenv("SERVER_NAME")) != NULL) { - mg_addenv(blk, "SERVER_NAME=%s", s); - } else { - mg_sock_to_str(nc->sock, buf, sizeof(buf), 3); - mg_addenv(blk, "SERVER_NAME=%s", buf); - } - mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root); - mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root); - mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION); - - /* Prepare the environment block */ - mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1"); - mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1"); - mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */ - - mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p); - - mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p, - hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len, - hm->query_string.p); - - mg_conn_addr_to_str(nc, buf, sizeof(buf), - MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP); - mg_addenv(blk, "REMOTE_ADDR=%s", buf); - mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT); - mg_addenv(blk, "SERVER_PORT=%s", buf); - - s = hm->uri.p + hm->uri.len - path_info_len - 1; - if (*s == '/') { - const char *base_name = strrchr(prog, DIRSEP); - mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p, - (base_name != NULL ? base_name + 1 : prog)); - } else { - mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p); - } - mg_addenv(blk, "SCRIPT_FILENAME=%s", prog); - - if (path_info != NULL && path_info->len > 0) { - mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p); - /* Not really translated... */ - mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p); - } - -#if MG_ENABLE_SSL - mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off")); -#else - mg_addenv(blk, "HTTPS=off"); -#endif - - if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) != - NULL) { - mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p); - } - - if (hm->query_string.len > 0) { - mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len, - hm->query_string.p); - } - - if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) != - NULL) { - mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p); - } - - mg_addenv2(blk, "PATH"); - mg_addenv2(blk, "TMP"); - mg_addenv2(blk, "TEMP"); - mg_addenv2(blk, "TMPDIR"); - mg_addenv2(blk, "PERLLIB"); - mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI); - -#ifdef _WIN32 - mg_addenv2(blk, "COMSPEC"); - mg_addenv2(blk, "SYSTEMROOT"); - mg_addenv2(blk, "SystemDrive"); - mg_addenv2(blk, "ProgramFiles"); - mg_addenv2(blk, "ProgramFiles(x86)"); - mg_addenv2(blk, "CommonProgramFiles(x86)"); -#else - mg_addenv2(blk, "LD_LIBRARY_PATH"); -#endif /* _WIN32 */ - - /* Add all headers as HTTP_* variables */ - for (i = 0; hm->header_names[i].len > 0; i++) { - p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len, - hm->header_names[i].p, (int) hm->header_values[i].len, - hm->header_values[i].p); - - /* Convert variable name into uppercase, and change - to _ */ - for (; *p != '=' && *p != '\0'; p++) { - if (*p == '-') *p = '_'; - *p = (char) toupper(*(unsigned char *) p); - } - } - - blk->vars[blk->nvars++] = NULL; - blk->buf[blk->len++] = '\0'; -} - -static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { -#if !MG_ENABLE_CALLBACK_USERDATA - void *user_data = cgi_nc->user_data; -#endif - struct mg_connection *nc = (struct mg_connection *) user_data; - (void) ev_data; - - if (nc == NULL) { - /* The corresponding network connection was closed. */ - cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; - return; - } - - switch (ev) { - case MG_EV_RECV: - /* - * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n" - * It outputs headers, then body. Headers might include "Status" - * header, which changes CODE, and it might include "Location" header - * which changes CODE to 302. - * - * Therefore we do not send the output from the CGI script to the user - * until all CGI headers are received. - * - * Here we parse the output from the CGI script, and if all headers has - * been received, send appropriate reply line, and forward all - * received headers to the client. - */ - if (nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS) { - struct mbuf *io = &cgi_nc->recv_mbuf; - int len = mg_http_get_request_len(io->buf, io->len); - - if (len == 0) break; - if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) { - cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; - mg_http_send_error(nc, 500, "Bad headers"); - } else { - struct http_message hm; - struct mg_str *h; - mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm); - if (mg_get_http_header(&hm, "Location") != NULL) { - mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n"); - } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) { - mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p); - } else { - mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n"); - } - } - nc->flags &= ~MG_F_HTTP_CGI_PARSE_HEADERS; - } - if (!(nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS)) { - mg_forward(cgi_nc, nc); - } - break; - case MG_EV_CLOSE: - DBG(("%p CLOSE", cgi_nc)); - mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi); - nc->flags |= MG_F_SEND_AND_CLOSE; - break; - } -} - -MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog, - const struct mg_str *path_info, - const struct http_message *hm, - const struct mg_serve_http_opts *opts) { - struct mg_cgi_env_block blk; - char dir[MG_MAX_PATH]; - const char *p; - sock_t fds[2]; - - DBG(("%p [%s]", nc, prog)); - mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk); - /* - * CGI must be executed in its own directory. 'dir' must point to the - * directory containing executable program, 'p' must point to the - * executable program name relative to 'dir'. - */ - if ((p = strrchr(prog, DIRSEP)) == NULL) { - snprintf(dir, sizeof(dir), "%s", "."); - } else { - snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog); - prog = p + 1; - } - - if (!mg_socketpair(fds, SOCK_STREAM)) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - return; - } - -#ifndef _WIN32 - struct sigaction sa; - - sigemptyset(&sa.sa_mask); - sa.sa_handler = SIG_IGN; - sa.sa_flags = 0; - sigaction(SIGCHLD, &sa, NULL); -#endif - - if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir, - fds[1]) != 0) { - struct mg_connection *cgi_nc = - mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler MG_UD_ARG(nc)); - struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc); - cgi_pd->cgi.cgi_nc = cgi_nc; -#if !MG_ENABLE_CALLBACK_USERDATA - cgi_pd->cgi.cgi_nc->user_data = nc; -#endif - nc->flags |= MG_F_HTTP_CGI_PARSE_HEADERS; - /* Push POST data to the CGI */ - if (hm->body.len > 0) { - mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, hm->body.len); - } - mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len); - } else { - closesocket(fds[0]); - mg_http_send_error(nc, 500, "CGI failure"); - } - -#ifndef _WIN32 - closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */ -#endif -} - -MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) { - if (d == NULL) return; - if (d->cgi_nc != NULL) { - d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; - d->cgi_nc->user_data = NULL; - } - memset(d, 0, sizeof(*d)); -} - -#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http_ssi.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM - -static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm, - const char *path, FILE *fp, int include_level, - const struct mg_serve_http_opts *opts); - -static void mg_send_file_data(struct mg_connection *nc, FILE *fp) { - char buf[BUFSIZ]; - size_t n; - while ((n = mg_fread(buf, 1, sizeof(buf), fp)) > 0) { - mg_send(nc, buf, n); - } -} - -static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm, - const char *ssi, char *tag, int include_level, - const struct mg_serve_http_opts *opts) { - char file_name[MG_MAX_PATH], path[MG_MAX_PATH], *p; - FILE *fp; - - /* - * sscanf() is safe here, since send_ssi_file() also uses buffer - * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN. - */ - if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) { - /* File name is relative to the webserver root */ - snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name); - } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) { - /* - * File name is relative to the webserver working directory - * or it is absolute system path - */ - snprintf(path, sizeof(path), "%s", file_name); - } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 || - sscanf(tag, " \"%[^\"]\"", file_name) == 1) { - /* File name is relative to the currect document */ - snprintf(path, sizeof(path), "%s", ssi); - if ((p = strrchr(path, DIRSEP)) != NULL) { - p[1] = '\0'; - } - snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name); - } else { - mg_printf(nc, "Bad SSI #include: [%s]", tag); - return; - } - - if ((fp = mg_fopen(path, "rb")) == NULL) { - mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path, - strerror(mg_get_errno())); - } else { - mg_set_close_on_exec((sock_t) fileno(fp)); - if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > - 0) { - mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts); - } else { - mg_send_file_data(nc, fp); - } - fclose(fp); - } -} - -#if MG_ENABLE_HTTP_SSI_EXEC -static void do_ssi_exec(struct mg_connection *nc, char *tag) { - char cmd[BUFSIZ]; - FILE *fp; - - if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) { - mg_printf(nc, "Bad SSI #exec: [%s]", tag); - } else if ((fp = popen(cmd, "r")) == NULL) { - mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno())); - } else { - mg_send_file_data(nc, fp); - pclose(fp); - } -} -#endif /* MG_ENABLE_HTTP_SSI_EXEC */ - -/* - * SSI directive has the following format: - * - */ -static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm, - const char *path, FILE *fp, int include_level, - const struct mg_serve_http_opts *opts) { - static const struct mg_str btag = MG_MK_STR(" */ - buf[i--] = '\0'; - while (i > 0 && buf[i] == ' ') { - buf[i--] = '\0'; - } - - /* Handle known SSI directives */ - if (strncmp(p, d_include.p, d_include.len) == 0) { - mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level, - opts); - } else if (strncmp(p, d_call.p, d_call.len) == 0) { - struct mg_ssi_call_ctx cctx; - memset(&cctx, 0, sizeof(cctx)); - cctx.req = hm; - cctx.file = mg_mk_str(path); - cctx.arg = mg_mk_str(p + d_call.len + 1); - mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL, - (void *) cctx.arg.p); /* NUL added above */ - mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL_CTX, &cctx); -#if MG_ENABLE_HTTP_SSI_EXEC - } else if (strncmp(p, d_exec.p, d_exec.len) == 0) { - do_ssi_exec(nc, p + d_exec.len + 1); -#endif - } else { - /* Silently ignore unknown SSI directive. */ - } - len = 0; - } else if (ch == '<') { - in_ssi_tag = 1; - if (len > 0) { - mg_send(nc, buf, (size_t) len); - } - len = 0; - buf[len++] = ch & 0xff; - } else if (in_ssi_tag) { - if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) { - /* Not an SSI tag */ - in_ssi_tag = 0; - } else if (len == (int) sizeof(buf) - 2) { - mg_printf(nc, "%s: SSI tag is too large", path); - len = 0; - } - buf[len++] = ch & 0xff; - } else { - buf[len++] = ch & 0xff; - if (len == (int) sizeof(buf)) { - mg_send(nc, buf, (size_t) len); - len = 0; - } - } - } - - /* Send the rest of buffered data */ - if (len > 0) { - mg_send(nc, buf, (size_t) len); - } -} - -MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc, - struct http_message *hm, - const char *path, - const struct mg_serve_http_opts *opts) { - FILE *fp; - struct mg_str mime_type; - DBG(("%p %s", nc, path)); - - if ((fp = mg_fopen(path, "rb")) == NULL) { - mg_http_send_error(nc, 404, NULL); - } else { - mg_set_close_on_exec((sock_t) fileno(fp)); - - mime_type = mg_get_mime_type(path, "text/plain", opts); - mg_send_response_line(nc, 200, opts->extra_headers); - mg_printf(nc, - "Content-Type: %.*s\r\n" - "Connection: close\r\n\r\n", - (int) mime_type.len, mime_type.p); - mg_send_ssi_file(nc, hm, path, fp, 0, opts); - fclose(fp); - nc->flags |= MG_F_SEND_AND_CLOSE; - } -} - -#endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http_webdav.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV - -MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) { - static const char *methods[] = { - "PUT", - "DELETE", - "MKCOL", - "PROPFIND", - "MOVE" -#if MG_ENABLE_FAKE_DAVLOCK - , - "LOCK", - "UNLOCK" -#endif - }; - size_t i; - - for (i = 0; i < ARRAY_SIZE(methods); i++) { - if (mg_vcmp(s, methods[i]) == 0) { - return 1; - } - } - - return 0; -} - -static int mg_mkdir(const char *path, uint32_t mode) { -#ifndef _WIN32 - return mkdir(path, mode); -#else - (void) mode; - return _mkdir(path); -#endif -} - -static void mg_print_props(struct mg_connection *nc, const char *name, - cs_stat_t *stp) { - char mtime[64]; - time_t t = stp->st_mtime; /* store in local variable for NDK compile */ - struct mg_str name_esc = mg_url_encode(mg_mk_str(name)); - mg_gmt_time_string(mtime, sizeof(mtime), &t); - mg_printf(nc, - "" - "%s" - "" - "" - "%s" - "%" INT64_FMT - "" - "%s" - "" - "HTTP/1.1 200 OK" - "" - "\n", - name_esc.p, S_ISDIR(stp->st_mode) ? "" : "", - (int64_t) stp->st_size, mtime); - free((void *) name_esc.p); -} - -MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path, - cs_stat_t *stp, struct http_message *hm, - struct mg_serve_http_opts *opts) { - static const char header[] = - "HTTP/1.1 207 Multi-Status\r\n" - "Connection: close\r\n" - "Content-Type: text/xml; charset=utf-8\r\n\r\n" - "" - "\n"; - static const char footer[] = "\n"; - const struct mg_str *depth = mg_get_http_header(hm, "Depth"); - - /* Print properties for the requested resource itself */ - if (S_ISDIR(stp->st_mode) && - strcmp(opts->enable_directory_listing, "yes") != 0) { - mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n"); - } else { - char uri[MG_MAX_PATH]; - mg_send(nc, header, sizeof(header) - 1); - snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p); - mg_print_props(nc, uri, stp); - if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) { - mg_scan_directory(nc, path, opts, mg_print_props); - } - mg_send(nc, footer, sizeof(footer) - 1); - nc->flags |= MG_F_SEND_AND_CLOSE; - } -} - -#if MG_ENABLE_FAKE_DAVLOCK -/* - * Windows explorer (probably there are another WebDav clients like it) - * requires LOCK support in webdav. W/out this, it still works, but fails - * to save file: shows error message and offers "Save As". - * "Save as" works, but this message is very annoying. - * This is fake lock, which doesn't lock something, just returns LOCK token, - * UNLOCK always answers "OK". - * With this fake LOCK Windows Explorer looks happy and saves file. - * NOTE: that is not DAV LOCK imlementation, it is just a way to shut up - * Windows native DAV client. This is why FAKE LOCK is not enabed by default - */ -MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) { - static const char *reply = - "HTTP/1.1 207 Multi-Status\r\n" - "Connection: close\r\n" - "Content-Type: text/xml; charset=utf-8\r\n\r\n" - "" - "\n" - "\n" - "\n" - "\n" - "\n" - "opaquelocktoken:%s%u" - "" - "" - "\n" - "" - "\n"; - mg_printf(nc, reply, path, (unsigned int) mg_time()); - nc->flags |= MG_F_SEND_AND_CLOSE; -} -#endif - -MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path, - struct http_message *hm) { - int status_code = 500; - if (hm->body.len != (size_t) ~0 && hm->body.len > 0) { - status_code = 415; - } else if (!mg_mkdir(path, 0755)) { - status_code = 201; - } else if (errno == EEXIST) { - status_code = 405; - } else if (errno == EACCES) { - status_code = 403; - } else if (errno == ENOENT) { - status_code = 409; - } else { - status_code = 500; - } - mg_http_send_error(nc, status_code, NULL); -} - -static int mg_remove_directory(const struct mg_serve_http_opts *opts, - const char *dir) { - char path[MG_MAX_PATH]; - struct dirent *dp; - cs_stat_t st; - DIR *dirp; - - if ((dirp = opendir(dir)) == NULL) return 0; - - while ((dp = readdir(dirp)) != NULL) { - if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) { - continue; - } - snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name); - mg_stat(path, &st); - if (S_ISDIR(st.st_mode)) { - mg_remove_directory(opts, path); - } else { - remove(path); - } - } - closedir(dirp); - rmdir(dir); - - return 1; -} - -MG_INTERNAL void mg_handle_move(struct mg_connection *c, - const struct mg_serve_http_opts *opts, - const char *path, struct http_message *hm) { - const struct mg_str *dest = mg_get_http_header(hm, "Destination"); - if (dest == NULL) { - mg_http_send_error(c, 411, NULL); - } else { - const char *p = (char *) memchr(dest->p, '/', dest->len); - if (p != NULL && p[1] == '/' && - (p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) { - char buf[MG_MAX_PATH]; - snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root, - (int) (dest->p + dest->len - p), p); - if (rename(path, buf) == 0) { - mg_http_send_error(c, 200, NULL); - } else { - mg_http_send_error(c, 418, NULL); - } - } else { - mg_http_send_error(c, 500, NULL); - } - } -} - -MG_INTERNAL void mg_handle_delete(struct mg_connection *nc, - const struct mg_serve_http_opts *opts, - const char *path) { - cs_stat_t st; - if (mg_stat(path, &st) != 0) { - mg_http_send_error(nc, 404, NULL); - } else if (S_ISDIR(st.st_mode)) { - mg_remove_directory(opts, path); - mg_http_send_error(nc, 204, NULL); - } else if (remove(path) == 0) { - mg_http_send_error(nc, 204, NULL); - } else { - mg_http_send_error(nc, 423, NULL); - } -} - -/* Return -1 on error, 1 on success. */ -static int mg_create_itermediate_directories(const char *path) { - const char *s; - - /* Create intermediate directories if they do not exist */ - for (s = path + 1; *s != '\0'; s++) { - if (*s == '/') { - char buf[MG_MAX_PATH]; - cs_stat_t st; - snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path); - buf[sizeof(buf) - 1] = '\0'; - if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) { - return -1; - } - } - } - - return 1; -} - -MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path, - struct http_message *hm) { - struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); - cs_stat_t st; - const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length"); - int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201; - - mg_http_free_proto_data_file(&pd->file); - if ((rc = mg_create_itermediate_directories(path)) == 0) { - mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code); - } else if (rc == -1) { - mg_http_send_error(nc, 500, NULL); - } else if (cl_hdr == NULL) { - mg_http_send_error(nc, 411, NULL); - } else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) { - mg_http_send_error(nc, 500, NULL); - } else { - const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range"); - int64_t r1 = 0, r2 = 0; - pd->file.type = DATA_PUT; - mg_set_close_on_exec((sock_t) fileno(pd->file.fp)); - pd->file.cl = to64(cl_hdr->p); - if (range_hdr != NULL && - mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) { - status_code = 206; - fseeko(pd->file.fp, r1, SEEK_SET); - pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1; - } - mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code); - /* Remove HTTP request from the mbuf, leave only payload */ - mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len); - mg_http_transfer_file_data(nc); - } -} - -#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http_websocket.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET - -/* Amalgamated: #include "common/cs_sha1.h" */ - -#ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS -#define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5 -#endif - -#define FLAGS_MASK_FIN (1 << 7) -#define FLAGS_MASK_OP 0x0f - -static int mg_is_ws_fragment(unsigned char flags) { - return (flags & FLAGS_MASK_FIN) == 0 || - (flags & FLAGS_MASK_OP) == WEBSOCKET_OP_CONTINUE; -} - -static int mg_is_ws_first_fragment(unsigned char flags) { - return (flags & FLAGS_MASK_FIN) == 0 && - (flags & FLAGS_MASK_OP) != WEBSOCKET_OP_CONTINUE; -} - -static int mg_is_ws_control_frame(unsigned char flags) { - unsigned char op = (flags & FLAGS_MASK_OP); - return op == WEBSOCKET_OP_CLOSE || op == WEBSOCKET_OP_PING || - op == WEBSOCKET_OP_PONG; -} - -static void mg_handle_incoming_websocket_frame(struct mg_connection *nc, - struct websocket_message *wsm) { - if (wsm->flags & 0x8) { - mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm); - } else { - mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_FRAME, wsm); - } -} - -static struct mg_ws_proto_data *mg_ws_get_proto_data(struct mg_connection *nc) { - struct mg_http_proto_data *htd = mg_http_get_proto_data(nc); - return (htd != NULL ? &htd->ws_data : NULL); -} - -/* - * Sends a Close websocket frame with the given data, and closes the underlying - * connection. If `len` is ~0, strlen(data) is used. - */ -static void mg_ws_close(struct mg_connection *nc, const void *data, - size_t len) { - if ((int) len == ~0) { - len = strlen((const char *) data); - } - mg_send_websocket_frame(nc, WEBSOCKET_OP_CLOSE, data, len); - nc->flags |= MG_F_SEND_AND_CLOSE; -} - -static int mg_deliver_websocket_data(struct mg_connection *nc) { - /* Using unsigned char *, cause of integer arithmetic below */ - uint64_t i, data_len = 0, frame_len = 0, new_data_len = nc->recv_mbuf.len, - len, mask_len = 0, header_len = 0; - struct mg_ws_proto_data *wsd = mg_ws_get_proto_data(nc); - unsigned char *new_data = (unsigned char *) nc->recv_mbuf.buf, - *e = (unsigned char *) nc->recv_mbuf.buf + nc->recv_mbuf.len; - uint8_t flags; - int ok, reass; - - if (wsd->reass_len > 0) { - /* - * We already have some previously received data which we need to - * reassemble and deliver to the client code when we get the final - * fragment. - * - * NOTE: it doesn't mean that the current message must be a continuation: - * it might be a control frame (Close, Ping or Pong), which should be - * handled without breaking the fragmented message. - */ - - size_t existing_len = wsd->reass_len; - assert(new_data_len >= existing_len); - - new_data += existing_len; - new_data_len -= existing_len; - } - - flags = new_data[0]; - - reass = new_data_len > 0 && mg_is_ws_fragment(flags) && - !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG); - - if (reass && mg_is_ws_control_frame(flags)) { - /* - * Control frames can't be fragmented, so if we encounter fragmented - * control frame, close connection immediately. - */ - mg_ws_close(nc, "fragmented control frames are illegal", ~0); - return 0; - } else if (new_data_len > 0 && !reass && !mg_is_ws_control_frame(flags) && - wsd->reass_len > 0) { - /* - * When in the middle of a fragmented message, only the continuations - * and control frames are allowed. - */ - mg_ws_close(nc, "non-continuation in the middle of a fragmented message", - ~0); - return 0; - } - - if (new_data_len >= 2) { - len = new_data[1] & 0x7f; - mask_len = new_data[1] & FLAGS_MASK_FIN ? 4 : 0; - if (len < 126 && new_data_len >= mask_len) { - data_len = len; - header_len = 2 + mask_len; - } else if (len == 126 && new_data_len >= 4 + mask_len) { - header_len = 4 + mask_len; - data_len = ntohs(*(uint16_t *) &new_data[2]); - } else if (new_data_len >= 10 + mask_len) { - header_len = 10 + mask_len; - data_len = (((uint64_t) ntohl(*(uint32_t *) &new_data[2])) << 32) + - ntohl(*(uint32_t *) &new_data[6]); - } - } - - frame_len = header_len + data_len; - ok = (frame_len > 0 && frame_len <= new_data_len); - - /* Check for overflow */ - if (frame_len < header_len || frame_len < data_len) { - ok = 0; - mg_ws_close(nc, "overflowed message", ~0); - } - - if (ok) { - size_t cleanup_len = 0; - struct websocket_message wsm; - - wsm.size = (size_t) data_len; - wsm.data = new_data + header_len; - wsm.flags = flags; - - /* Apply mask if necessary */ - if (mask_len > 0) { - for (i = 0; i < data_len; i++) { - new_data[i + header_len] ^= (new_data + header_len - mask_len)[i % 4]; - } - } - - if (reass) { - /* This is a message fragment */ - - if (mg_is_ws_first_fragment(flags)) { - /* - * On the first fragmented frame, skip the first byte (op) and also - * reset size to 1 (op), it'll be incremented with the data len below. - */ - new_data += 1; - wsd->reass_len = 1 /* op */; - } - - /* Append this frame to the reassembled buffer */ - memmove(new_data, wsm.data, e - wsm.data); - wsd->reass_len += wsm.size; - nc->recv_mbuf.len -= wsm.data - new_data; - - if (flags & FLAGS_MASK_FIN) { - /* On last fragmented frame - call user handler and remove data */ - wsm.flags = FLAGS_MASK_FIN | nc->recv_mbuf.buf[0]; - wsm.data = (unsigned char *) nc->recv_mbuf.buf + 1 /* op */; - wsm.size = wsd->reass_len - 1 /* op */; - cleanup_len = wsd->reass_len; - wsd->reass_len = 0; - - /* Pass reassembled message to the client code. */ - mg_handle_incoming_websocket_frame(nc, &wsm); - mbuf_remove(&nc->recv_mbuf, cleanup_len); /* Cleanup frame */ - } - } else { - /* - * This is a complete message, not a fragment. It might happen in between - * of a fragmented message (in this case, WebSocket protocol requires - * current message to be a control frame). - */ - cleanup_len = (size_t) frame_len; - - /* First of all, check if we need to react on a control frame. */ - switch (flags & FLAGS_MASK_OP) { - case WEBSOCKET_OP_PING: - mg_send_websocket_frame(nc, WEBSOCKET_OP_PONG, wsm.data, wsm.size); - break; - - case WEBSOCKET_OP_CLOSE: - mg_ws_close(nc, wsm.data, wsm.size); - break; - } - - /* Pass received message to the client code. */ - mg_handle_incoming_websocket_frame(nc, &wsm); - - /* Cleanup frame */ - memmove(nc->recv_mbuf.buf + wsd->reass_len, - nc->recv_mbuf.buf + wsd->reass_len + cleanup_len, - nc->recv_mbuf.len - wsd->reass_len - cleanup_len); - nc->recv_mbuf.len -= cleanup_len; - } - } - - return ok; -} - -struct ws_mask_ctx { - size_t pos; /* zero means unmasked */ - uint32_t mask; -}; - -static uint32_t mg_ws_random_mask(void) { - uint32_t mask; -/* - * The spec requires WS client to generate hard to - * guess mask keys. From RFC6455, Section 5.3: - * - * The unpredictability of the masking key is essential to prevent - * authors of malicious applications from selecting the bytes that appear on - * the wire. - * - * Hence this feature is essential when the actual end user of this API - * is untrusted code that wouldn't have access to a lower level net API - * anyway (e.g. web browsers). Hence this feature is low prio for most - * mongoose use cases and thus can be disabled, e.g. when porting to a platform - * that lacks rand(). - */ -#if MG_DISABLE_WS_RANDOM_MASK - mask = 0xefbeadde; /* generated with a random number generator, I swear */ -#else - if (sizeof(long) >= 4) { - mask = (uint32_t) rand(); - } else if (sizeof(long) == 2) { - mask = (uint32_t) rand() << 16 | (uint32_t) rand(); - } -#endif - return mask; -} - -static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len, - struct ws_mask_ctx *ctx) { - int header_len; - unsigned char header[10]; - - header[0] = - (op & WEBSOCKET_DONT_FIN ? 0x0 : FLAGS_MASK_FIN) | (op & FLAGS_MASK_OP); - if (len < 126) { - header[1] = (unsigned char) len; - header_len = 2; - } else if (len < 65535) { - uint16_t tmp = htons((uint16_t) len); - header[1] = 126; - memcpy(&header[2], &tmp, sizeof(tmp)); - header_len = 4; - } else { - uint32_t tmp; - header[1] = 127; - tmp = htonl((uint32_t)((uint64_t) len >> 32)); - memcpy(&header[2], &tmp, sizeof(tmp)); - tmp = htonl((uint32_t)(len & 0xffffffff)); - memcpy(&header[6], &tmp, sizeof(tmp)); - header_len = 10; - } - - /* client connections enable masking */ - if (nc->listener == NULL) { - header[1] |= 1 << 7; /* set masking flag */ - mg_send(nc, header, header_len); - ctx->mask = mg_ws_random_mask(); - mg_send(nc, &ctx->mask, sizeof(ctx->mask)); - ctx->pos = nc->send_mbuf.len; - } else { - mg_send(nc, header, header_len); - ctx->pos = 0; - } -} - -static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) { - size_t i; - if (ctx->pos == 0) return; - for (i = 0; i < (mbuf->len - ctx->pos); i++) { - mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4]; - } -} - -void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data, - size_t len) { - struct ws_mask_ctx ctx; - DBG(("%p %d %d", nc, op, (int) len)); - mg_send_ws_header(nc, op, len, &ctx); - mg_send(nc, data, len); - - mg_ws_mask_frame(&nc->send_mbuf, &ctx); - - if (op == WEBSOCKET_OP_CLOSE) { - nc->flags |= MG_F_SEND_AND_CLOSE; - } -} - -void mg_send_websocket_framev(struct mg_connection *nc, int op, - const struct mg_str *strv, int strvcnt) { - struct ws_mask_ctx ctx; - int i; - int len = 0; - for (i = 0; i < strvcnt; i++) { - len += strv[i].len; - } - - mg_send_ws_header(nc, op, len, &ctx); - - for (i = 0; i < strvcnt; i++) { - mg_send(nc, strv[i].p, strv[i].len); - } - - mg_ws_mask_frame(&nc->send_mbuf, &ctx); - - if (op == WEBSOCKET_OP_CLOSE) { - nc->flags |= MG_F_SEND_AND_CLOSE; - } -} - -void mg_printf_websocket_frame(struct mg_connection *nc, int op, - const char *fmt, ...) { - char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; - va_list ap; - int len; - - va_start(ap, fmt); - if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) { - mg_send_websocket_frame(nc, op, buf, len); - } - va_end(ap); - - if (buf != mem && buf != NULL) { - MG_FREE(buf); - } -} - -MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { - mg_call(nc, nc->handler, nc->user_data, ev, ev_data); - - switch (ev) { - case MG_EV_RECV: - do { - } while (mg_deliver_websocket_data(nc)); - break; - case MG_EV_POLL: - /* Ping idle websocket connections */ - { - time_t now = *(time_t *) ev_data; - if (nc->flags & MG_F_IS_WEBSOCKET && - now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) { - mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0); - } - } - break; - default: - break; - } -#if MG_ENABLE_CALLBACK_USERDATA - (void) user_data; -#endif -} - -#ifndef MG_EXT_SHA1 -void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[], - const size_t *msg_lens, uint8_t *digest) { - size_t i; - cs_sha1_ctx sha_ctx; - cs_sha1_init(&sha_ctx); - for (i = 0; i < num_msgs; i++) { - cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]); - } - cs_sha1_final(digest, &sha_ctx); -} -#else -extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[], - const size_t *msg_lens, uint8_t *digest); -#endif - -MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc, - const struct mg_str *key, - struct http_message *hm) { - static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic}; - const size_t msg_lens[2] = {key->len, 36}; - unsigned char sha[20]; - char b64_sha[30]; - struct mg_str *s; - - mg_hash_sha1_v(2, msgs, msg_lens, sha); - mg_base64_encode(sha, sizeof(sha), b64_sha); - mg_printf(nc, "%s", - "HTTP/1.1 101 Switching Protocols\r\n" - "Upgrade: websocket\r\n" - "Connection: Upgrade\r\n"); - - s = mg_get_http_header(hm, "Sec-WebSocket-Protocol"); - if (s != NULL) { - mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) s->len, s->p); - } - mg_printf(nc, "Sec-WebSocket-Accept: %s%s", b64_sha, "\r\n\r\n"); - - DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha)); -} - -void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path, - const char *host, const char *protocol, - const char *extra_headers) { - mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL, - NULL); -} - -void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path, - const char *host, const char *protocol, - const char *extra_headers, const char *user, - const char *pass) { - mg_send_websocket_handshake3v(nc, mg_mk_str(path), mg_mk_str(host), - mg_mk_str(protocol), mg_mk_str(extra_headers), - mg_mk_str(user), mg_mk_str(pass)); -} - -void mg_send_websocket_handshake3v(struct mg_connection *nc, - const struct mg_str path, - const struct mg_str host, - const struct mg_str protocol, - const struct mg_str extra_headers, - const struct mg_str user, - const struct mg_str pass) { - struct mbuf auth; - char key[25]; - uint32_t nonce[4]; - nonce[0] = mg_ws_random_mask(); - nonce[1] = mg_ws_random_mask(); - nonce[2] = mg_ws_random_mask(); - nonce[3] = mg_ws_random_mask(); - mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key); - - mbuf_init(&auth, 0); - if (user.len > 0) { - mg_basic_auth_header(user, pass, &auth); - } - - /* - * NOTE: the (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is - * broken: it doesn't like zero length to be passed to %.*s - * i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`. - * because it handles NULL specially (and incorrectly). - */ - mg_printf(nc, - "GET %.*s HTTP/1.1\r\n" - "Upgrade: websocket\r\n" - "Connection: Upgrade\r\n" - "%.*s" - "Sec-WebSocket-Version: 13\r\n" - "Sec-WebSocket-Key: %s\r\n", - (int) path.len, path.p, (int) auth.len, - (auth.buf == NULL ? "" : auth.buf), key); - - /* TODO(mkm): take default hostname from http proto data if host == NULL */ - if (host.len > 0) { - int host_len = (int) (path.p - host.p); /* Account for possible :PORT */ - mg_printf(nc, "Host: %.*s\r\n", host_len, host.p); - } - if (protocol.len > 0) { - mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) protocol.len, - protocol.p); - } - if (extra_headers.len > 0) { - mg_printf(nc, "%.*s", (int) extra_headers.len, extra_headers.p); - } - mg_printf(nc, "\r\n"); - - nc->flags |= MG_F_IS_WEBSOCKET; - - mbuf_free(&auth); -} - -void mg_send_websocket_handshake(struct mg_connection *nc, const char *path, - const char *extra_headers) { - struct mg_str null_str = MG_NULL_STR; - mg_send_websocket_handshake3v( - nc, mg_mk_str(path), null_str /* host */, null_str /* protocol */, - mg_mk_str(extra_headers), null_str /* user */, null_str /* pass */); -} - -struct mg_connection *mg_connect_ws_opt( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - struct mg_connect_opts opts, const char *url, const char *protocol, - const char *extra_headers) { - struct mg_str null_str = MG_NULL_STR; - struct mg_str host = MG_NULL_STR, path = MG_NULL_STR, user_info = MG_NULL_STR; - struct mg_connection *nc = - mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http", - "ws", "https", "wss", url, &path, &user_info, &host); - if (nc != NULL) { - mg_send_websocket_handshake3v(nc, path, host, mg_mk_str(protocol), - mg_mk_str(extra_headers), user_info, - null_str); - } - return nc; -} - -struct mg_connection *mg_connect_ws( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - const char *url, const char *protocol, const char *extra_headers) { - struct mg_connect_opts opts; - memset(&opts, 0, sizeof(opts)); - return mg_connect_ws_opt(mgr, MG_CB(ev_handler, user_data), opts, url, - protocol, extra_headers); -} -#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_util.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* Amalgamated: #include "common/cs_base64.h" */ -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_util.h" */ - -/* For platforms with limited libc */ -#ifndef MAX -#define MAX(a, b) ((a) > (b) ? (a) : (b)) -#endif - -const char *mg_skip(const char *s, const char *end, const char *delims, - struct mg_str *v) { - v->p = s; - while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++; - v->len = s - v->p; - while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++; - return s; -} - -#if MG_ENABLE_FILESYSTEM && !defined(MG_USER_FILE_FUNCTIONS) -int mg_stat(const char *path, cs_stat_t *st) { -#ifdef _WIN32 - wchar_t wpath[MG_MAX_PATH]; - to_wchar(path, wpath, ARRAY_SIZE(wpath)); - DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st))); - return _wstati64(wpath, st); -#else - return stat(path, st); -#endif -} - -FILE *mg_fopen(const char *path, const char *mode) { -#ifdef _WIN32 - wchar_t wpath[MG_MAX_PATH], wmode[10]; - to_wchar(path, wpath, ARRAY_SIZE(wpath)); - to_wchar(mode, wmode, ARRAY_SIZE(wmode)); - return _wfopen(wpath, wmode); -#else - return fopen(path, mode); -#endif -} - -int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */ -#if defined(_WIN32) && !defined(WINCE) - wchar_t wpath[MG_MAX_PATH]; - to_wchar(path, wpath, ARRAY_SIZE(wpath)); - return _wopen(wpath, flag, mode); -#else - return open(path, flag, mode); /* LCOV_EXCL_LINE */ -#endif -} - -size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f) { - return fread(ptr, size, count, f); -} - -size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f) { - return fwrite(ptr, size, count, f); -} -#endif - -void mg_base64_encode(const unsigned char *src, int src_len, char *dst) { - cs_base64_encode(src, src_len, dst); -} - -int mg_base64_decode(const unsigned char *s, int len, char *dst) { - return cs_base64_decode(s, len, dst, NULL); -} - -#if MG_ENABLE_THREADS -void *mg_start_thread(void *(*f)(void *), void *p) { -#ifdef WINCE - return (void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL); -#elif defined(_WIN32) - return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p); -#else - pthread_t thread_id = (pthread_t) 0; - pthread_attr_t attr; - - (void) pthread_attr_init(&attr); - (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); - -#if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1 - (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE); -#endif - - pthread_create(&thread_id, &attr, f, p); - pthread_attr_destroy(&attr); - - return (void *) thread_id; -#endif -} -#endif /* MG_ENABLE_THREADS */ - -/* Set close-on-exec bit for a given socket. */ -void mg_set_close_on_exec(sock_t sock) { -#if defined(_WIN32) && !defined(WINCE) - (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0); -#elif defined(__unix__) - fcntl(sock, F_SETFD, FD_CLOEXEC); -#else - (void) sock; -#endif -} - -int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len, - int flags) { - int is_v6; - if (buf == NULL || len <= 0) return 0; - memset(buf, 0, len); -#if MG_ENABLE_IPV6 - is_v6 = sa->sa.sa_family == AF_INET6; -#else - is_v6 = 0; -#endif - if (flags & MG_SOCK_STRINGIFY_IP) { -#if MG_ENABLE_IPV6 - const void *addr = NULL; - char *start = buf; - socklen_t capacity = len; - if (!is_v6) { - addr = &sa->sin.sin_addr; - } else { - addr = (void *) &sa->sin6.sin6_addr; - if (flags & MG_SOCK_STRINGIFY_PORT) { - *buf = '['; - start++; - capacity--; - } - } - if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) { - goto cleanup; - } -#elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32) - /* Only Windoze Vista (and newer) have inet_ntop() */ - char *addr_str = inet_ntoa(sa->sin.sin_addr); - if (addr_str != NULL) { - strncpy(buf, inet_ntoa(sa->sin.sin_addr), len - 1); - } else { - goto cleanup; - } -#else - if (inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len) == NULL) { - goto cleanup; - } -#endif - } - if (flags & MG_SOCK_STRINGIFY_PORT) { - int port = ntohs(sa->sin.sin_port); - if (flags & MG_SOCK_STRINGIFY_IP) { - int buf_len = strlen(buf); - snprintf(buf + buf_len, len - (buf_len + 1), "%s:%d", (is_v6 ? "]" : ""), - port); - } else { - snprintf(buf, len, "%d", port); - } - } - - return strlen(buf); - -cleanup: - *buf = '\0'; - return 0; -} - -int mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len, - int flags) { - union socket_address sa; - memset(&sa, 0, sizeof(sa)); - mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa); - return mg_sock_addr_to_str(&sa, buf, len, flags); -} - -#if MG_ENABLE_HEXDUMP -static int mg_hexdump_n(const void *buf, int len, char *dst, int dst_len, - int offset) { - const unsigned char *p = (const unsigned char *) buf; - char ascii[17] = ""; - int i, idx, n = 0; - - for (i = 0; i < len; i++) { - idx = i % 16; - if (idx == 0) { - if (i > 0) n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii); - n += snprintf(dst + n, MAX(dst_len - n, 0), "%04x ", i + offset); - } - if (dst_len - n < 0) { - return n; - } - n += snprintf(dst + n, MAX(dst_len - n, 0), " %02x", p[i]); - ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i]; - ascii[idx + 1] = '\0'; - } - - while (i++ % 16) n += snprintf(dst + n, MAX(dst_len - n, 0), "%s", " "); - n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii); - - return n; -} - -int mg_hexdump(const void *buf, int len, char *dst, int dst_len) { - return mg_hexdump_n(buf, len, dst, dst_len, 0); -} - -void mg_hexdumpf(FILE *fp, const void *buf, int len) { - char tmp[80]; - int offset = 0, n; - while (len > 0) { - n = (len < 16 ? len : 16); - mg_hexdump_n(((const char *) buf) + offset, n, tmp, sizeof(tmp), offset); - fputs(tmp, fp); - offset += n; - len -= n; - } -} - -void mg_hexdump_connection(struct mg_connection *nc, const char *path, - const void *buf, int num_bytes, int ev) { - FILE *fp = NULL; - char src[60], dst[60]; - const char *tag = NULL; - switch (ev) { - case MG_EV_RECV: - tag = "<-"; - break; - case MG_EV_SEND: - tag = "->"; - break; - case MG_EV_ACCEPT: - tag = " 0) { - mg_hexdumpf(fp, buf, num_bytes); - } - if (fp != stdout && fp != stderr) fclose(fp); -} -#endif - -int mg_is_big_endian(void) { - static const int n = 1; - /* TODO(mkm) use compiletime check with 4-byte char literal */ - return ((char *) &n)[0] == 0; -} - -DO_NOT_WARN_UNUSED MG_INTERNAL int mg_get_errno(void) { -#ifndef WINCE - return errno; -#else - /* TODO(alashkin): translate error codes? */ - return GetLastError(); -#endif -} - -void mg_mbuf_append_base64_putc(char ch, void *user_data) { - struct mbuf *mbuf = (struct mbuf *) user_data; - mbuf_append(mbuf, &ch, sizeof(ch)); -} - -void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len) { - struct cs_base64_ctx ctx; - cs_base64_init(&ctx, mg_mbuf_append_base64_putc, mbuf); - cs_base64_update(&ctx, (const char *) data, len); - cs_base64_finish(&ctx); -} - -void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass, - struct mbuf *buf) { - const char *header_prefix = "Authorization: Basic "; - const char *header_suffix = "\r\n"; - - struct cs_base64_ctx ctx; - cs_base64_init(&ctx, mg_mbuf_append_base64_putc, buf); - - mbuf_append(buf, header_prefix, strlen(header_prefix)); - - cs_base64_update(&ctx, user.p, user.len); - if (pass.len > 0) { - cs_base64_update(&ctx, ":", 1); - cs_base64_update(&ctx, pass.p, pass.len); - } - cs_base64_finish(&ctx); - mbuf_append(buf, header_suffix, strlen(header_suffix)); -} - -struct mg_str mg_url_encode_opt(const struct mg_str src, - const struct mg_str safe, unsigned int flags) { - const char *hex = - (flags & MG_URL_ENCODE_F_UPPERCASE_HEX ? "0123456789ABCDEF" - : "0123456789abcdef"); - size_t i = 0; - struct mbuf mb; - mbuf_init(&mb, src.len); - - for (i = 0; i < src.len; i++) { - const unsigned char c = *((const unsigned char *) src.p + i); - if (isalnum(c) || mg_strchr(safe, c) != NULL) { - mbuf_append(&mb, &c, 1); - } else if (c == ' ' && (flags & MG_URL_ENCODE_F_SPACE_AS_PLUS)) { - mbuf_append(&mb, "+", 1); - } else { - mbuf_append(&mb, "%", 1); - mbuf_append(&mb, &hex[c >> 4], 1); - mbuf_append(&mb, &hex[c & 15], 1); - } - } - mbuf_append(&mb, "", 1); - mbuf_trim(&mb); - return mg_mk_str_n(mb.buf, mb.len - 1); -} - -struct mg_str mg_url_encode(const struct mg_str src) { - return mg_url_encode_opt(src, mg_mk_str("._-$,;~()/"), 0); -} -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_mqtt.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_MQTT - -#include - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_mqtt.h" */ - -static uint16_t getu16(const char *p) { - const uint8_t *up = (const uint8_t *) p; - return (up[0] << 8) + up[1]; -} - -static const char *scanto(const char *p, struct mg_str *s) { - s->len = getu16(p); - s->p = p + 2; - return s->p + s->len; -} - -MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) { - uint8_t header; - size_t len = 0, len_len = 0; - const char *p, *end; - unsigned char lc = 0; - int cmd; - - if (io->len < 2) return MG_MQTT_ERROR_INCOMPLETE_MSG; - header = io->buf[0]; - cmd = header >> 4; - - /* decode mqtt variable length */ - len = len_len = 0; - p = io->buf + 1; - while ((size_t)(p - io->buf) < io->len) { - lc = *((const unsigned char *) p++); - len += (lc & 0x7f) << 7 * len_len; - len_len++; - if (!(lc & 0x80)) break; - if (len_len > 4) return MG_MQTT_ERROR_MALFORMED_MSG; - } - - end = p + len; - if (lc & 0x80 || len > (io->len - (p - io->buf))) { - return MG_MQTT_ERROR_INCOMPLETE_MSG; - } - - mm->cmd = cmd; - mm->qos = MG_MQTT_GET_QOS(header); - - switch (cmd) { - case MG_MQTT_CMD_CONNECT: { - p = scanto(p, &mm->protocol_name); - if (p > end - 4) return MG_MQTT_ERROR_MALFORMED_MSG; - mm->protocol_version = *(uint8_t *) p++; - mm->connect_flags = *(uint8_t *) p++; - mm->keep_alive_timer = getu16(p); - p += 2; - if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; - p = scanto(p, &mm->client_id); - if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG; - if (mm->connect_flags & MG_MQTT_HAS_WILL) { - if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; - p = scanto(p, &mm->will_topic); - } - if (mm->connect_flags & MG_MQTT_HAS_WILL) { - if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; - p = scanto(p, &mm->will_message); - } - if (mm->connect_flags & MG_MQTT_HAS_USER_NAME) { - if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; - p = scanto(p, &mm->user_name); - } - if (mm->connect_flags & MG_MQTT_HAS_PASSWORD) { - if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; - p = scanto(p, &mm->password); - } - if (p != end) return MG_MQTT_ERROR_MALFORMED_MSG; - - LOG(LL_DEBUG, - ("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] " - "will_msg [%.*s] user_name [%.*s] password [%.*s]", - (int) len, (int) mm->connect_flags, (int) mm->keep_alive_timer, - (int) mm->protocol_name.len, mm->protocol_name.p, - (int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len, - mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p, - (int) mm->user_name.len, mm->user_name.p, (int) mm->password.len, - mm->password.p)); - break; - } - case MG_MQTT_CMD_CONNACK: - if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; - mm->connack_ret_code = p[1]; - break; - case MG_MQTT_CMD_PUBACK: - case MG_MQTT_CMD_PUBREC: - case MG_MQTT_CMD_PUBREL: - case MG_MQTT_CMD_PUBCOMP: - case MG_MQTT_CMD_SUBACK: - mm->message_id = getu16(p); - break; - case MG_MQTT_CMD_PUBLISH: { - p = scanto(p, &mm->topic); - if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG; - if (mm->qos > 0) { - if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; - mm->message_id = getu16(p); - p += 2; - } - mm->payload.p = p; - mm->payload.len = end - p; - break; - } - case MG_MQTT_CMD_SUBSCRIBE: - if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; - mm->message_id = getu16(p); - p += 2; - /* - * topic expressions are left in the payload and can be parsed with - * `mg_mqtt_next_subscribe_topic` - */ - mm->payload.p = p; - mm->payload.len = end - p; - break; - default: - /* Unhandled command */ - break; - } - - mm->len = end - io->buf; - return mm->len; -} - -static void mqtt_handler(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { - struct mbuf *io = &nc->recv_mbuf; - struct mg_mqtt_message mm; - memset(&mm, 0, sizeof(mm)); - - nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); - - switch (ev) { - case MG_EV_ACCEPT: - if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc); - break; - case MG_EV_RECV: { - /* There can be multiple messages in the buffer, process them all. */ - while (1) { - int len = parse_mqtt(io, &mm); - if (len < 0) { - if (len == MG_MQTT_ERROR_MALFORMED_MSG) { - /* Protocol error. */ - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } else if (len == MG_MQTT_ERROR_INCOMPLETE_MSG) { - /* Not fully buffered, let's check if we have a chance to get more - * data later */ - if (nc->recv_mbuf_limit > 0 && - nc->recv_mbuf.len >= nc->recv_mbuf_limit) { - LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit " - "%lu bytes, and not drained, closing", - nc, (unsigned long) nc->recv_mbuf.len, - (unsigned long) nc->recv_mbuf_limit)); - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } - } else { - /* Should never be here */ - LOG(LL_ERROR, ("%p invalid len: %d, closing", nc, len)); - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } - break; - } - - nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data)); - mbuf_remove(io, len); - } - break; - } - case MG_EV_POLL: { - struct mg_mqtt_proto_data *pd = - (struct mg_mqtt_proto_data *) nc->proto_data; - double now = mg_time(); - if (pd->keep_alive > 0 && pd->last_control_time > 0 && - (now - pd->last_control_time) > pd->keep_alive) { - LOG(LL_DEBUG, ("Send PINGREQ")); - mg_mqtt_ping(nc); - } - break; - } - } -} - -static void mg_mqtt_proto_data_destructor(void *proto_data) { - MG_FREE(proto_data); -} - -static struct mg_str mg_mqtt_next_topic_component(struct mg_str *topic) { - struct mg_str res = *topic; - const char *c = mg_strchr(*topic, '/'); - if (c != NULL) { - res.len = (c - topic->p); - topic->len -= (res.len + 1); - topic->p += (res.len + 1); - } else { - topic->len = 0; - } - return res; -} - -/* Refernce: https://mosquitto.org/man/mqtt-7.html */ -int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) { - struct mg_str ec, tc; - if (exp.len == 0) return 0; - while (1) { - ec = mg_mqtt_next_topic_component(&exp); - tc = mg_mqtt_next_topic_component(&topic); - if (ec.len == 0) { - if (tc.len != 0) return 0; - if (exp.len == 0) break; - continue; - } - if (mg_vcmp(&ec, "+") == 0) { - if (tc.len == 0 && topic.len == 0) return 0; - continue; - } - if (mg_vcmp(&ec, "#") == 0) { - /* Must be the last component in the expression or it's invalid. */ - return (exp.len == 0); - } - if (mg_strcmp(ec, tc) != 0) { - return 0; - } - } - return (tc.len == 0 && topic.len == 0); -} - -int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) { - return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic); -} - -void mg_set_protocol_mqtt(struct mg_connection *nc) { - nc->proto_handler = mqtt_handler; - nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data)); - nc->proto_data_destructor = mg_mqtt_proto_data_destructor; -} - -static void mg_send_mqtt_header(struct mg_connection *nc, uint8_t cmd, - uint8_t flags, size_t len) { - struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; - uint8_t buf[1 + sizeof(size_t)]; - uint8_t *vlen = &buf[1]; - - buf[0] = (cmd << 4) | flags; - - /* mqtt variable length encoding */ - do { - *vlen = len % 0x80; - len /= 0x80; - if (len > 0) *vlen |= 0x80; - vlen++; - } while (len > 0); - - mg_send(nc, buf, vlen - buf); - pd->last_control_time = mg_time(); -} - -void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) { - static struct mg_send_mqtt_handshake_opts opts; - mg_send_mqtt_handshake_opt(nc, client_id, opts); -} - -void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id, - struct mg_send_mqtt_handshake_opts opts) { - struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; - uint16_t id_len = 0, wt_len = 0, wm_len = 0, user_len = 0, pw_len = 0; - uint16_t netbytes; - size_t total_len; - - if (client_id != NULL) { - id_len = strlen(client_id); - } - - total_len = 7 + 1 + 2 + 2 + id_len; - - if (opts.user_name != NULL) { - opts.flags |= MG_MQTT_HAS_USER_NAME; - } - if (opts.password != NULL) { - opts.flags |= MG_MQTT_HAS_PASSWORD; - } - if (opts.will_topic != NULL && opts.will_message != NULL) { - wt_len = strlen(opts.will_topic); - wm_len = strlen(opts.will_message); - opts.flags |= MG_MQTT_HAS_WILL; - } - if (opts.keep_alive == 0) { - opts.keep_alive = 60; - } - - if (opts.flags & MG_MQTT_HAS_WILL) { - total_len += 2 + wt_len + 2 + wm_len; - } - if (opts.flags & MG_MQTT_HAS_USER_NAME) { - user_len = strlen(opts.user_name); - total_len += 2 + user_len; - } - if (opts.flags & MG_MQTT_HAS_PASSWORD) { - pw_len = strlen(opts.password); - total_len += 2 + pw_len; - } - - mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNECT, 0, total_len); - mg_send(nc, "\00\04MQTT\04", 7); - mg_send(nc, &opts.flags, 1); - - netbytes = htons(opts.keep_alive); - mg_send(nc, &netbytes, 2); - - netbytes = htons(id_len); - mg_send(nc, &netbytes, 2); - mg_send(nc, client_id, id_len); - - if (opts.flags & MG_MQTT_HAS_WILL) { - netbytes = htons(wt_len); - mg_send(nc, &netbytes, 2); - mg_send(nc, opts.will_topic, wt_len); - - netbytes = htons(wm_len); - mg_send(nc, &netbytes, 2); - mg_send(nc, opts.will_message, wm_len); - } - - if (opts.flags & MG_MQTT_HAS_USER_NAME) { - netbytes = htons(user_len); - mg_send(nc, &netbytes, 2); - mg_send(nc, opts.user_name, user_len); - } - if (opts.flags & MG_MQTT_HAS_PASSWORD) { - netbytes = htons(pw_len); - mg_send(nc, &netbytes, 2); - mg_send(nc, opts.password, pw_len); - } - - if (pd != NULL) { - pd->keep_alive = opts.keep_alive; - } -} - -void mg_mqtt_publish(struct mg_connection *nc, const char *topic, - uint16_t message_id, int flags, const void *data, - size_t len) { - uint16_t netbytes; - uint16_t topic_len = strlen(topic); - - size_t total_len = 2 + topic_len + len; - if (MG_MQTT_GET_QOS(flags) > 0) { - total_len += 2; - } - - mg_send_mqtt_header(nc, MG_MQTT_CMD_PUBLISH, flags, total_len); - - netbytes = htons(topic_len); - mg_send(nc, &netbytes, 2); - mg_send(nc, topic, topic_len); - - if (MG_MQTT_GET_QOS(flags) > 0) { - netbytes = htons(message_id); - mg_send(nc, &netbytes, 2); - } - - mg_send(nc, data, len); -} - -void mg_mqtt_subscribe(struct mg_connection *nc, - const struct mg_mqtt_topic_expression *topics, - size_t topics_len, uint16_t message_id) { - uint16_t netbytes; - size_t i; - uint16_t topic_len; - size_t total_len = 2; - - for (i = 0; i < topics_len; i++) { - total_len += 2 + strlen(topics[i].topic) + 1; - } - - mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1), total_len); - - netbytes = htons(message_id); - mg_send(nc, (char *) &netbytes, 2); - - for (i = 0; i < topics_len; i++) { - topic_len = strlen(topics[i].topic); - netbytes = htons(topic_len); - mg_send(nc, &netbytes, 2); - mg_send(nc, topics[i].topic, topic_len); - mg_send(nc, &topics[i].qos, 1); - } -} - -int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg, - struct mg_str *topic, uint8_t *qos, int pos) { - unsigned char *buf = (unsigned char *) msg->payload.p + pos; - int new_pos; - - if ((size_t) pos >= msg->payload.len) return -1; - - topic->len = buf[0] << 8 | buf[1]; - topic->p = (char *) buf + 2; - new_pos = pos + 2 + topic->len + 1; - if ((size_t) new_pos > msg->payload.len) return -1; - *qos = buf[2 + topic->len]; - return new_pos; -} - -void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics, - size_t topics_len, uint16_t message_id) { - uint16_t netbytes; - size_t i; - uint16_t topic_len; - size_t total_len = 2; - - for (i = 0; i < topics_len; i++) { - total_len += 2 + strlen(topics[i]); - } - - mg_send_mqtt_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1), total_len); - - netbytes = htons(message_id); - mg_send(nc, (char *) &netbytes, 2); - - for (i = 0; i < topics_len; i++) { - topic_len = strlen(topics[i]); - netbytes = htons(topic_len); - mg_send(nc, &netbytes, 2); - mg_send(nc, topics[i], topic_len); - } -} - -void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) { - uint8_t unused = 0; - mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNACK, 0, 2); - mg_send(nc, &unused, 1); - mg_send(nc, &return_code, 1); -} - -/* - * Sends a command which contains only a `message_id` and a QoS level of 1. - * - * Helper function. - */ -static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd, - uint16_t message_id) { - uint16_t netbytes; - uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0); - - mg_send_mqtt_header(nc, cmd, flags, 2 /* len */); - - netbytes = htons(message_id); - mg_send(nc, &netbytes, 2); -} - -void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) { - mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id); -} - -void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) { - mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id); -} - -void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) { - mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id); -} - -void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) { - mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id); -} - -void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len, - uint16_t message_id) { - size_t i; - uint16_t netbytes; - - mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len); - - netbytes = htons(message_id); - mg_send(nc, &netbytes, 2); - - for (i = 0; i < qoss_len; i++) { - mg_send(nc, &qoss[i], 1); - } -} - -void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) { - mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id); -} - -void mg_mqtt_ping(struct mg_connection *nc) { - mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0); -} - -void mg_mqtt_pong(struct mg_connection *nc) { - mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0); -} - -void mg_mqtt_disconnect(struct mg_connection *nc) { - mg_send_mqtt_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0); -} - -#endif /* MG_ENABLE_MQTT */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_mqtt_server.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_mqtt_server.h" */ - -#if MG_ENABLE_MQTT_BROKER - -static void mg_mqtt_session_init(struct mg_mqtt_broker *brk, - struct mg_mqtt_session *s, - struct mg_connection *nc) { - s->brk = brk; - s->subscriptions = NULL; - s->num_subscriptions = 0; - s->nc = nc; -} - -static void mg_mqtt_add_session(struct mg_mqtt_session *s) { - LIST_INSERT_HEAD(&s->brk->sessions, s, link); -} - -static void mg_mqtt_remove_session(struct mg_mqtt_session *s) { - LIST_REMOVE(s, link); -} - -static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) { - size_t i; - for (i = 0; i < s->num_subscriptions; i++) { - MG_FREE((void *) s->subscriptions[i].topic); - } - MG_FREE(s->subscriptions); - MG_FREE(s); -} - -static void mg_mqtt_close_session(struct mg_mqtt_session *s) { - mg_mqtt_remove_session(s); - mg_mqtt_destroy_session(s); -} - -void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) { - LIST_INIT(&brk->sessions); - brk->user_data = user_data; -} - -static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk, - struct mg_connection *nc) { - struct mg_mqtt_session *s = - (struct mg_mqtt_session *) MG_CALLOC(1, sizeof *s); - if (s == NULL) { - /* LCOV_EXCL_START */ - mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE); - return; - /* LCOV_EXCL_STOP */ - } - - /* TODO(mkm): check header (magic and version) */ - - mg_mqtt_session_init(brk, s, nc); - nc->priv_2 = s; - mg_mqtt_add_session(s); - - mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED); -} - -static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc, - struct mg_mqtt_message *msg) { - struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->priv_2; - uint8_t qoss[MG_MQTT_MAX_SESSION_SUBSCRIPTIONS]; - size_t num_subs = 0; - struct mg_str topic; - uint8_t qos; - int pos; - struct mg_mqtt_topic_expression *te; - - for (pos = 0; - (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) { - if (num_subs >= sizeof(MG_MQTT_MAX_SESSION_SUBSCRIPTIONS) || - (ss->num_subscriptions + num_subs >= - MG_MQTT_MAX_SESSION_SUBSCRIPTIONS)) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - return; - } - qoss[num_subs++] = qos; - } - - if (num_subs > 0) { - te = (struct mg_mqtt_topic_expression *) MG_REALLOC( - ss->subscriptions, - sizeof(*ss->subscriptions) * (ss->num_subscriptions + num_subs)); - if (te == NULL) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - return; - } - ss->subscriptions = te; - for (pos = 0; - pos < (int) msg->payload.len && - (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1; - ss->num_subscriptions++) { - te = &ss->subscriptions[ss->num_subscriptions]; - te->topic = (char *) MG_MALLOC(topic.len + 1); - te->qos = qos; - memcpy((char *) te->topic, topic.p, topic.len); - ((char *) te->topic)[topic.len] = '\0'; - } - } - - if (pos == (int) msg->payload.len) { - mg_mqtt_suback(nc, qoss, num_subs, msg->message_id); - } else { - /* We did not fully parse the payload, something must be wrong. */ - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } -} - -static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk, - struct mg_mqtt_message *msg) { - struct mg_mqtt_session *s; - size_t i; - - for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) { - for (i = 0; i < s->num_subscriptions; i++) { - if (mg_mqtt_vmatch_topic_expression(s->subscriptions[i].topic, - msg->topic)) { - char buf[100], *p = buf; - mg_asprintf(&p, sizeof(buf), "%.*s", (int) msg->topic.len, - msg->topic.p); - if (p == NULL) { - return; - } - mg_mqtt_publish(s->nc, p, 0, 0, msg->payload.p, msg->payload.len); - if (p != buf) { - MG_FREE(p); - } - break; - } - } - } -} - -void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) { - struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data; - struct mg_mqtt_broker *brk; - - if (nc->listener) { - brk = (struct mg_mqtt_broker *) nc->listener->priv_2; - } else { - brk = (struct mg_mqtt_broker *) nc->priv_2; - } - - switch (ev) { - case MG_EV_ACCEPT: - if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc); - nc->priv_2 = NULL; /* Clear up the inherited pointer to broker */ - break; - case MG_EV_MQTT_CONNECT: - if (nc->priv_2 == NULL) { - mg_mqtt_broker_handle_connect(brk, nc); - } else { - /* Repeated CONNECT */ - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } - break; - case MG_EV_MQTT_SUBSCRIBE: - if (nc->priv_2 != NULL) { - mg_mqtt_broker_handle_subscribe(nc, msg); - } else { - /* Subscribe before CONNECT */ - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } - break; - case MG_EV_MQTT_PUBLISH: - if (nc->priv_2 != NULL) { - mg_mqtt_broker_handle_publish(brk, msg); - } else { - /* Publish before CONNECT */ - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } - break; - case MG_EV_CLOSE: - if (nc->listener && nc->priv_2 != NULL) { - mg_mqtt_close_session((struct mg_mqtt_session *) nc->priv_2); - } - break; - } -} - -struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk, - struct mg_mqtt_session *s) { - return s == NULL ? LIST_FIRST(&brk->sessions) : LIST_NEXT(s, link); -} - -#endif /* MG_ENABLE_MQTT_BROKER */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_dns.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_DNS - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_dns.h" */ - -static int mg_dns_tid = 0xa0; - -struct mg_dns_header { - uint16_t transaction_id; - uint16_t flags; - uint16_t num_questions; - uint16_t num_answers; - uint16_t num_authority_prs; - uint16_t num_other_prs; -}; - -struct mg_dns_resource_record *mg_dns_next_record( - struct mg_dns_message *msg, int query, - struct mg_dns_resource_record *prev) { - struct mg_dns_resource_record *rr; - - for (rr = (prev == NULL ? msg->answers : prev + 1); - rr - msg->answers < msg->num_answers; rr++) { - if (rr->rtype == query) { - return rr; - } - } - return NULL; -} - -int mg_dns_parse_record_data(struct mg_dns_message *msg, - struct mg_dns_resource_record *rr, void *data, - size_t data_len) { - switch (rr->rtype) { - case MG_DNS_A_RECORD: - if (data_len < sizeof(struct in_addr)) { - return -1; - } - if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) { - return -1; - } - memcpy(data, rr->rdata.p, data_len); - return 0; -#if MG_ENABLE_IPV6 - case MG_DNS_AAAA_RECORD: - if (data_len < sizeof(struct in6_addr)) { - return -1; /* LCOV_EXCL_LINE */ - } - memcpy(data, rr->rdata.p, data_len); - return 0; -#endif - case MG_DNS_CNAME_RECORD: - mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len); - return 0; - } - - return -1; -} - -int mg_dns_insert_header(struct mbuf *io, size_t pos, - struct mg_dns_message *msg) { - struct mg_dns_header header; - - memset(&header, 0, sizeof(header)); - header.transaction_id = msg->transaction_id; - header.flags = htons(msg->flags); - header.num_questions = htons(msg->num_questions); - header.num_answers = htons(msg->num_answers); - - return mbuf_insert(io, pos, &header, sizeof(header)); -} - -int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) { - unsigned char *begin, *end; - struct mg_dns_resource_record *last_q; - if (msg->num_questions <= 0) return 0; - begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header); - last_q = &msg->questions[msg->num_questions - 1]; - end = (unsigned char *) last_q->name.p + last_q->name.len + 4; - return mbuf_append(io, begin, end - begin); -} - -int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) { - const char *s; - unsigned char n; - size_t pos = io->len; - - do { - if ((s = strchr(name, '.')) == NULL) { - s = name + len; - } - - if (s - name > 127) { - return -1; /* TODO(mkm) cover */ - } - n = s - name; /* chunk length */ - mbuf_append(io, &n, 1); /* send length */ - mbuf_append(io, name, n); - - if (*s == '.') { - n++; - } - - name += n; - len -= n; - } while (*s != '\0'); - mbuf_append(io, "\0", 1); /* Mark end of host name */ - - return io->len - pos; -} - -int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr, - const char *name, size_t nlen, const void *rdata, - size_t rlen) { - size_t pos = io->len; - uint16_t u16; - uint32_t u32; - - if (rr->kind == MG_DNS_INVALID_RECORD) { - return -1; /* LCOV_EXCL_LINE */ - } - - if (mg_dns_encode_name(io, name, nlen) == -1) { - return -1; - } - - u16 = htons(rr->rtype); - mbuf_append(io, &u16, 2); - u16 = htons(rr->rclass); - mbuf_append(io, &u16, 2); - - if (rr->kind == MG_DNS_ANSWER) { - u32 = htonl(rr->ttl); - mbuf_append(io, &u32, 4); - - if (rr->rtype == MG_DNS_CNAME_RECORD) { - int clen; - /* fill size after encoding */ - size_t off = io->len; - mbuf_append(io, &u16, 2); - if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) { - return -1; - } - u16 = clen; - io->buf[off] = u16 >> 8; - io->buf[off + 1] = u16 & 0xff; - } else { - u16 = htons((uint16_t) rlen); - mbuf_append(io, &u16, 2); - mbuf_append(io, rdata, rlen); - } - } - - return io->len - pos; -} - -void mg_send_dns_query(struct mg_connection *nc, const char *name, - int query_type) { - struct mg_dns_message *msg = - (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg)); - struct mbuf pkt; - struct mg_dns_resource_record *rr = &msg->questions[0]; - - DBG(("%s %d", name, query_type)); - - mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */); - - msg->transaction_id = ++mg_dns_tid; - msg->flags = 0x100; - msg->num_questions = 1; - - mg_dns_insert_header(&pkt, 0, msg); - - rr->rtype = query_type; - rr->rclass = 1; /* Class: inet */ - rr->kind = MG_DNS_QUESTION; - - if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) { - /* TODO(mkm): return an error code */ - goto cleanup; /* LCOV_EXCL_LINE */ - } - - /* TCP DNS requires messages to be prefixed with len */ - if (!(nc->flags & MG_F_UDP)) { - uint16_t len = htons((uint16_t) pkt.len); - mbuf_insert(&pkt, 0, &len, 2); - } - - mg_send(nc, pkt.buf, pkt.len); - mbuf_free(&pkt); - -cleanup: - MG_FREE(msg); -} - -static unsigned char *mg_parse_dns_resource_record( - unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr, - int reply) { - unsigned char *name = data; - int chunk_len, data_len; - - while (data < end && (chunk_len = *data)) { - if (((unsigned char *) data)[0] & 0xc0) { - data += 1; - break; - } - data += chunk_len + 1; - } - - if (data > end - 5) { - return NULL; - } - - rr->name.p = (char *) name; - rr->name.len = data - name + 1; - data++; - - rr->rtype = data[0] << 8 | data[1]; - data += 2; - - rr->rclass = data[0] << 8 | data[1]; - data += 2; - - rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION; - if (reply) { - if (data >= end - 6) { - return NULL; - } - - rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 | - data[2] << 8 | data[3]; - data += 4; - - data_len = *data << 8 | *(data + 1); - data += 2; - - rr->rdata.p = (char *) data; - rr->rdata.len = data_len; - data += data_len; - } - return data; -} - -int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) { - struct mg_dns_header *header = (struct mg_dns_header *) buf; - unsigned char *data = (unsigned char *) buf + sizeof(*header); - unsigned char *end = (unsigned char *) buf + len; - int i; - - memset(msg, 0, sizeof(*msg)); - msg->pkt.p = buf; - msg->pkt.len = len; - - if (len < (int) sizeof(*header)) return -1; - - msg->transaction_id = header->transaction_id; - msg->flags = ntohs(header->flags); - msg->num_questions = ntohs(header->num_questions); - if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) { - msg->num_questions = (int) ARRAY_SIZE(msg->questions); - } - msg->num_answers = ntohs(header->num_answers); - if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) { - msg->num_answers = (int) ARRAY_SIZE(msg->answers); - } - - for (i = 0; i < msg->num_questions; i++) { - data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0); - if (data == NULL) return -1; - } - - for (i = 0; i < msg->num_answers; i++) { - data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1); - if (data == NULL) return -1; - } - - return 0; -} - -size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name, - char *dst, int dst_len) { - int chunk_len, num_ptrs = 0; - char *old_dst = dst; - const unsigned char *data = (unsigned char *) name->p; - const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len; - - if (data >= end) { - return 0; - } - - while ((chunk_len = *data++)) { - int leeway = dst_len - (dst - old_dst); - if (data >= end) { - return 0; - } - - if ((chunk_len & 0xc0) == 0xc0) { - uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0]; - if (off >= msg->pkt.len) { - return 0; - } - /* Basic circular loop avoidance: allow up to 16 pointer hops. */ - if (++num_ptrs > 15) { - return 0; - } - data = (unsigned char *) msg->pkt.p + off; - continue; - } - if (chunk_len > 63) { - return 0; - } - if (chunk_len > leeway) { - chunk_len = leeway; - } - - if (data + chunk_len >= end) { - return 0; - } - - memcpy(dst, data, chunk_len); - data += chunk_len; - dst += chunk_len; - leeway -= chunk_len; - if (leeway == 0) { - return dst - old_dst; - } - *dst++ = '.'; - } - - if (dst != old_dst) { - *--dst = 0; - } - return dst - old_dst; -} - -static void dns_handler(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { - struct mbuf *io = &nc->recv_mbuf; - struct mg_dns_message msg; - - /* Pass low-level events to the user handler */ - nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); - - switch (ev) { - case MG_EV_RECV: - if (!(nc->flags & MG_F_UDP)) { - mbuf_remove(&nc->recv_mbuf, 2); - } - if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) { - /* reply + recursion allowed + format error */ - memset(&msg, 0, sizeof(msg)); - msg.flags = 0x8081; - mg_dns_insert_header(io, 0, &msg); - if (!(nc->flags & MG_F_UDP)) { - uint16_t len = htons((uint16_t) io->len); - mbuf_insert(io, 0, &len, 2); - } - mg_send(nc, io->buf, io->len); - } else { - /* Call user handler with parsed message */ - nc->handler(nc, MG_DNS_MESSAGE, &msg MG_UD_ARG(user_data)); - } - mbuf_remove(io, io->len); - break; - } -} - -void mg_set_protocol_dns(struct mg_connection *nc) { - nc->proto_handler = dns_handler; -} - -#endif /* MG_ENABLE_DNS */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_dns_server.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_DNS_SERVER - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "dns-server.h" */ - -struct mg_dns_reply mg_dns_create_reply(struct mbuf *io, - struct mg_dns_message *msg) { - struct mg_dns_reply rep; - rep.msg = msg; - rep.io = io; - rep.start = io->len; - - /* reply + recursion allowed */ - msg->flags |= 0x8080; - mg_dns_copy_questions(io, msg); - - msg->num_answers = 0; - return rep; -} - -void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) { - size_t sent = r->io->len - r->start; - mg_dns_insert_header(r->io, r->start, r->msg); - if (!(nc->flags & MG_F_UDP)) { - uint16_t len = htons((uint16_t) sent); - mbuf_insert(r->io, r->start, &len, 2); - } - - if (&nc->send_mbuf != r->io) { - mg_send(nc, r->io->buf + r->start, r->io->len - r->start); - r->io->len = r->start; - } -} - -int mg_dns_reply_record(struct mg_dns_reply *reply, - struct mg_dns_resource_record *question, - const char *name, int rtype, int ttl, const void *rdata, - size_t rdata_len) { - struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg; - char rname[512]; - struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers]; - if (msg->num_answers >= MG_MAX_DNS_ANSWERS) { - return -1; /* LCOV_EXCL_LINE */ - } - - if (name == NULL) { - name = rname; - rname[511] = 0; - mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1); - } - - *ans = *question; - ans->kind = MG_DNS_ANSWER; - ans->rtype = rtype; - ans->ttl = ttl; - - if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata, - rdata_len) == -1) { - return -1; /* LCOV_EXCL_LINE */ - }; - - msg->num_answers++; - return 0; -} - -#endif /* MG_ENABLE_DNS_SERVER */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_resolv.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_ASYNC_RESOLVER - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_resolv.h" */ - -#ifndef MG_DEFAULT_NAMESERVER -#define MG_DEFAULT_NAMESERVER "8.8.8.8" -#endif - -struct mg_resolve_async_request { - char name[1024]; - int query; - mg_resolve_callback_t callback; - void *data; - time_t timeout; - int max_retries; - enum mg_resolve_err err; - - /* state */ - time_t last_time; - int retries; -}; - -/* - * Find what nameserver to use. - * - * Return 0 if OK, -1 if error - */ -static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) { - int ret = -1; - -#ifdef _WIN32 - int i; - LONG err; - HKEY hKey, hSub; - wchar_t subkey[512], value[128], - *key = L"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces"; - - if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey)) != - ERROR_SUCCESS) { - fprintf(stderr, "cannot open reg key %S: %ld\n", key, err); - ret = -1; - } else { - for (ret = -1, i = 0; 1; i++) { - DWORD subkey_size = sizeof(subkey), type, len = sizeof(value); - if (RegEnumKeyExW(hKey, i, subkey, &subkey_size, NULL, NULL, NULL, - NULL) != ERROR_SUCCESS) { - break; - } - if (RegOpenKeyExW(hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS && - ((RegQueryValueExW(hSub, L"NameServer", 0, &type, (void *) value, - &len) == ERROR_SUCCESS && - value[0] != '\0') || - (RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value, - &len) == ERROR_SUCCESS && - value[0] != '\0'))) { - /* - * See https://github.com/cesanta/mongoose/issues/176 - * The value taken from the registry can be empty, a single - * IP address, or multiple IP addresses separated by comma. - * If it's empty, check the next interface. - * If it's multiple IP addresses, take the first one. - */ - wchar_t *comma = wcschr(value, ','); - if (comma != NULL) { - *comma = '\0'; - } - /* %S will convert wchar_t -> char */ - snprintf(name, name_len, "%S", value); - ret = 0; - RegCloseKey(hSub); - break; - } - } - RegCloseKey(hKey); - } -#elif MG_ENABLE_FILESYSTEM && defined(MG_RESOLV_CONF_FILE_NAME) - FILE *fp; - char line[512]; - - if ((fp = mg_fopen(MG_RESOLV_CONF_FILE_NAME, "r")) == NULL) { - ret = -1; - } else { - /* Try to figure out what nameserver to use */ - for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) { - unsigned int a, b, c, d; - if (sscanf(line, "nameserver %u.%u.%u.%u", &a, &b, &c, &d) == 4) { - snprintf(name, name_len, "%u.%u.%u.%u", a, b, c, d); - ret = 0; - break; - } - } - (void) fclose(fp); - } -#else - snprintf(name, name_len, "%s", MG_DEFAULT_NAMESERVER); -#endif /* _WIN32 */ - - return ret; -} - -int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) { -#if MG_ENABLE_FILESYSTEM && defined(MG_HOSTS_FILE_NAME) - /* TODO(mkm) cache /etc/hosts */ - FILE *fp; - char line[1024]; - char *p; - char alias[256]; - unsigned int a, b, c, d; - int len = 0; - - if ((fp = mg_fopen(MG_HOSTS_FILE_NAME, "r")) == NULL) { - return -1; - } - - for (; fgets(line, sizeof(line), fp) != NULL;) { - if (line[0] == '#') continue; - - if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) { - /* TODO(mkm): handle ipv6 */ - continue; - } - for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) { - if (strcmp(alias, name) == 0) { - usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d); - fclose(fp); - return 0; - } - } - } - - fclose(fp); -#else - (void) name; - (void) usa; -#endif - - return -1; -} - -static void mg_resolve_async_eh(struct mg_connection *nc, int ev, - void *data MG_UD_ARG(void *user_data)) { - time_t now = (time_t) mg_time(); - struct mg_resolve_async_request *req; - struct mg_dns_message *msg; -#if !MG_ENABLE_CALLBACK_USERDATA - void *user_data = nc->user_data; -#endif - - if (ev != MG_EV_POLL) { - DBG(("ev=%d user_data=%p", ev, user_data)); - } - - req = (struct mg_resolve_async_request *) user_data; - - if (req == NULL) { - return; - } - - switch (ev) { - case MG_EV_POLL: - if (req->retries > req->max_retries) { - req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT; - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - break; - } - if (nc->flags & MG_F_CONNECTING) break; - /* fallthrough */ - case MG_EV_CONNECT: - if (req->retries == 0 || now - req->last_time >= req->timeout) { - mg_send_dns_query(nc, req->name, req->query); - req->last_time = now; - req->retries++; - } - break; - case MG_EV_RECV: - msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg)); - if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 && - msg->num_answers > 0) { - req->callback(msg, req->data, MG_RESOLVE_OK); - nc->user_data = NULL; - MG_FREE(req); - } else { - req->err = MG_RESOLVE_NO_ANSWERS; - } - MG_FREE(msg); - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - break; - case MG_EV_SEND: - /* - * If a send error occurs, prevent closing of the connection by the core. - * We will retry after timeout. - */ - nc->flags &= ~MG_F_CLOSE_IMMEDIATELY; - mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len); - break; - case MG_EV_TIMER: - req->err = MG_RESOLVE_TIMEOUT; - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - break; - case MG_EV_CLOSE: - /* If we got here with request still not done, fire an error callback. */ - if (req != NULL) { - char addr[32]; - mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP); -#ifdef MG_LOG_DNS_FAILURES - LOG(LL_ERROR, ("Failed to resolve '%s', server %s", req->name, addr)); -#endif - req->callback(NULL, req->data, req->err); - nc->user_data = NULL; - MG_FREE(req); - } - break; - } -} - -int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query, - mg_resolve_callback_t cb, void *data) { - struct mg_resolve_async_opts opts; - memset(&opts, 0, sizeof(opts)); - return mg_resolve_async_opt(mgr, name, query, cb, data, opts); -} - -int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query, - mg_resolve_callback_t cb, void *data, - struct mg_resolve_async_opts opts) { - struct mg_resolve_async_request *req; - struct mg_connection *dns_nc; - const char *nameserver = opts.nameserver; - char dns_server_buff[17], nameserver_url[26]; - - if (nameserver == NULL) { - nameserver = mgr->nameserver; - } - - DBG(("%s %d %p", name, query, opts.dns_conn)); - - /* resolve with DNS */ - req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req)); - if (req == NULL) { - return -1; - } - - strncpy(req->name, name, sizeof(req->name)); - req->name[sizeof(req->name) - 1] = '\0'; - - req->query = query; - req->callback = cb; - req->data = data; - /* TODO(mkm): parse defaults out of resolve.conf */ - req->max_retries = opts.max_retries ? opts.max_retries : 2; - req->timeout = opts.timeout ? opts.timeout : 5; - - /* Lazily initialize dns server */ - if (nameserver == NULL) { - if (mg_get_ip_address_of_nameserver(dns_server_buff, - sizeof(dns_server_buff)) != -1) { - nameserver = dns_server_buff; - } else { - nameserver = MG_DEFAULT_NAMESERVER; - } - } - - snprintf(nameserver_url, sizeof(nameserver_url), "udp://%s:53", nameserver); - - dns_nc = mg_connect(mgr, nameserver_url, MG_CB(mg_resolve_async_eh, NULL)); - if (dns_nc == NULL) { - MG_FREE(req); - return -1; - } - dns_nc->user_data = req; - if (opts.dns_conn != NULL) { - *opts.dns_conn = dns_nc; - } - - return 0; -} - -void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver) { - MG_FREE((char *) mgr->nameserver); - mgr->nameserver = NULL; - if (nameserver != NULL) { - mgr->nameserver = strdup(nameserver); - } -} - -#endif /* MG_ENABLE_ASYNC_RESOLVER */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_coap.c" -#endif -/* - * Copyright (c) 2015 Cesanta Software Limited - * All rights reserved - * This software is dual-licensed: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. For the terms of this - * license, see . - * - * You are free to use this software under the terms of the GNU General - * Public License, but WITHOUT ANY WARRANTY; without even the implied - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * Alternatively, you can license this software under a commercial - * license, as set out in . - */ - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_coap.h" */ - -#if MG_ENABLE_COAP - -void mg_coap_free_options(struct mg_coap_message *cm) { - while (cm->options != NULL) { - struct mg_coap_option *next = cm->options->next; - MG_FREE(cm->options); - cm->options = next; - } -} - -struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm, - uint32_t number, char *value, - size_t len) { - struct mg_coap_option *new_option = - (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option)); - - new_option->number = number; - new_option->value.p = value; - new_option->value.len = len; - - if (cm->options == NULL) { - cm->options = cm->optiomg_tail = new_option; - } else { - /* - * A very simple attention to help clients to compose options: - * CoAP wants to see options ASC ordered. - * Could be change by using sort in coap_compose - */ - if (cm->optiomg_tail->number <= new_option->number) { - /* if option is already ordered just add it */ - cm->optiomg_tail = cm->optiomg_tail->next = new_option; - } else { - /* looking for appropriate position */ - struct mg_coap_option *current_opt = cm->options; - struct mg_coap_option *prev_opt = 0; - - while (current_opt != NULL) { - if (current_opt->number > new_option->number) { - break; - } - prev_opt = current_opt; - current_opt = current_opt->next; - } - - if (prev_opt != NULL) { - prev_opt->next = new_option; - new_option->next = current_opt; - } else { - /* insert new_option to the beginning */ - new_option->next = cm->options; - cm->options = new_option; - } - } - } - - return new_option; -} - -/* - * Fills CoAP header in mg_coap_message. - * - * Helper function. - */ -static char *coap_parse_header(char *ptr, struct mbuf *io, - struct mg_coap_message *cm) { - if (io->len < sizeof(uint32_t)) { - cm->flags |= MG_COAP_NOT_ENOUGH_DATA; - return NULL; - } - - /* - * Version (Ver): 2-bit unsigned integer. Indicates the CoAP version - * number. Implementations of this specification MUST set this field - * to 1 (01 binary). Other values are reserved for future versions. - * Messages with unknown version numbers MUST be silently ignored. - */ - if (((uint8_t) *ptr >> 6) != 1) { - cm->flags |= MG_COAP_IGNORE; - return NULL; - } - - /* - * Type (T): 2-bit unsigned integer. Indicates if this message is of - * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or - * Reset (3). - */ - cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4; - cm->flags |= MG_COAP_MSG_TYPE_FIELD; - - /* - * Token Length (TKL): 4-bit unsigned integer. Indicates the length of - * the variable-length Token field (0-8 bytes). Lengths 9-15 are - * reserved, MUST NOT be sent, and MUST be processed as a message - * format error. - */ - cm->token.len = *ptr & 0x0F; - if (cm->token.len > 8) { - cm->flags |= MG_COAP_FORMAT_ERROR; - return NULL; - } - - ptr++; - - /* - * Code: 8-bit unsigned integer, split into a 3-bit class (most - * significant bits) and a 5-bit detail (least significant bits) - */ - cm->code_class = (uint8_t) *ptr >> 5; - cm->code_detail = *ptr & 0x1F; - cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD); - - ptr++; - - /* Message ID: 16-bit unsigned integer in network byte order. */ - cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1); - cm->flags |= MG_COAP_MSG_ID_FIELD; - - ptr += 2; - - return ptr; -} - -/* - * Fills token information in mg_coap_message. - * - * Helper function. - */ -static char *coap_get_token(char *ptr, struct mbuf *io, - struct mg_coap_message *cm) { - if (cm->token.len != 0) { - if (ptr + cm->token.len > io->buf + io->len) { - cm->flags |= MG_COAP_NOT_ENOUGH_DATA; - return NULL; - } else { - cm->token.p = ptr; - ptr += cm->token.len; - cm->flags |= MG_COAP_TOKEN_FIELD; - } - } - - return ptr; -} - -/* - * Returns Option Delta or Length. - * - * Helper function. - */ -static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) { - int ret = 0; - - if (*opt_info == 13) { - /* - * 13: An 8-bit unsigned integer follows the initial byte and - * indicates the Option Delta/Length minus 13. - */ - if (ptr < io->buf + io->len) { - *opt_info = (uint8_t) *ptr + 13; - ret = sizeof(uint8_t); - } else { - ret = -1; /* LCOV_EXCL_LINE */ - } - } else if (*opt_info == 14) { - /* - * 14: A 16-bit unsigned integer in network byte order follows the - * initial byte and indicates the Option Delta/Length minus 269. - */ - if (ptr + sizeof(uint8_t) < io->buf + io->len) { - *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269; - ret = sizeof(uint16_t); - } else { - ret = -1; /* LCOV_EXCL_LINE */ - } - } - - return ret; -} - -/* - * Fills options in mg_coap_message. - * - * Helper function. - * - * General options format: - * +---------------+---------------+ - * | Option Delta | Option Length | 1 byte - * +---------------+---------------+ - * \ Option Delta (extended) \ 0-2 bytes - * +-------------------------------+ - * / Option Length (extended) \ 0-2 bytes - * +-------------------------------+ - * \ Option Value \ 0 or more bytes - * +-------------------------------+ - */ -static char *coap_get_options(char *ptr, struct mbuf *io, - struct mg_coap_message *cm) { - uint16_t prev_opt = 0; - - if (ptr == io->buf + io->len) { - /* end of packet, ok */ - return NULL; - } - - /* 0xFF is payload marker */ - while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) { - uint16_t option_delta, option_lenght; - int optinfo_len; - - /* Option Delta: 4-bit unsigned integer */ - option_delta = ((uint8_t) *ptr & 0xF0) >> 4; - /* Option Length: 4-bit unsigned integer */ - option_lenght = *ptr & 0x0F; - - if (option_delta == 15 || option_lenght == 15) { - /* - * 15: Reserved for future use. If the field is set to this value, - * it MUST be processed as a message format error - */ - cm->flags |= MG_COAP_FORMAT_ERROR; - break; - } - - ptr++; - - /* check for extended option delta */ - optinfo_len = coap_get_ext_opt(ptr, io, &option_delta); - if (optinfo_len == -1) { - cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ - break; /* LCOV_EXCL_LINE */ - } - - ptr += optinfo_len; - - /* check or extended option lenght */ - optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght); - if (optinfo_len == -1) { - cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ - break; /* LCOV_EXCL_LINE */ - } - - ptr += optinfo_len; - - /* - * Instead of specifying the Option Number directly, the instances MUST - * appear in order of their Option Numbers and a delta encoding is used - * between them. - */ - option_delta += prev_opt; - - mg_coap_add_option(cm, option_delta, ptr, option_lenght); - - prev_opt = option_delta; - - if (ptr + option_lenght > io->buf + io->len) { - cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ - break; /* LCOV_EXCL_LINE */ - } - - ptr += option_lenght; - } - - if ((cm->flags & MG_COAP_ERROR) != 0) { - mg_coap_free_options(cm); - return NULL; - } - - cm->flags |= MG_COAP_OPTIOMG_FIELD; - - if (ptr == io->buf + io->len) { - /* end of packet, ok */ - return NULL; - } - - ptr++; - - return ptr; -} - -uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) { - char *ptr; - - memset(cm, 0, sizeof(*cm)); - - if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) { - return cm->flags; - } - - if ((ptr = coap_get_token(ptr, io, cm)) == NULL) { - return cm->flags; - } - - if ((ptr = coap_get_options(ptr, io, cm)) == NULL) { - return cm->flags; - } - - /* the rest is payload */ - cm->payload.len = io->len - (ptr - io->buf); - if (cm->payload.len != 0) { - cm->payload.p = ptr; - cm->flags |= MG_COAP_PAYLOAD_FIELD; - } - - return cm->flags; -} - -/* - * Calculates extended size of given Opt Number/Length in coap message. - * - * Helper function. - */ -static size_t coap_get_ext_opt_size(uint32_t value) { - int ret = 0; - - if (value >= 13 && value <= 0xFF + 13) { - ret = sizeof(uint8_t); - } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) { - ret = sizeof(uint16_t); - } - - return ret; -} - -/* - * Splits given Opt Number/Length into base and ext values. - * - * Helper function. - */ -static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) { - int ret = 0; - - if (value < 13) { - *base = value; - } else if (value >= 13 && value <= 0xFF + 13) { - *base = 13; - *ext = value - 13; - ret = sizeof(uint8_t); - } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) { - *base = 14; - *ext = value - 269; - ret = sizeof(uint16_t); - } - - return ret; -} - -/* - * Puts uint16_t (in network order) into given char stream. - * - * Helper function. - */ -static char *coap_add_uint16(char *ptr, uint16_t val) { - *ptr = val >> 8; - ptr++; - *ptr = val & 0x00FF; - ptr++; - return ptr; -} - -/* - * Puts extended value of Opt Number/Length into given char stream. - * - * Helper function. - */ -static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) { - if (len == sizeof(uint8_t)) { - *ptr = (char) val; - ptr++; - } else if (len == sizeof(uint16_t)) { - ptr = coap_add_uint16(ptr, val); - } - - return ptr; -} - -/* - * Verifies given mg_coap_message and calculates message size for it. - * - * Helper function. - */ -static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm, - size_t *len) { - struct mg_coap_option *opt; - uint32_t prev_opt_number; - - *len = 4; /* header */ - if (cm->msg_type > MG_COAP_MSG_MAX) { - return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD; - } - if (cm->token.len > 8) { - return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD; - } - if (cm->code_class > 7) { - return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD; - } - if (cm->code_detail > 31) { - return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD; - } - - *len += cm->token.len; - if (cm->payload.len != 0) { - *len += cm->payload.len + 1; /* ... + 1; add payload marker */ - } - - opt = cm->options; - prev_opt_number = 0; - while (opt != NULL) { - *len += 1; /* basic delta/length */ - *len += coap_get_ext_opt_size(opt->number - prev_opt_number); - *len += coap_get_ext_opt_size((uint32_t) opt->value.len); - /* - * Current implementation performs check if - * option_number > previous option_number and produces an error - * TODO(alashkin): write design doc with limitations - * May be resorting is more suitable solution. - */ - if ((opt->next != NULL && opt->number > opt->next->number) || - opt->value.len > 0xFFFF + 269 || - opt->number - prev_opt_number > 0xFFFF + 269) { - return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD; - } - *len += opt->value.len; - prev_opt_number = opt->number; - opt = opt->next; - } - - return 0; -} - -uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) { - struct mg_coap_option *opt; - uint32_t res, prev_opt_number; - size_t prev_io_len, packet_size; - char *ptr; - - res = coap_calculate_packet_size(cm, &packet_size); - if (res != 0) { - return res; - } - - /* saving previous lenght to handle non-empty mbuf */ - prev_io_len = io->len; - if (mbuf_append(io, NULL, packet_size) == 0) return MG_COAP_ERROR; - ptr = io->buf + prev_io_len; - - /* - * since cm is verified, it is possible to use bits shift operator - * without additional zeroing of unused bits - */ - - /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */ - *ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len); - ptr++; - - /* code class: 3 bits, code detail: 5 bits */ - *ptr = (cm->code_class << 5) | (cm->code_detail); - ptr++; - - ptr = coap_add_uint16(ptr, cm->msg_id); - - if (cm->token.len != 0) { - memcpy(ptr, cm->token.p, cm->token.len); - ptr += cm->token.len; - } - - opt = cm->options; - prev_opt_number = 0; - while (opt != NULL) { - uint8_t delta_base = 0, length_base = 0; - uint16_t delta_ext = 0, length_ext = 0; - - size_t opt_delta_len = - coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext); - size_t opt_lenght_len = - coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext); - - *ptr = (delta_base << 4) | length_base; - ptr++; - - ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len); - ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len); - - if (opt->value.len != 0) { - memcpy(ptr, opt->value.p, opt->value.len); - ptr += opt->value.len; - } - - prev_opt_number = opt->number; - opt = opt->next; - } - - if (cm->payload.len != 0) { - *ptr = (char) -1; - ptr++; - memcpy(ptr, cm->payload.p, cm->payload.len); - } - - return 0; -} - -uint32_t mg_coap_send_message(struct mg_connection *nc, - struct mg_coap_message *cm) { - struct mbuf packet_out; - uint32_t compose_res; - - mbuf_init(&packet_out, 0); - compose_res = mg_coap_compose(cm, &packet_out); - if (compose_res != 0) { - return compose_res; /* LCOV_EXCL_LINE */ - } - - mg_send(nc, packet_out.buf, (int) packet_out.len); - mbuf_free(&packet_out); - - return 0; -} - -uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) { - struct mg_coap_message cm; - memset(&cm, 0, sizeof(cm)); - cm.msg_type = MG_COAP_MSG_ACK; - cm.msg_id = msg_id; - - return mg_coap_send_message(nc, &cm); -} - -static void coap_handler(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { - struct mbuf *io = &nc->recv_mbuf; - struct mg_coap_message cm; - uint32_t parse_res; - - memset(&cm, 0, sizeof(cm)); - - nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); - - switch (ev) { - case MG_EV_RECV: - parse_res = mg_coap_parse(io, &cm); - if ((parse_res & MG_COAP_IGNORE) == 0) { - if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) { - /* - * Since we support UDP only - * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR - */ - cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */ - } /* LCOV_EXCL_LINE */ - nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type, - &cm MG_UD_ARG(user_data)); - } - - mg_coap_free_options(&cm); - mbuf_remove(io, io->len); - break; - } -} -/* - * Attach built-in CoAP event handler to the given connection. - * - * The user-defined event handler will receive following extra events: - * - * - MG_EV_COAP_CON - * - MG_EV_COAP_NOC - * - MG_EV_COAP_ACK - * - MG_EV_COAP_RST - */ -int mg_set_protocol_coap(struct mg_connection *nc) { - /* supports UDP only */ - if ((nc->flags & MG_F_UDP) == 0) { - return -1; - } - - nc->proto_handler = coap_handler; - - return 0; -} - -#endif /* MG_ENABLE_COAP */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_sntp.c" -#endif -/* - * Copyright (c) 2016 Cesanta Software Limited - * All rights reserved - */ - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_sntp.h" */ -/* Amalgamated: #include "mg_util.h" */ - -#if MG_ENABLE_SNTP - -#define SNTP_TIME_OFFSET 2208988800 - -#ifndef SNTP_TIMEOUT -#define SNTP_TIMEOUT 10 -#endif - -#ifndef SNTP_ATTEMPTS -#define SNTP_ATTEMPTS 3 -#endif - -static uint64_t mg_get_sec(uint64_t val) { - return (val & 0xFFFFFFFF00000000) >> 32; -} - -static uint64_t mg_get_usec(uint64_t val) { - uint64_t tmp = (val & 0x00000000FFFFFFFF); - tmp *= 1000000; - tmp >>= 32; - return tmp; -} - -static void mg_ntp_to_tv(uint64_t val, struct timeval *tv) { - uint64_t tmp; - tmp = mg_get_sec(val); - tmp -= SNTP_TIME_OFFSET; - tv->tv_sec = tmp; - tv->tv_usec = mg_get_usec(val); -} - -static void mg_get_ntp_ts(const char *ntp, uint64_t *val) { - uint32_t tmp; - memcpy(&tmp, ntp, sizeof(tmp)); - tmp = ntohl(tmp); - *val = (uint64_t) tmp << 32; - memcpy(&tmp, ntp + 4, sizeof(tmp)); - tmp = ntohl(tmp); - *val |= tmp; -} - -void mg_sntp_send_request(struct mg_connection *c) { - uint8_t buf[48] = {0}; - /* - * header - 8 bit: - * LI (2 bit) - 3 (not in sync), VN (3 bit) - 4 (version), - * mode (3 bit) - 3 (client) - */ - buf[0] = (3 << 6) | (4 << 3) | 3; - -/* - * Next fields should be empty in client request - * stratum, 8 bit - * poll interval, 8 bit - * rrecision, 8 bit - * root delay, 32 bit - * root dispersion, 32 bit - * ref id, 32 bit - * ref timestamp, 64 bit - * originate Timestamp, 64 bit - * receive Timestamp, 64 bit -*/ - -/* - * convert time to sntp format (sntp starts from 00:00:00 01.01.1900) - * according to rfc868 it is 2208988800L sec - * this information is used to correct roundtrip delay - * but if local clock is absolutely broken (and doesn't work even - * as simple timer), it is better to disable it -*/ -#ifndef MG_SNTP_NO_DELAY_CORRECTION - uint32_t sec; - sec = htonl((uint32_t)(mg_time() + SNTP_TIME_OFFSET)); - memcpy(&buf[40], &sec, sizeof(sec)); -#endif - - mg_send(c, buf, sizeof(buf)); -} - -#ifndef MG_SNTP_NO_DELAY_CORRECTION -static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) { - /* roundloop delay = (T4 - T1) - (T3 - T2) */ - uint64_t d1 = ((mg_time() + SNTP_TIME_OFFSET) * 1000000) - - (mg_get_sec(t1) * 1000000 + mg_get_usec(t1)); - uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) - - (mg_get_sec(t2) * 1000000 + mg_get_usec(t2)); - - return (d1 > d2) ? d1 - d2 : 0; -} -#endif - -MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len, - struct mg_sntp_message *msg) { - uint8_t hdr; - uint64_t trsm_ts_T3, delay = 0; - int mode; - struct timeval tv; - - if (len < 48) { - return -1; - } - - hdr = buf[0]; - - if ((hdr & 0x38) >> 3 != 4) { - /* Wrong version */ - return -1; - } - - mode = hdr & 0x7; - if (mode != 4 && mode != 5) { - /* Not a server reply */ - return -1; - } - - memset(msg, 0, sizeof(*msg)); - - msg->kiss_of_death = (buf[1] == 0); /* Server asks to not send requests */ - - mg_get_ntp_ts(&buf[40], &trsm_ts_T3); - -#ifndef MG_SNTP_NO_DELAY_CORRECTION - { - uint64_t orig_ts_T1, recv_ts_T2; - mg_get_ntp_ts(&buf[24], &orig_ts_T1); - mg_get_ntp_ts(&buf[32], &recv_ts_T2); - delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3); - } -#endif - - mg_ntp_to_tv(trsm_ts_T3, &tv); - - msg->time = (double) tv.tv_sec + (((double) tv.tv_usec + delay) / 1000000.0); - - return 0; -} - -static void mg_sntp_handler(struct mg_connection *c, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { - struct mbuf *io = &c->recv_mbuf; - struct mg_sntp_message msg; - - c->handler(c, ev, ev_data MG_UD_ARG(user_data)); - - switch (ev) { - case MG_EV_RECV: { - if (mg_sntp_parse_reply(io->buf, io->len, &msg) < 0) { - DBG(("Invalid SNTP packet received (%d)", (int) io->len)); - c->handler(c, MG_SNTP_MALFORMED_REPLY, NULL MG_UD_ARG(user_data)); - } else { - c->handler(c, MG_SNTP_REPLY, (void *) &msg MG_UD_ARG(user_data)); - } - - mbuf_remove(io, io->len); - break; - } - } -} - -int mg_set_protocol_sntp(struct mg_connection *c) { - if ((c->flags & MG_F_UDP) == 0) { - return -1; - } - - c->proto_handler = mg_sntp_handler; - - return 0; -} - -struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, - MG_CB(mg_event_handler_t event_handler, - void *user_data), - const char *sntp_server_name) { - struct mg_connection *c = NULL; - char url[100], *p_url = url; - const char *proto = "", *port = "", *tmp; - - /* If port is not specified, use default (123) */ - tmp = strchr(sntp_server_name, ':'); - if (tmp != NULL && *(tmp + 1) == '/') { - tmp = strchr(tmp + 1, ':'); - } - - if (tmp == NULL) { - port = ":123"; - } - - /* Add udp:// if needed */ - if (strncmp(sntp_server_name, "udp://", 6) != 0) { - proto = "udp://"; - } - - mg_asprintf(&p_url, sizeof(url), "%s%s%s", proto, sntp_server_name, port); - - c = mg_connect(mgr, p_url, event_handler MG_UD_ARG(user_data)); - - if (c == NULL) { - goto cleanup; - } - - mg_set_protocol_sntp(c); - -cleanup: - if (p_url != url) { - MG_FREE(p_url); - } - - return c; -} - -struct sntp_data { - mg_event_handler_t hander; - int count; -}; - -static void mg_sntp_util_ev_handler(struct mg_connection *c, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { -#if !MG_ENABLE_CALLBACK_USERDATA - void *user_data = c->user_data; -#endif - struct sntp_data *sd = (struct sntp_data *) user_data; - - switch (ev) { - case MG_EV_CONNECT: - if (*(int *) ev_data != 0) { - mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); - break; - } - /* fallthrough */ - case MG_EV_TIMER: - if (sd->count <= SNTP_ATTEMPTS) { - mg_sntp_send_request(c); - mg_set_timer(c, mg_time() + 10); - sd->count++; - } else { - mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); - c->flags |= MG_F_CLOSE_IMMEDIATELY; - } - break; - case MG_SNTP_MALFORMED_REPLY: - mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); - c->flags |= MG_F_CLOSE_IMMEDIATELY; - break; - case MG_SNTP_REPLY: - mg_call(c, sd->hander, c->user_data, MG_SNTP_REPLY, ev_data); - c->flags |= MG_F_CLOSE_IMMEDIATELY; - break; - case MG_EV_CLOSE: - MG_FREE(user_data); - c->user_data = NULL; - break; - } -} - -struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr, - mg_event_handler_t event_handler, - const char *sntp_server_name) { - struct mg_connection *c; - struct sntp_data *sd = (struct sntp_data *) MG_CALLOC(1, sizeof(*sd)); - if (sd == NULL) { - return NULL; - } - - c = mg_sntp_connect(mgr, MG_CB(mg_sntp_util_ev_handler, sd), - sntp_server_name); - if (c == NULL) { - MG_FREE(sd); - return NULL; - } - - sd->hander = event_handler; -#if !MG_ENABLE_CALLBACK_USERDATA - c->user_data = sd; -#endif - - return c; -} - -#endif /* MG_ENABLE_SNTP */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_socks.c" -#endif -/* - * Copyright (c) 2017 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_SOCKS - -/* Amalgamated: #include "mg_socks.h" */ -/* Amalgamated: #include "mg_internal.h" */ - -/* - * https://www.ietf.org/rfc/rfc1928.txt paragraph 3, handle client handshake - * - * +----+----------+----------+ - * |VER | NMETHODS | METHODS | - * +----+----------+----------+ - * | 1 | 1 | 1 to 255 | - * +----+----------+----------+ - */ -static void mg_socks5_handshake(struct mg_connection *c) { - struct mbuf *r = &c->recv_mbuf; - if (r->buf[0] != MG_SOCKS_VERSION) { - c->flags |= MG_F_CLOSE_IMMEDIATELY; - } else if (r->len > 2 && (size_t) r->buf[1] + 2 <= r->len) { - /* https://www.ietf.org/rfc/rfc1928.txt paragraph 3 */ - unsigned char reply[2] = {MG_SOCKS_VERSION, MG_SOCKS_HANDSHAKE_FAILURE}; - int i; - for (i = 2; i < r->buf[1] + 2; i++) { - /* TODO(lsm): support other auth methods */ - if (r->buf[i] == MG_SOCKS_HANDSHAKE_NOAUTH) reply[1] = r->buf[i]; - } - mbuf_remove(r, 2 + r->buf[1]); - mg_send(c, reply, sizeof(reply)); - c->flags |= MG_SOCKS_HANDSHAKE_DONE; /* Mark handshake done */ - } -} - -static void disband(struct mg_connection *c) { - struct mg_connection *c2 = (struct mg_connection *) c->user_data; - if (c2 != NULL) { - c2->flags |= MG_F_SEND_AND_CLOSE; - c2->user_data = NULL; - } - c->flags |= MG_F_SEND_AND_CLOSE; - c->user_data = NULL; -} - -static void relay_data(struct mg_connection *c) { - struct mg_connection *c2 = (struct mg_connection *) c->user_data; - if (c2 != NULL) { - mg_send(c2, c->recv_mbuf.buf, c->recv_mbuf.len); - mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len); - } else { - c->flags |= MG_F_SEND_AND_CLOSE; - } -} - -static void serv_ev_handler(struct mg_connection *c, int ev, void *ev_data) { - if (ev == MG_EV_CLOSE) { - disband(c); - } else if (ev == MG_EV_RECV) { - relay_data(c); - } else if (ev == MG_EV_CONNECT) { - int res = *(int *) ev_data; - if (res != 0) LOG(LL_ERROR, ("connect error: %d", res)); - } -} - -static void mg_socks5_connect(struct mg_connection *c, const char *addr) { - struct mg_connection *serv = mg_connect(c->mgr, addr, serv_ev_handler); - serv->user_data = c; - c->user_data = serv; -} - -/* - * Request, https://www.ietf.org/rfc/rfc1928.txt paragraph 4 - * - * +----+-----+-------+------+----------+----------+ - * |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | - * +----+-----+-------+------+----------+----------+ - * | 1 | 1 | X'00' | 1 | Variable | 2 | - * +----+-----+-------+------+----------+----------+ - */ -static void mg_socks5_handle_request(struct mg_connection *c) { - struct mbuf *r = &c->recv_mbuf; - unsigned char *p = (unsigned char *) r->buf; - unsigned char addr_len = 4, reply = MG_SOCKS_SUCCESS; - int ver, cmd, atyp; - char addr[300]; - - if (r->len < 8) return; /* return if not fully buffered. min DST.ADDR is 2 */ - ver = p[0]; - cmd = p[1]; - atyp = p[3]; - - /* TODO(lsm): support other commands */ - if (ver != MG_SOCKS_VERSION || cmd != MG_SOCKS_CMD_CONNECT) { - reply = MG_SOCKS_CMD_NOT_SUPPORTED; - } else if (atyp == MG_SOCKS_ADDR_IPV4) { - addr_len = 4; - if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ - snprintf(addr, sizeof(addr), "%d.%d.%d.%d:%d", p[4], p[5], p[6], p[7], - p[8] << 8 | p[9]); - mg_socks5_connect(c, addr); - } else if (atyp == MG_SOCKS_ADDR_IPV6) { - addr_len = 16; - if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ - snprintf(addr, sizeof(addr), "[%x:%x:%x:%x:%x:%x:%x:%x]:%d", - p[4] << 8 | p[5], p[6] << 8 | p[7], p[8] << 8 | p[9], - p[10] << 8 | p[11], p[12] << 8 | p[13], p[14] << 8 | p[15], - p[16] << 8 | p[17], p[18] << 8 | p[19], p[20] << 8 | p[21]); - mg_socks5_connect(c, addr); - } else if (atyp == MG_SOCKS_ADDR_DOMAIN) { - addr_len = p[4] + 1; - if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ - snprintf(addr, sizeof(addr), "%.*s:%d", p[4], p + 5, - p[4 + addr_len] << 8 | p[4 + addr_len + 1]); - mg_socks5_connect(c, addr); - } else { - reply = MG_SOCKS_ADDR_NOT_SUPPORTED; - } - - /* - * Reply, https://www.ietf.org/rfc/rfc1928.txt paragraph 5 - * - * +----+-----+-------+------+----------+----------+ - * |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | - * +----+-----+-------+------+----------+----------+ - * | 1 | 1 | X'00' | 1 | Variable | 2 | - * +----+-----+-------+------+----------+----------+ - */ - { - unsigned char buf[] = {MG_SOCKS_VERSION, reply, 0}; - mg_send(c, buf, sizeof(buf)); - } - mg_send(c, r->buf + 3, addr_len + 1 + 2); - - mbuf_remove(r, 6 + addr_len); /* Remove request from the input stream */ - c->flags |= MG_SOCKS_CONNECT_DONE; /* Mark ourselves as connected */ -} - -static void socks_handler(struct mg_connection *c, int ev, void *ev_data) { - if (ev == MG_EV_RECV) { - if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) mg_socks5_handshake(c); - if (c->flags & MG_SOCKS_HANDSHAKE_DONE && - !(c->flags & MG_SOCKS_CONNECT_DONE)) { - mg_socks5_handle_request(c); - } - if (c->flags & MG_SOCKS_CONNECT_DONE) relay_data(c); - } else if (ev == MG_EV_CLOSE) { - disband(c); - } - (void) ev_data; -} - -void mg_set_protocol_socks(struct mg_connection *c) { - c->proto_handler = socks_handler; -} -#endif -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/cc3200/cc3200_libc.c" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if CS_PLATFORM == CS_P_CC3200 - -/* Amalgamated: #include "common/mg_mem.h" */ -#include -#include - -#ifndef __TI_COMPILER_VERSION__ -#include -#include -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -#include - -#define CONSOLE_UART UARTA0_BASE - -#ifdef __TI_COMPILER_VERSION__ -int asprintf(char **strp, const char *fmt, ...) { - va_list ap; - int len; - - *strp = MG_MALLOC(BUFSIZ); - if (*strp == NULL) return -1; - - va_start(ap, fmt); - len = vsnprintf(*strp, BUFSIZ, fmt, ap); - va_end(ap); - - if (len > 0) { - *strp = MG_REALLOC(*strp, len + 1); - if (*strp == NULL) return -1; - } - - if (len >= BUFSIZ) { - va_start(ap, fmt); - len = vsnprintf(*strp, len + 1, fmt, ap); - va_end(ap); - } - - return len; -} - -#if MG_TI_NO_HOST_INTERFACE -time_t HOSTtime() { - struct timeval tp; - gettimeofday(&tp, NULL); - return tp.tv_sec; -} -#endif - -#endif /* __TI_COMPILER_VERSION__ */ - -void fprint_str(FILE *fp, const char *str) { - while (*str != '\0') { - if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r'); - MAP_UARTCharPut(CONSOLE_UART, *str++); - } -} - -void _exit(int status) { - fprint_str(stderr, "_exit\n"); - /* cause an unaligned access exception, that will drop you into gdb */ - *(int *) 1 = status; - while (1) - ; /* avoid gcc warning because stdlib abort() has noreturn attribute */ -} - -void _not_implemented(const char *what) { - fprint_str(stderr, what); - fprint_str(stderr, " is not implemented\n"); - _exit(42); -} - -int _kill(int pid, int sig) { - (void) pid; - (void) sig; - _not_implemented("_kill"); - return -1; -} - -int _getpid() { - fprint_str(stderr, "_getpid is not implemented\n"); - return 42; -} - -int _isatty(int fd) { - /* 0, 1 and 2 are TTYs. */ - return fd < 2; -} - -#endif /* CS_PLATFORM == CS_P_CC3200 */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/msp432/msp432_libc.c" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if CS_PLATFORM == CS_P_MSP432 - -#include -#include - -int gettimeofday(struct timeval *tp, void *tzp) { - uint32_t ticks = Clock_getTicks(); - tp->tv_sec = ticks / 1000; - tp->tv_usec = (ticks % 1000) * 1000; - return 0; -} - -#endif /* CS_PLATFORM == CS_P_MSP432 */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/nrf5/nrf5_libc.c" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \ - defined(__ARMCC_VERSION) -int gettimeofday(struct timeval *tp, void *tzp) { - /* TODO */ - tp->tv_sec = 0; - tp->tv_usec = 0; - return 0; -} -#endif -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_fs_slfs.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ -#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ - -#if defined(MG_FS_SLFS) - -#include -#ifndef __TI_COMPILER_VERSION__ -#include -#include -#endif - -#define MAX_OPEN_SLFS_FILES 8 - -/* Indirect libc interface - same functions, different names. */ -int fs_slfs_open(const char *pathname, int flags, mode_t mode); -int fs_slfs_close(int fd); -ssize_t fs_slfs_read(int fd, void *buf, size_t count); -ssize_t fs_slfs_write(int fd, const void *buf, size_t count); -int fs_slfs_stat(const char *pathname, struct stat *s); -int fs_slfs_fstat(int fd, struct stat *s); -off_t fs_slfs_lseek(int fd, off_t offset, int whence); -int fs_slfs_unlink(const char *filename); -int fs_slfs_rename(const char *from, const char *to); - -void fs_slfs_set_file_size(const char *name, size_t size); -void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token); -void fs_slfs_unset_file_flags(const char *name); - -#endif /* defined(MG_FS_SLFS) */ - -#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_fs_slfs.c" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* Standard libc interface to TI SimpleLink FS. */ - -#if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) - -/* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */ - -#include - -#if CS_PLATFORM == CS_P_CC3200 -#include -#endif - -/* Amalgamated: #include "common/cs_dbg.h" */ -/* Amalgamated: #include "common/mg_mem.h" */ - -#if SL_MAJOR_VERSION_NUM < 2 -int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) { - _i32 fh; - _i32 r = sl_FsOpen(fname, flags, (unsigned long *) token, &fh); - return (r < 0 ? r : fh); -} -#else /* SL_MAJOR_VERSION_NUM >= 2 */ -int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) { - return sl_FsOpen(fname, flags, (unsigned long *) token); -} -#endif - -/* From sl_fs.c */ -int set_errno(int e); -const char *drop_dir(const char *fname, bool *is_slfs); - -/* - * With SLFS, you have to pre-declare max file size. Yes. Really. - * 64K should be enough for everyone. Right? - */ -#ifndef FS_SLFS_MAX_FILE_SIZE -#define FS_SLFS_MAX_FILE_SIZE (64 * 1024) -#endif - -struct sl_file_open_info { - char *name; - size_t size; - uint32_t flags; - uint32_t *token; -}; - -struct sl_fd_info { - _i32 fh; - _off_t pos; - size_t size; -}; - -static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES]; -static struct sl_file_open_info s_sl_file_open_infos[MAX_OPEN_SLFS_FILES]; - -static struct sl_file_open_info *fs_slfs_find_foi(const char *name, - bool create); - -static int sl_fs_to_errno(_i32 r) { - DBG(("SL error: %d", (int) r)); - switch (r) { - case SL_FS_OK: - return 0; - case SL_ERROR_FS_FILE_NAME_EXIST: - return EEXIST; - case SL_ERROR_FS_WRONG_FILE_NAME: - return EINVAL; - case SL_ERROR_FS_NO_AVAILABLE_NV_INDEX: - case SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE: - return ENOSPC; - case SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM: - return ENOMEM; - case SL_ERROR_FS_FILE_NOT_EXISTS: - return ENOENT; - case SL_ERROR_FS_NOT_SUPPORTED: - return ENOTSUP; - } - return ENXIO; -} - -int fs_slfs_open(const char *pathname, int flags, mode_t mode) { - int fd; - for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) { - if (s_sl_fds[fd].fh <= 0) break; - } - if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM); - struct sl_fd_info *fi = &s_sl_fds[fd]; - - /* - * Apply path manipulations again, in case we got here directly - * (via TI libc's "add_device"). - */ - pathname = drop_dir(pathname, NULL); - - _u32 am = 0; - fi->size = (size_t) -1; - int rw = (flags & 3); - size_t new_size = 0; - struct sl_file_open_info *foi = - fs_slfs_find_foi(pathname, false /* create */); - if (foi != NULL) { - LOG(LL_DEBUG, ("FOI for %s: %d 0x%x %p", pathname, (int) foi->size, - (unsigned int) foi->flags, foi->token)); - } - if (rw == O_RDONLY) { - SlFsFileInfo_t sl_fi; - _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi); - if (r == SL_FS_OK) { - fi->size = SL_FI_FILE_SIZE(sl_fi); - } - am = SL_FS_READ; - } else { - if (!(flags & O_TRUNC) || (flags & O_APPEND)) { - // FailFS files cannot be opened for append and will be truncated - // when opened for write. - return set_errno(ENOTSUP); - } - if (flags & O_CREAT) { - if (foi->size > 0) { - new_size = foi->size; - } else { - new_size = FS_SLFS_MAX_FILE_SIZE; - } - am = FS_MODE_OPEN_CREATE(new_size, 0); - } else { - am = SL_FS_WRITE; - } -#if SL_MAJOR_VERSION_NUM >= 2 - am |= SL_FS_OVERWRITE; -#endif - } - uint32_t *token = NULL; - if (foi != NULL) { - am |= foi->flags; - token = foi->token; - } - fi->fh = slfs_open((_u8 *) pathname, am, token); - LOG(LL_DEBUG, ("sl_FsOpen(%s, 0x%x, %p) sz %u = %d", pathname, (int) am, - token, (unsigned int) new_size, (int) fi->fh)); - int r; - if (fi->fh >= 0) { - fi->pos = 0; - r = fd; - } else { - r = set_errno(sl_fs_to_errno(fi->fh)); - } - return r; -} - -int fs_slfs_close(int fd) { - struct sl_fd_info *fi = &s_sl_fds[fd]; - if (fi->fh <= 0) return set_errno(EBADF); - _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0); - LOG(LL_DEBUG, ("sl_FsClose(%d) = %d", (int) fi->fh, (int) r)); - s_sl_fds[fd].fh = -1; - return set_errno(sl_fs_to_errno(r)); -} - -ssize_t fs_slfs_read(int fd, void *buf, size_t count) { - struct sl_fd_info *fi = &s_sl_fds[fd]; - if (fi->fh <= 0) return set_errno(EBADF); - /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE. - */ - if (fi->pos == fi->size) return 0; - _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count); - DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count, - (int) r)); - if (r >= 0) { - fi->pos += r; - return r; - } - return set_errno(sl_fs_to_errno(r)); -} - -ssize_t fs_slfs_write(int fd, const void *buf, size_t count) { - struct sl_fd_info *fi = &s_sl_fds[fd]; - if (fi->fh <= 0) return set_errno(EBADF); - _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count); - DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count, - (int) r)); - if (r >= 0) { - fi->pos += r; - return r; - } - return set_errno(sl_fs_to_errno(r)); -} - -int fs_slfs_stat(const char *pathname, struct stat *s) { - SlFsFileInfo_t sl_fi; - /* - * Apply path manipulations again, in case we got here directly - * (via TI libc's "add_device"). - */ - pathname = drop_dir(pathname, NULL); - _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi); - if (r == SL_FS_OK) { - s->st_mode = S_IFREG | 0666; - s->st_nlink = 1; - s->st_size = SL_FI_FILE_SIZE(sl_fi); - return 0; - } - return set_errno(sl_fs_to_errno(r)); -} - -int fs_slfs_fstat(int fd, struct stat *s) { - struct sl_fd_info *fi = &s_sl_fds[fd]; - if (fi->fh <= 0) return set_errno(EBADF); - s->st_mode = 0666; - s->st_mode = S_IFREG | 0666; - s->st_nlink = 1; - s->st_size = fi->size; - return 0; -} - -off_t fs_slfs_lseek(int fd, off_t offset, int whence) { - if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF); - switch (whence) { - case SEEK_SET: - s_sl_fds[fd].pos = offset; - break; - case SEEK_CUR: - s_sl_fds[fd].pos += offset; - break; - case SEEK_END: - return set_errno(ENOTSUP); - } - return 0; -} - -int fs_slfs_unlink(const char *pathname) { - /* - * Apply path manipulations again, in case we got here directly - * (via TI libc's "add_device"). - */ - pathname = drop_dir(pathname, NULL); - return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0))); -} - -int fs_slfs_rename(const char *from, const char *to) { - return set_errno(ENOTSUP); -} - -static struct sl_file_open_info *fs_slfs_find_foi(const char *name, - bool create) { - int i = 0; - for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) { - if (s_sl_file_open_infos[i].name != NULL && - strcmp(drop_dir(s_sl_file_open_infos[i].name, NULL), name) == 0) { - break; - } - } - if (i != MAX_OPEN_SLFS_FILES) return &s_sl_file_open_infos[i]; - if (!create) return NULL; - for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) { - if (s_sl_file_open_infos[i].name == NULL) break; - } - if (i == MAX_OPEN_SLFS_FILES) { - i = 0; /* Evict a random slot. */ - } - if (s_sl_file_open_infos[i].name != NULL) { - free(s_sl_file_open_infos[i].name); - } - s_sl_file_open_infos[i].name = strdup(name); - return &s_sl_file_open_infos[i]; -} - -void fs_slfs_set_file_size(const char *name, size_t size) { - struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */); - foi->size = size; -} - -void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token) { - struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */); - foi->flags = flags; - foi->token = token; -} - -void fs_slfs_unset_file_flags(const char *name) { - struct sl_file_open_info *foi = fs_slfs_find_foi(name, false /* create */); - if (foi == NULL) return; - free(foi->name); - memset(foi, 0, sizeof(*foi)); -} - -#endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_fs.c" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if MG_NET_IF == MG_NET_IF_SIMPLELINK && \ - (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS)) - -int set_errno(int e) { - errno = e; - return (e == 0 ? 0 : -1); -} - -const char *drop_dir(const char *fname, bool *is_slfs) { - if (is_slfs != NULL) { - *is_slfs = (strncmp(fname, "SL:", 3) == 0); - if (*is_slfs) fname += 3; - } - /* Drop "./", if any */ - if (fname[0] == '.' && fname[1] == '/') { - fname += 2; - } - /* - * Drop / if it is the only one in the path. - * This allows use of /pretend/directories but serves /file.txt as normal. - */ - if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) { - fname++; - } - return fname; -} - -#if !defined(MG_FS_NO_VFS) - -#include -#include -#include -#include -#include -#ifdef __TI_COMPILER_VERSION__ -#include -#endif - -/* Amalgamated: #include "common/cs_dbg.h" */ -/* Amalgamated: #include "common/platform.h" */ - -#ifdef CC3200_FS_SPIFFS -/* Amalgamated: #include "cc3200_fs_spiffs.h" */ -#endif - -#ifdef MG_FS_SLFS -/* Amalgamated: #include "sl_fs_slfs.h" */ -#endif - -#define NUM_SYS_FDS 3 -#define SPIFFS_FD_BASE 10 -#define SLFS_FD_BASE 100 - -#if !defined(MG_UART_CHAR_PUT) && !defined(MG_UART_WRITE) -#if CS_PLATFORM == CS_P_CC3200 -#include -#include -#include -#include -#include -#define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c); -#else -#define MG_UART_WRITE(fd, buf, len) -#endif /* CS_PLATFORM == CS_P_CC3200 */ -#endif /* !MG_UART_CHAR_PUT */ - -enum fd_type { - FD_INVALID, - FD_SYS, -#ifdef CC3200_FS_SPIFFS - FD_SPIFFS, -#endif -#ifdef MG_FS_SLFS - FD_SLFS -#endif -}; -static int fd_type(int fd) { - if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS; -#ifdef CC3200_FS_SPIFFS - if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) { - return FD_SPIFFS; - } -#endif -#ifdef MG_FS_SLFS - if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) { - return FD_SLFS; - } -#endif - return FD_INVALID; -} - -#if MG_TI_NO_HOST_INTERFACE -int open(const char *pathname, unsigned flags, int mode) { -#else -int _open(const char *pathname, int flags, mode_t mode) { -#endif - int fd = -1; - bool is_sl; - const char *fname = drop_dir(pathname, &is_sl); - if (is_sl) { -#ifdef MG_FS_SLFS - fd = fs_slfs_open(fname, flags, mode); - if (fd >= 0) fd += SLFS_FD_BASE; -#endif - } else { -#ifdef CC3200_FS_SPIFFS - fd = fs_spiffs_open(fname, flags, mode); - if (fd >= 0) fd += SPIFFS_FD_BASE; -#endif - } - LOG(LL_DEBUG, - ("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname)); - return fd; -} - -int _stat(const char *pathname, struct stat *st) { - int res = -1; - bool is_sl; - const char *fname = drop_dir(pathname, &is_sl); - memset(st, 0, sizeof(*st)); - /* Simulate statting the root directory. */ - if (fname[0] == '\0' || strcmp(fname, ".") == 0) { - st->st_ino = 0; - st->st_mode = S_IFDIR | 0777; - st->st_nlink = 1; - st->st_size = 0; - return 0; - } - if (is_sl) { -#ifdef MG_FS_SLFS - res = fs_slfs_stat(fname, st); -#endif - } else { -#ifdef CC3200_FS_SPIFFS - res = fs_spiffs_stat(fname, st); -#endif - } - LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname)); - return res; -} - -#if MG_TI_NO_HOST_INTERFACE -int close(int fd) { -#else -int _close(int fd) { -#endif - int r = -1; - switch (fd_type(fd)) { - case FD_INVALID: - r = set_errno(EBADF); - break; - case FD_SYS: - r = set_errno(EACCES); - break; -#ifdef CC3200_FS_SPIFFS - case FD_SPIFFS: - r = fs_spiffs_close(fd - SPIFFS_FD_BASE); - break; -#endif -#ifdef MG_FS_SLFS - case FD_SLFS: - r = fs_slfs_close(fd - SLFS_FD_BASE); - break; -#endif - } - DBG(("close(%d) = %d", fd, r)); - return r; -} - -#if MG_TI_NO_HOST_INTERFACE -off_t lseek(int fd, off_t offset, int whence) { -#else -off_t _lseek(int fd, off_t offset, int whence) { -#endif - int r = -1; - switch (fd_type(fd)) { - case FD_INVALID: - r = set_errno(EBADF); - break; - case FD_SYS: - r = set_errno(ESPIPE); - break; -#ifdef CC3200_FS_SPIFFS - case FD_SPIFFS: - r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence); - break; -#endif -#ifdef MG_FS_SLFS - case FD_SLFS: - r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence); - break; -#endif - } - DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r)); - return r; -} - -int _fstat(int fd, struct stat *s) { - int r = -1; - memset(s, 0, sizeof(*s)); - switch (fd_type(fd)) { - case FD_INVALID: - r = set_errno(EBADF); - break; - case FD_SYS: { - /* Create barely passable stats for STD{IN,OUT,ERR}. */ - memset(s, 0, sizeof(*s)); - s->st_ino = fd; - s->st_mode = S_IFCHR | 0666; - r = 0; - break; - } -#ifdef CC3200_FS_SPIFFS - case FD_SPIFFS: - r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s); - break; -#endif -#ifdef MG_FS_SLFS - case FD_SLFS: - r = fs_slfs_fstat(fd - SLFS_FD_BASE, s); - break; -#endif - } - DBG(("fstat(%d) = %d", fd, r)); - return r; -} - -#if MG_TI_NO_HOST_INTERFACE -int read(int fd, char *buf, unsigned count) { -#else -ssize_t _read(int fd, void *buf, size_t count) { -#endif - int r = -1; - switch (fd_type(fd)) { - case FD_INVALID: - r = set_errno(EBADF); - break; - case FD_SYS: { - if (fd != 0) { - r = set_errno(EACCES); - break; - } - /* Should we allow reading from stdin = uart? */ - r = set_errno(ENOTSUP); - break; - } -#ifdef CC3200_FS_SPIFFS - case FD_SPIFFS: - r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count); - break; -#endif -#ifdef MG_FS_SLFS - case FD_SLFS: - r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count); - break; -#endif - } - DBG(("read(%d, %u) = %d", fd, count, r)); - return r; -} - -#if MG_TI_NO_HOST_INTERFACE -int write(int fd, const char *buf, unsigned count) { -#else -ssize_t _write(int fd, const void *buf, size_t count) { -#endif - int r = -1; - switch (fd_type(fd)) { - case FD_INVALID: - r = set_errno(EBADF); - break; - case FD_SYS: { - if (fd == 0) { - r = set_errno(EACCES); - break; - } -#ifdef MG_UART_WRITE - MG_UART_WRITE(fd, buf, count); -#elif defined(MG_UART_CHAR_PUT) - { - size_t i; - for (i = 0; i < count; i++) { - const char c = ((const char *) buf)[i]; - if (c == '\n') MG_UART_CHAR_PUT(fd, '\r'); - MG_UART_CHAR_PUT(fd, c); - } - } -#endif - r = count; - break; - } -#ifdef CC3200_FS_SPIFFS - case FD_SPIFFS: - r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count); - break; -#endif -#ifdef MG_FS_SLFS - case FD_SLFS: - r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count); - break; -#endif - } - return r; -} - -/* - * On Newlib we override rename directly too, because the default - * implementation using _link and _unlink doesn't work for us. - */ -#if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) -int rename(const char *frompath, const char *topath) { - int r = -1; - bool is_sl_from, is_sl_to; - const char *from = drop_dir(frompath, &is_sl_from); - const char *to = drop_dir(topath, &is_sl_to); - if (is_sl_from || is_sl_to) { - set_errno(ENOTSUP); - } else { -#ifdef CC3200_FS_SPIFFS - r = fs_spiffs_rename(from, to); -#endif - } - DBG(("rename(%s, %s) = %d", from, to, r)); - return r; -} -#endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */ - -#if MG_TI_NO_HOST_INTERFACE -int unlink(const char *pathname) { -#else -int _unlink(const char *pathname) { -#endif - int r = -1; - bool is_sl; - const char *fname = drop_dir(pathname, &is_sl); - if (is_sl) { -#ifdef MG_FS_SLFS - r = fs_slfs_unlink(fname); -#endif - } else { -#ifdef CC3200_FS_SPIFFS - r = fs_spiffs_unlink(fname); -#endif - } - DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname)); - return r; -} - -#ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */ -DIR *opendir(const char *dir_name) { - DIR *r = NULL; - bool is_sl; - drop_dir(dir_name, &is_sl); - if (is_sl) { - r = NULL; - set_errno(ENOTSUP); - } else { - r = fs_spiffs_opendir(dir_name); - } - DBG(("opendir(%s) = %p", dir_name, r)); - return r; -} - -struct dirent *readdir(DIR *dir) { - struct dirent *res = fs_spiffs_readdir(dir); - DBG(("readdir(%p) = %p", dir, res)); - return res; -} - -int closedir(DIR *dir) { - int res = fs_spiffs_closedir(dir); - DBG(("closedir(%p) = %d", dir, res)); - return res; -} - -int rmdir(const char *path) { - return fs_spiffs_rmdir(path); -} - -int mkdir(const char *path, mode_t mode) { - (void) path; - (void) mode; - /* for spiffs supports only root dir, which comes from mongoose as '.' */ - return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR; -} -#endif - -int sl_fs_init(void) { - int ret = 1; -#ifdef __TI_COMPILER_VERSION__ -#ifdef MG_FS_SLFS -#pragma diag_push -#pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \ - */ - ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read, - fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink, - fs_slfs_rename) == 0); -#pragma diag_pop -#endif -#endif - return ret; -} - -#endif /* !defined(MG_FS_NO_VFS) */ -#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \ - defined(MG_FS_SPIFFS)) */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_socket.c" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if MG_NET_IF == MG_NET_IF_SIMPLELINK - -#include -#include - -/* Amalgamated: #include "common/platform.h" */ - -const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) { - int res; - struct in_addr *in = (struct in_addr *) src; - if (af != AF_INET) { - errno = ENOTSUP; - return NULL; - } - res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0), - SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2), - SL_IPV4_BYTE(in->s_addr, 3)); - return res > 0 ? dst : NULL; -} - -char *inet_ntoa(struct in_addr n) { - static char a[16]; - return (char *) inet_ntop(AF_INET, &n, a, sizeof(a)); -} - -int inet_pton(int af, const char *src, void *dst) { - uint32_t a0, a1, a2, a3; - uint8_t *db = (uint8_t *) dst; - if (af != AF_INET) { - errno = ENOTSUP; - return 0; - } - if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) { - return 0; - } - *db = a3; - *(db + 1) = a2; - *(db + 2) = a1; - *(db + 3) = a0; - return 1; -} - -#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_mg_task.c" -#endif -#if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) - -/* Amalgamated: #include "mg_task.h" */ - -#include - -enum mg_q_msg_type { - MG_Q_MSG_CB, -}; -struct mg_q_msg { - enum mg_q_msg_type type; - void (*cb)(struct mg_mgr *mgr, void *arg); - void *arg; -}; -static OsiMsgQ_t s_mg_q; -static void mg_task(void *arg); - -bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) { - if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) { - return false; - } - if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size, - (void *) mg_init, priority, NULL) != OSI_OK) { - return false; - } - return true; -} - -static void mg_task(void *arg) { - struct mg_mgr mgr; - mg_init_cb mg_init = (mg_init_cb) arg; - mg_mgr_init(&mgr, NULL); - mg_init(&mgr); - while (1) { - struct mg_q_msg msg; - mg_mgr_poll(&mgr, 1); - if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue; - switch (msg.type) { - case MG_Q_MSG_CB: { - msg.cb(&mgr, msg.arg); - } - } - } -} - -void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) { - struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg}; - osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT); -} - -#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \ - */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_net_if.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ -#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ - -/* Amalgamated: #include "mongoose/src/net_if.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifndef MG_ENABLE_NET_IF_SIMPLELINK -#define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK -#endif - -extern const struct mg_iface_vtable mg_simplelink_iface_vtable; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_net_if.c" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* Amalgamated: #include "common/platforms/simplelink/sl_net_if.h" */ - -#if MG_ENABLE_NET_IF_SIMPLELINK - -/* Amalgamated: #include "mongoose/src/internal.h" */ -/* Amalgamated: #include "mongoose/src/util.h" */ - -#define MG_TCP_RECV_BUFFER_SIZE 1024 -#define MG_UDP_RECV_BUFFER_SIZE 1500 - -static sock_t mg_open_listening_socket(struct mg_connection *nc, - union socket_address *sa, int type, - int proto); - -static void mg_set_non_blocking_mode(sock_t sock) { - SlSockNonblocking_t opt; -#if SL_MAJOR_VERSION_NUM < 2 - opt.NonblockingEnabled = 1; -#else - opt.NonBlockingEnabled = 1; -#endif - sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt)); -} - -static int mg_is_error(int n) { - return (n < 0 && n != SL_ERROR_BSD_EALREADY && n != SL_ERROR_BSD_EAGAIN); -} - -static void mg_sl_if_connect_tcp(struct mg_connection *nc, - const union socket_address *sa) { - int proto = 0; -#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK - if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET; -#endif - sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto); - if (sock < 0) { - nc->err = sock; - goto out; - } - mg_sock_set(nc, sock); -#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK - nc->err = sl_set_ssl_opts(sock, nc); - if (nc->err != 0) goto out; -#endif - nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin)); -out: - DBG(("%p to %s:%d sock %d %d err %d", nc, inet_ntoa(sa->sin.sin_addr), - ntohs(sa->sin.sin_port), nc->sock, proto, nc->err)); -} - -static void mg_sl_if_connect_udp(struct mg_connection *nc) { - sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) { - nc->err = sock; - return; - } - mg_sock_set(nc, sock); - nc->err = 0; -} - -static int mg_sl_if_listen_tcp(struct mg_connection *nc, - union socket_address *sa) { - int proto = 0; - if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET; - sock_t sock = mg_open_listening_socket(nc, sa, SOCK_STREAM, proto); - if (sock < 0) return sock; - mg_sock_set(nc, sock); - return 0; -} - -static int mg_sl_if_listen_udp(struct mg_connection *nc, - union socket_address *sa) { - sock_t sock = mg_open_listening_socket(nc, sa, SOCK_DGRAM, 0); - if (sock == INVALID_SOCKET) return (errno ? errno : 1); - mg_sock_set(nc, sock); - return 0; -} - -static int mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf, - size_t len) { - int n = (int) sl_Send(nc->sock, buf, len, 0); - if (n < 0 && !mg_is_error(n)) n = 0; - return n; -} - -static int mg_sl_if_udp_send(struct mg_connection *nc, const void *buf, - size_t len) { - int n = sl_SendTo(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin)); - if (n < 0 && !mg_is_error(n)) n = 0; - return n; -} - -static int mg_sl_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len) { - int n = sl_Recv(nc->sock, buf, len, 0); - if (n == 0) { - /* Orderly shutdown of the socket, try flushing output. */ - nc->flags |= MG_F_SEND_AND_CLOSE; - } else if (n < 0 && !mg_is_error(n)) { - n = 0; - } - return n; -} - -static int mg_sl_if_udp_recv(struct mg_connection *nc, void *buf, size_t len, - union socket_address *sa, size_t *sa_len) { - SlSocklen_t sa_len_t = *sa_len; - int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0, - (SlSockAddr_t *) sa, &sa_len_t); - *sa_len = sa_len_t; - if (n < 0 && !mg_is_error(n)) n = 0; - return n; -} - -static int mg_sl_if_create_conn(struct mg_connection *nc) { - (void) nc; - return 1; -} - -void mg_sl_if_destroy_conn(struct mg_connection *nc) { - if (nc->sock == INVALID_SOCKET) return; - /* For UDP, only close outgoing sockets or listeners. */ - if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) { - sl_Close(nc->sock); - } - nc->sock = INVALID_SOCKET; -} - -static int mg_accept_conn(struct mg_connection *lc) { - struct mg_connection *nc; - union socket_address sa; - socklen_t sa_len = sizeof(sa); - sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len); - if (sock < 0) { - DBG(("%p: failed to accept: %d", lc, sock)); - return 0; - } - nc = mg_if_accept_new_conn(lc); - if (nc == NULL) { - sl_Close(sock); - return 0; - } - DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr), - ntohs(sa.sin.sin_port))); - mg_sock_set(nc, sock); - mg_if_accept_tcp_cb(nc, &sa, sa_len); - return 1; -} - -/* 'sa' must be an initialized address to bind to */ -static sock_t mg_open_listening_socket(struct mg_connection *nc, - union socket_address *sa, int type, - int proto) { - int r; - socklen_t sa_len = - (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6); - sock_t sock = sl_Socket(sa->sa.sa_family, type, proto); - if (sock < 0) return sock; -#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK - if ((r = sl_set_ssl_opts(sock, nc)) < 0) goto clean; -#endif - if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) goto clean; - if (type != SOCK_DGRAM) { - if ((r = sl_Listen(sock, SOMAXCONN)) < 0) goto clean; - } - mg_set_non_blocking_mode(sock); -clean: - if (r < 0) { - sl_Close(sock); - sock = r; - } - return sock; -} - -#define _MG_F_FD_CAN_READ 1 -#define _MG_F_FD_CAN_WRITE 1 << 1 -#define _MG_F_FD_ERROR 1 << 2 - -void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) { - DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, - fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); - - if (!mg_if_poll(nc, now)) return; - - if (nc->flags & MG_F_CONNECTING) { - if ((nc->flags & MG_F_UDP) || nc->err != SL_ERROR_BSD_EALREADY) { - mg_if_connect_cb(nc, nc->err); - } else { - /* In SimpleLink, to get status of non-blocking connect() we need to wait - * until socket is writable and repeat the call to sl_Connect again, - * which will now return the real status. */ - if (fd_flags & _MG_F_FD_CAN_WRITE) { - nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin)); - DBG(("%p conn res=%d", nc, nc->err)); - if (nc->err == SL_ERROR_BSD_ESECSNOVERIFY || - /* TODO(rojer): Provide API to set the date for verification. */ - nc->err == SL_ERROR_BSD_ESECDATEERROR -#if SL_MAJOR_VERSION_NUM >= 2 - /* Per SWRU455, this error does not mean verification failed, - * it only means that the cert used is not present in the trusted - * root CA catalog. Which is perfectly fine. */ - || - nc->err == SL_ERROR_BSD_ESECUNKNOWNROOTCA -#endif - ) { - nc->err = 0; - } - mg_if_connect_cb(nc, nc->err); - } - } - /* Ignore read/write in further processing, we've handled it. */ - fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE); - } - - if (fd_flags & _MG_F_FD_CAN_READ) { - if (nc->flags & MG_F_UDP) { - mg_if_can_recv_cb(nc); - } else { - if (nc->flags & MG_F_LISTENING) { - mg_accept_conn(nc); - } else { - mg_if_can_recv_cb(nc); - } - } - } - - if (fd_flags & _MG_F_FD_CAN_WRITE) { - mg_if_can_send_cb(nc); - } - - DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, nc->flags, - (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); -} - -/* Associate a socket to a connection. */ -void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) { - mg_set_non_blocking_mode(sock); - nc->sock = sock; - DBG(("%p %d", nc, sock)); -} - -void mg_sl_if_init(struct mg_iface *iface) { - (void) iface; - DBG(("%p using sl_Select()", iface->mgr)); -} - -void mg_sl_if_free(struct mg_iface *iface) { - (void) iface; -} - -void mg_sl_if_add_conn(struct mg_connection *nc) { - (void) nc; -} - -void mg_sl_if_remove_conn(struct mg_connection *nc) { - (void) nc; -} - -time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) { - struct mg_mgr *mgr = iface->mgr; - double now = mg_time(); - double min_timer; - struct mg_connection *nc, *tmp; - struct SlTimeval_t tv; - SlFdSet_t read_set, write_set, err_set; - sock_t max_fd = INVALID_SOCKET; - int num_fds, num_ev = 0, num_timers = 0; - - SL_SOCKET_FD_ZERO(&read_set); - SL_SOCKET_FD_ZERO(&write_set); - SL_SOCKET_FD_ZERO(&err_set); - - /* - * Note: it is ok to have connections with sock == INVALID_SOCKET in the list, - * e.g. timer-only "connections". - */ - min_timer = 0; - for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) { - tmp = nc->next; - - if (nc->sock != INVALID_SOCKET) { - num_fds++; - - if (!(nc->flags & MG_F_WANT_WRITE) && - nc->recv_mbuf.len < nc->recv_mbuf_limit && - (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) { - SL_SOCKET_FD_SET(nc->sock, &read_set); - if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock; - } - - if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) || - (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) { - SL_SOCKET_FD_SET(nc->sock, &write_set); - SL_SOCKET_FD_SET(nc->sock, &err_set); - if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock; - } - } - - if (nc->ev_timer_time > 0) { - if (num_timers == 0 || nc->ev_timer_time < min_timer) { - min_timer = nc->ev_timer_time; - } - num_timers++; - } - } - - /* - * If there is a timer to be fired earlier than the requested timeout, - * adjust the timeout. - */ - if (num_timers > 0) { - double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */; - if (timer_timeout_ms < timeout_ms) { - timeout_ms = timer_timeout_ms; - } - } - if (timeout_ms < 0) timeout_ms = 0; - - tv.tv_sec = timeout_ms / 1000; - tv.tv_usec = (timeout_ms % 1000) * 1000; - - if (num_fds > 0) { - num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv); - } - - now = mg_time(); - DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, - num_fds, timeout_ms)); - - for (nc = mgr->active_connections; nc != NULL; nc = tmp) { - int fd_flags = 0; - if (nc->sock != INVALID_SOCKET) { - if (num_ev > 0) { - fd_flags = - (SL_SOCKET_FD_ISSET(nc->sock, &read_set) && - (!(nc->flags & MG_F_UDP) || nc->listener == NULL) - ? _MG_F_FD_CAN_READ - : 0) | - (SL_SOCKET_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE - : 0) | - (SL_SOCKET_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0); - } - /* SimpleLink does not report UDP sockets as writable. */ - if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) { - fd_flags |= _MG_F_FD_CAN_WRITE; - } - } - tmp = nc->next; - mg_mgr_handle_conn(nc, fd_flags, now); - } - - return now; -} - -void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote, - union socket_address *sa) { - /* SimpleLink does not provide a way to get socket's peer address after - * accept or connect. Address should have been preserved in the connection, - * so we do our best here by using it. */ - if (remote) memcpy(sa, &nc->sa, sizeof(*sa)); -} - -void sl_restart_cb(struct mg_mgr *mgr) { - /* - * SimpleLink has been restarted, meaning all sockets have been invalidated. - * We try our best - we'll restart the listeners, but for outgoing - * connections we have no option but to terminate. - */ - struct mg_connection *nc; - for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { - if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */ - if (nc->flags & MG_F_LISTENING) { - DBG(("restarting %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr), - ntohs(nc->sa.sin.sin_port))); - int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa) - : mg_sl_if_listen_tcp(nc, &nc->sa)); - if (res == 0) continue; - /* Well, we tried and failed. Fall through to closing. */ - } - nc->sock = INVALID_SOCKET; - DBG(("terminating %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr), - ntohs(nc->sa.sin.sin_port))); - /* TODO(rojer): Outgoing UDP? */ - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } -} - -/* clang-format off */ -#define MG_SL_IFACE_VTABLE \ - { \ - mg_sl_if_init, \ - mg_sl_if_free, \ - mg_sl_if_add_conn, \ - mg_sl_if_remove_conn, \ - mg_sl_if_poll, \ - mg_sl_if_listen_tcp, \ - mg_sl_if_listen_udp, \ - mg_sl_if_connect_tcp, \ - mg_sl_if_connect_udp, \ - mg_sl_if_tcp_send, \ - mg_sl_if_udp_send, \ - mg_sl_if_tcp_recv, \ - mg_sl_if_udp_recv, \ - mg_sl_if_create_conn, \ - mg_sl_if_destroy_conn, \ - mg_sl_if_sock_set, \ - mg_sl_if_get_conn_addr, \ - } -/* clang-format on */ - -const struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE; -#if MG_NET_IF == MG_NET_IF_SIMPLELINK -const struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE; -#endif - -#endif /* MG_ENABLE_NET_IF_SIMPLELINK */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_ssl_if.c" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK - -/* Amalgamated: #include "common/mg_mem.h" */ - -#ifndef MG_SSL_IF_SIMPLELINK_SLFS_PREFIX -#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "SL:" -#endif - -#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN \ - (sizeof(MG_SSL_IF_SIMPLELINK_SLFS_PREFIX) - 1) - -struct mg_ssl_if_ctx { - char *ssl_cert; - char *ssl_key; - char *ssl_ca_cert; - char *ssl_server_name; -}; - -void mg_ssl_if_init() { -} - -enum mg_ssl_if_result mg_ssl_if_conn_init( - struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, - const char **err_msg) { - struct mg_ssl_if_ctx *ctx = - (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); - if (ctx == NULL) { - MG_SET_PTRPTR(err_msg, "Out of memory"); - return MG_SSL_ERROR; - } - nc->ssl_if_data = ctx; - - if (params->cert != NULL || params->key != NULL) { - if (params->cert != NULL && params->key != NULL) { - ctx->ssl_cert = strdup(params->cert); - ctx->ssl_key = strdup(params->key); - } else { - MG_SET_PTRPTR(err_msg, "Both cert and key are required."); - return MG_SSL_ERROR; - } - } - if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) { - ctx->ssl_ca_cert = strdup(params->ca_cert); - } - /* TODO(rojer): cipher_suites. */ - if (params->server_name != NULL) { - ctx->ssl_server_name = strdup(params->server_name); - } - return MG_SSL_OK; -} - -enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, - struct mg_connection *lc) { - /* SimpleLink does everything for us, nothing for us to do. */ - (void) nc; - (void) lc; - return MG_SSL_OK; -} - -enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) { - /* SimpleLink has already performed the handshake, nothing to do. */ - return MG_SSL_OK; -} - -int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) { - /* SimpelLink handles TLS, so this is just a pass-through. */ - int n = nc->iface->vtable->tcp_recv(nc, buf, len); - if (n == 0) nc->flags |= MG_F_WANT_READ; - return n; -} - -int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) { - /* SimpelLink handles TLS, so this is just a pass-through. */ - return nc->iface->vtable->tcp_send(nc, buf, len); -} - -void mg_ssl_if_conn_close_notify(struct mg_connection *nc) { - /* Nothing to do */ - (void) nc; -} - -void mg_ssl_if_conn_free(struct mg_connection *nc) { - struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - if (ctx == NULL) return; - nc->ssl_if_data = NULL; - MG_FREE(ctx->ssl_cert); - MG_FREE(ctx->ssl_key); - MG_FREE(ctx->ssl_ca_cert); - MG_FREE(ctx->ssl_server_name); - memset(ctx, 0, sizeof(*ctx)); - MG_FREE(ctx); -} - -bool pem_to_der(const char *pem_file, const char *der_file) { - bool ret = false; - FILE *pf = NULL, *df = NULL; - bool writing = false; - pf = fopen(pem_file, "r"); - if (pf == NULL) goto clean; - remove(der_file); - fs_slfs_set_file_size(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, 2048); - df = fopen(der_file, "w"); - fs_slfs_unset_file_flags(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN); - if (df == NULL) goto clean; - while (1) { - char pem_buf[70]; - char der_buf[48]; - if (!fgets(pem_buf, sizeof(pem_buf), pf)) break; - if (writing) { - if (strstr(pem_buf, "-----END ") != NULL) { - ret = true; - break; - } - int l = 0; - while (!isspace((unsigned int) pem_buf[l])) l++; - int der_len = 0; - cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf), - der_buf, &der_len); - if (der_len <= 0) break; - if (fwrite(der_buf, 1, der_len, df) != der_len) break; - } else if (strstr(pem_buf, "-----BEGIN ") != NULL) { - writing = true; - } - } - -clean: - if (pf != NULL) fclose(pf); - if (df != NULL) { - fclose(df); - if (!ret) remove(der_file); - } - return ret; -} - -#if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS) -/* If the file's extension is .pem, convert it to DER format and put on SLFS. */ -static char *sl_pem2der(const char *pem_file) { - const char *pem_ext = strstr(pem_file, ".pem"); - if (pem_ext == NULL || *(pem_ext + 4) != '\0') { - return strdup(pem_file); - } - char *der_file = NULL; - /* DER file must be located on SLFS, add prefix. */ - int l = mg_asprintf(&der_file, 0, MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "%.*s.der", - (int) (pem_ext - pem_file), pem_file); - if (der_file == NULL) return NULL; - bool result = false; - cs_stat_t st; - if (mg_stat(der_file, &st) != 0) { - result = pem_to_der(pem_file, der_file); - LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result)); - } else { - /* File exists, assume it's already been converted. */ - result = true; - } - if (result) { - /* Strip the SL: prefix we added since NWP does not expect it. */ - memmove(der_file, der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, - l - 2 /* including \0 */); - } else { - MG_FREE(der_file); - der_file = NULL; - } - return der_file; -} -#else -static char *sl_pem2der(const char *pem_file) { - return strdup(pem_file); -} -#endif - -int sl_set_ssl_opts(int sock, struct mg_connection *nc) { - int err; - const struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - DBG(("%p ssl ctx: %p", nc, ctx)); - - if (ctx == NULL) return 0; - DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"), - (ctx->ssl_key ? ctx->ssl_cert : "-"), - (ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"), - (ctx->ssl_server_name ? ctx->ssl_server_name : "-"))); - if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) { - char *ssl_cert = sl_pem2der(ctx->ssl_cert), *ssl_key = NULL; - if (ssl_cert != NULL) { - err = sl_SetSockOpt(sock, SL_SOL_SOCKET, - SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert, - strlen(ssl_cert)); - MG_FREE(ssl_cert); - LOG(LL_DEBUG, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err)); - ssl_key = sl_pem2der(ctx->ssl_key); - if (ssl_key != NULL) { - err = sl_SetSockOpt(sock, SL_SOL_SOCKET, - SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key, - strlen(ssl_key)); - MG_FREE(ssl_key); - LOG(LL_DEBUG, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err)); - } else { - err = -1; - } - } else { - err = -1; - } - if (err != 0) return err; - } - if (ctx->ssl_ca_cert != NULL) { - if (ctx->ssl_ca_cert[0] != '\0') { - char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert); - if (ssl_ca_cert != NULL) { - err = - sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME, - ssl_ca_cert, strlen(ssl_ca_cert)); - LOG(LL_DEBUG, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err)); - } else { - err = -1; - } - MG_FREE(ssl_ca_cert); - if (err != 0) return err; - } - } - if (ctx->ssl_server_name != NULL) { - err = sl_SetSockOpt(sock, SL_SOL_SOCKET, - SL_SO_SECURE_DOMAIN_NAME_VERIFICATION, - ctx->ssl_server_name, strlen(ctx->ssl_server_name)); - DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err)); - /* Domain name verificationw as added in a NWP service pack, older - * versions return SL_ERROR_BSD_ENOPROTOOPT. There isn't much we can do - * about it, - * so we ignore the error. */ - if (err != 0 && err != SL_ERROR_BSD_ENOPROTOOPT) return err; - } - return 0; -} - -#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/lwip/mg_lwip_net_if.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ -#define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ - -#ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL -#define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL -#endif - -#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL - -#include - -extern const struct mg_iface_vtable mg_lwip_iface_vtable; - -struct mg_lwip_conn_state { - struct mg_connection *nc; - struct mg_connection *lc; - union { - struct tcp_pcb *tcp; - struct udp_pcb *udp; - } pcb; - err_t err; - size_t num_sent; /* Number of acknowledged bytes to be reported to the core */ - struct pbuf *rx_chain; /* Chain of incoming data segments. */ - size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */ - /* Last SSL write size, for retries. */ - int last_ssl_write_size; - /* Whether MG_SIG_RECV is already pending for this connection */ - int recv_pending; - /* Whether the connection is about to close, just `rx_chain` needs to drain */ - int draining_rx_chain; -}; - -enum mg_sig_type { - MG_SIG_CONNECT_RESULT = 1, - MG_SIG_RECV = 2, - MG_SIG_CLOSE_CONN = 3, - MG_SIG_TOMBSTONE = 4, - MG_SIG_ACCEPT = 5, -}; - -void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc); - -/* To be implemented by the platform. */ -void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr); - -#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */ - -#endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/lwip/mg_lwip_net_if.c" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL - -/* Amalgamated: #include "common/mg_mem.h" */ - -#include -#include -#include -#include -#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 -#include /* For tcp_seg */ -#else -#include -#endif -#include - -/* Amalgamated: #include "common/cs_dbg.h" */ - -/* - * Newest versions of LWIP have ip_2_ip4, older have ipX_2_ip, - * even older have nothing. - */ -#ifndef ip_2_ip4 -#ifdef ipX_2_ip -#define ip_2_ip4(addr) ipX_2_ip(addr) -#else -#define ip_2_ip4(addr) (addr) -#endif -#endif - -/* - * Depending on whether Mongoose is compiled with ipv6 support, use right - * lwip functions - */ -#if MG_ENABLE_IPV6 -#define TCP_NEW tcp_new_ip6 -#define TCP_BIND tcp_bind_ip6 -#define UDP_BIND udp_bind_ip6 -#define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x)) -#define SET_ADDR(dst, src) \ - memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \ - sizeof((dst)->sin6.sin6_addr.s6_addr)) -#else -#define TCP_NEW tcp_new -#define TCP_BIND tcp_bind -#define UDP_BIND udp_bind -#define IPADDR_NTOA ipaddr_ntoa -#define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = ip_2_ip4(src)->addr -#endif - -#if NO_SYS -#define tcpip_callback(fn, arg) (fn)(arg) -typedef void (*tcpip_callback_fn)(void *arg); -#endif - -void mg_lwip_if_init(struct mg_iface *iface); -void mg_lwip_if_free(struct mg_iface *iface); -void mg_lwip_if_add_conn(struct mg_connection *nc); -void mg_lwip_if_remove_conn(struct mg_connection *nc); -time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms); - -#if defined(RTOS_SDK) || defined(ESP_PLATFORM) -extern void mgos_lock(); -extern void mgos_unlock(); -#else -#define mgos_lock() -#define mgos_unlock() -#endif - -static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p); - -#if LWIP_TCP_KEEPALIVE -void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle, - int interval, int count) { - if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) { - return; - } - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - struct tcp_pcb *tpcb = cs->pcb.tcp; - if (idle > 0 && interval > 0 && count > 0) { - tpcb->keep_idle = idle * 1000; - tpcb->keep_intvl = interval * 1000; - tpcb->keep_cnt = count; - tpcb->so_options |= SOF_KEEPALIVE; - } else { - tpcb->so_options &= ~SOF_KEEPALIVE; - } -} -#elif !defined(MG_NO_LWIP_TCP_KEEPALIVE) -#warning LWIP TCP keepalive is disabled. Please consider enabling it. -#endif /* LWIP_TCP_KEEPALIVE */ - -static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) { - struct mg_connection *nc = (struct mg_connection *) arg; - DBG(("%p connect to %s:%u = %d", nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)), - tpcb->remote_port, err)); - if (nc == NULL) { - tcp_abort(tpcb); - return ERR_ARG; - } - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - cs->err = err; -#if LWIP_TCP_KEEPALIVE - if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6); -#endif - mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); - return ERR_OK; -} - -static void mg_lwip_tcp_error_cb(void *arg, err_t err) { - struct mg_connection *nc = (struct mg_connection *) arg; - DBG(("%p conn error %d", nc, err)); - if (nc == NULL || (nc->flags & MG_F_CLOSE_IMMEDIATELY)) return; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - cs->pcb.tcp = NULL; /* Has already been deallocated */ - if (nc->flags & MG_F_CONNECTING) { - cs->err = err; - mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); - } else { - mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); - } -} - -static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb, - struct pbuf *p, err_t err) { - struct mg_connection *nc = (struct mg_connection *) arg; - struct mg_lwip_conn_state *cs = - (nc ? (struct mg_lwip_conn_state *) nc->sock : NULL); - DBG(("%p %p %p %p %u %d", nc, cs, tpcb, p, (p != NULL ? p->tot_len : 0), - err)); - if (p == NULL) { - if (nc != NULL && !(nc->flags & MG_F_CLOSE_IMMEDIATELY)) { - if (cs->rx_chain != NULL) { - /* - * rx_chain still contains non-consumed data, don't close the - * connection - */ - cs->draining_rx_chain = 1; - } else { - mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); - } - } else { - /* Tombstoned connection, do nothing. */ - } - return ERR_OK; - } else if (nc == NULL) { - tcp_abort(tpcb); - return ERR_ARG; - } - /* - * If we get a chain of more than one segment at once, we need to bump - * refcount on the subsequent bufs to make them independent. - */ - if (p->next != NULL) { - struct pbuf *q = p->next; - for (; q != NULL; q = q->next) pbuf_ref(q); - } - mgos_lock(); - if (cs->rx_chain == NULL) { - cs->rx_offset = 0; - } else if (pbuf_clen(cs->rx_chain) >= 4) { - /* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX - * will be completely blocked. We already have at least 4 in the chain, - * this one is the last, so we have to make a copy and release this one. */ - struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM); - if (np != NULL) { - pbuf_copy(np, p); - pbuf_free(p); - p = np; - } - } - mg_lwip_recv_common(nc, p); - mgos_unlock(); - (void) err; - return ERR_OK; -} - -static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb, - u16_t num_sent) { - struct mg_connection *nc = (struct mg_connection *) arg; - DBG(("%p %p %u %p %p", nc, tpcb, num_sent, tpcb->unsent, tpcb->unacked)); - if (nc == NULL) return ERR_OK; - if ((nc->flags & MG_F_SEND_AND_CLOSE) && !(nc->flags & MG_F_WANT_WRITE) && - nc->send_mbuf.len == 0 && tpcb->unsent == NULL && tpcb->unacked == NULL) { - mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); - } - if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) { - mg_lwip_mgr_schedule_poll(nc->mgr); - } - (void) num_sent; - return ERR_OK; -} - -struct mg_lwip_if_connect_tcp_ctx { - struct mg_connection *nc; - const union socket_address *sa; -}; - -static void mg_lwip_if_connect_tcp_tcpip(void *arg) { - struct mg_lwip_if_connect_tcp_ctx *ctx = - (struct mg_lwip_if_connect_tcp_ctx *) arg; - struct mg_connection *nc = ctx->nc; - const union socket_address *sa = ctx->sa; - - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - struct tcp_pcb *tpcb = TCP_NEW(); - cs->pcb.tcp = tpcb; - ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; - u16_t port = ntohs(sa->sin.sin_port); - tcp_arg(tpcb, nc); - tcp_err(tpcb, mg_lwip_tcp_error_cb); - tcp_sent(tpcb, mg_lwip_tcp_sent_cb); - tcp_recv(tpcb, mg_lwip_tcp_recv_cb); - cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */); - DBG(("%p tcp_bind = %d", nc, cs->err)); - if (cs->err != ERR_OK) { - mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); - return; - } - cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb); - DBG(("%p tcp_connect %p = %d", nc, tpcb, cs->err)); - if (cs->err != ERR_OK) { - mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); - return; - } -} - -void mg_lwip_if_connect_tcp(struct mg_connection *nc, - const union socket_address *sa) { - struct mg_lwip_if_connect_tcp_ctx ctx = {.nc = nc, .sa = sa}; - tcpip_callback(mg_lwip_if_connect_tcp_tcpip, &ctx); -} - -/* - * Lwip included in the SDKs for nRF5x chips has different type for the - * callback of `udp_recv()` - */ -#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 -static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p, - const ip_addr_t *addr, u16_t port) -#else -static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p, - ip_addr_t *addr, u16_t port) -#endif -{ - struct mg_connection *nc = (struct mg_connection *) arg; - DBG(("%p %s:%u %p %u %u", nc, IPADDR_NTOA(addr), port, p, p->ref, p->len)); - /* Put address in a separate pbuf and tack it onto the packet. */ - struct pbuf *sap = - pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM); - if (sap == NULL) { - pbuf_free(p); - return; - } - union socket_address *sa = (union socket_address *) sap->payload; -#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 - sa->sin.sin_addr.s_addr = ip_2_ip4(addr)->addr; -#else - sa->sin.sin_addr.s_addr = addr->addr; -#endif - sa->sin.sin_port = htons(port); - /* Logic in the recv handler requires that there be exactly one data pbuf. */ - p = pbuf_coalesce(p, PBUF_RAW); - pbuf_chain(sap, p); - mgos_lock(); - mg_lwip_recv_common(nc, sap); - mgos_unlock(); - (void) pcb; -} - -static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (cs->rx_chain == NULL) { - cs->rx_chain = p; - } else { - pbuf_chain(cs->rx_chain, p); - } - if (!cs->recv_pending) { - cs->recv_pending = 1; - mg_lwip_post_signal(MG_SIG_RECV, nc); - } -} - -static int mg_lwip_if_udp_recv(struct mg_connection *nc, void *buf, size_t len, - union socket_address *sa, size_t *sa_len) { - /* - * For UDP, RX chain consists of interleaved address and packet bufs: - * Address pbuf followed by exactly one data pbuf (recv_cb took care of that). - */ - int res = 0; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (nc->sock == INVALID_SOCKET) return -1; - mgos_lock(); - if (cs->rx_chain != NULL) { - struct pbuf *ap = cs->rx_chain; - struct pbuf *dp = ap->next; - cs->rx_chain = pbuf_dechain(dp); - res = MIN(dp->len, len); - pbuf_copy_partial(dp, buf, res, 0); - pbuf_free(dp); - pbuf_copy_partial(ap, sa, MIN(*sa_len, ap->len), 0); - pbuf_free(ap); - } - mgos_unlock(); - return res; -} - -static void mg_lwip_if_connect_udp_tcpip(void *arg) { - struct mg_connection *nc = (struct mg_connection *) arg; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - struct udp_pcb *upcb = udp_new(); - cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */); - DBG(("%p udp_bind %p = %d", nc, upcb, cs->err)); - if (cs->err == ERR_OK) { - udp_recv(upcb, mg_lwip_udp_recv_cb, nc); - cs->pcb.udp = upcb; - } else { - udp_remove(upcb); - } - mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); -} - -void mg_lwip_if_connect_udp(struct mg_connection *nc) { - tcpip_callback(mg_lwip_if_connect_udp_tcpip, nc); -} - -static void tcp_close_tcpip(void *arg) { - tcp_close((struct tcp_pcb *) arg); -} - -void mg_lwip_handle_accept(struct mg_connection *nc) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (cs->pcb.tcp == NULL) return; - union socket_address sa; - struct tcp_pcb *tpcb = cs->pcb.tcp; - SET_ADDR(&sa, &tpcb->remote_ip); - sa.sin.sin_port = htons(tpcb->remote_port); - mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin)); -} - -static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) { - struct mg_connection *lc = (struct mg_connection *) arg, *nc; - struct mg_lwip_conn_state *lcs, *cs; - struct tcp_pcb_listen *lpcb; - LOG(LL_DEBUG, - ("%p conn %p from %s:%u", lc, newtpcb, - IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port)); - if (lc == NULL) { - tcp_abort(newtpcb); - return ERR_ABRT; - } - lcs = (struct mg_lwip_conn_state *) lc->sock; - lpcb = (struct tcp_pcb_listen *) lcs->pcb.tcp; -#if TCP_LISTEN_BACKLOG - tcp_accepted(lpcb); -#endif - nc = mg_if_accept_new_conn(lc); - if (nc == NULL) { - tcp_abort(newtpcb); - return ERR_ABRT; - } - cs = (struct mg_lwip_conn_state *) nc->sock; - cs->lc = lc; - cs->pcb.tcp = newtpcb; - /* We need to set up callbacks before returning because data may start - * arriving immediately. */ - tcp_arg(newtpcb, nc); - tcp_err(newtpcb, mg_lwip_tcp_error_cb); - tcp_sent(newtpcb, mg_lwip_tcp_sent_cb); - tcp_recv(newtpcb, mg_lwip_tcp_recv_cb); -#if LWIP_TCP_KEEPALIVE - mg_lwip_set_keepalive_params(nc, 60, 10, 6); -#endif - mg_lwip_post_signal(MG_SIG_ACCEPT, nc); - (void) err; - (void) lpcb; - return ERR_OK; -} - -struct mg_lwip_if_listen_ctx { - struct mg_connection *nc; - union socket_address *sa; - int ret; -}; - -static void mg_lwip_if_listen_tcp_tcpip(void *arg) { - struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg; - struct mg_connection *nc = ctx->nc; - union socket_address *sa = ctx->sa; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - struct tcp_pcb *tpcb = TCP_NEW(); - ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; - u16_t port = ntohs(sa->sin.sin_port); - cs->err = TCP_BIND(tpcb, ip, port); - DBG(("%p tcp_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err)); - if (cs->err != ERR_OK) { - tcp_close(tpcb); - ctx->ret = -1; - return; - } - tcp_arg(tpcb, nc); - tpcb = tcp_listen(tpcb); - cs->pcb.tcp = tpcb; - tcp_accept(tpcb, mg_lwip_accept_cb); - ctx->ret = 0; -} - -int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { - struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa}; - tcpip_callback(mg_lwip_if_listen_tcp_tcpip, &ctx); - return ctx.ret; -} - -static void mg_lwip_if_listen_udp_tcpip(void *arg) { - struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg; - struct mg_connection *nc = ctx->nc; - union socket_address *sa = ctx->sa; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - struct udp_pcb *upcb = udp_new(); - ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; - u16_t port = ntohs(sa->sin.sin_port); - cs->err = UDP_BIND(upcb, ip, port); - DBG(("%p udb_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err)); - if (cs->err != ERR_OK) { - udp_remove(upcb); - ctx->ret = -1; - } else { - udp_recv(upcb, mg_lwip_udp_recv_cb, nc); - cs->pcb.udp = upcb; - ctx->ret = 0; - } -} - -int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { - struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa}; - tcpip_callback(mg_lwip_if_listen_udp_tcpip, &ctx); - return ctx.ret; -} - -struct mg_lwip_tcp_write_ctx { - struct mg_connection *nc; - const void *data; - uint16_t len; - int ret; -}; - -static void tcp_output_tcpip(void *arg) { - tcp_output((struct tcp_pcb *) arg); -} - -static void mg_lwip_tcp_write_tcpip(void *arg) { - struct mg_lwip_tcp_write_ctx *ctx = (struct mg_lwip_tcp_write_ctx *) arg; - struct mg_connection *nc = ctx->nc; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - struct tcp_pcb *tpcb = cs->pcb.tcp; - size_t len = MIN(tpcb->mss, MIN(ctx->len, tpcb->snd_buf)); - size_t unsent, unacked; - if (len == 0) { - DBG(("%p no buf avail %u %u %p %p", tpcb, tpcb->snd_buf, tpcb->snd_queuelen, - tpcb->unsent, tpcb->unacked)); - tcpip_callback(tcp_output_tcpip, tpcb); - ctx->ret = 0; - return; - } - unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0); - unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0); -/* - * On ESP8266 we only allow one TCP segment in flight at any given time. - * This may increase latency and reduce efficiency of tcp windowing, - * but memory is scarce and precious on that platform so we do this to - * reduce footprint. - */ -#if CS_PLATFORM == CS_P_ESP8266 - if (unacked > 0) { - ctx->ret = 0; - return; - } - len = MIN(len, (TCP_MSS - unsent)); -#endif - cs->err = tcp_write(tpcb, ctx->data, len, TCP_WRITE_FLAG_COPY); - unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0); - unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0); - DBG(("%p tcp_write %u = %d, %u %u", tpcb, len, cs->err, unsent, unacked)); - if (cs->err != ERR_OK) { - /* - * We ignore ERR_MEM because memory will be freed up when the data is sent - * and we'll retry. - */ - ctx->ret = (cs->err == ERR_MEM ? 0 : -1); - return; - } - ctx->ret = len; - (void) unsent; - (void) unacked; -} - -int mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) { - struct mg_lwip_tcp_write_ctx ctx = {.nc = nc, .data = buf, .len = len}; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (nc->sock == INVALID_SOCKET) return -1; - struct tcp_pcb *tpcb = cs->pcb.tcp; - if (tpcb == NULL) return -1; - if (tpcb->snd_buf <= 0) return 0; - tcpip_callback(mg_lwip_tcp_write_tcpip, &ctx); - return ctx.ret; -} - -struct udp_sendto_ctx { - struct udp_pcb *upcb; - struct pbuf *p; - ip_addr_t *ip; - uint16_t port; - int ret; -}; - -static void udp_sendto_tcpip(void *arg) { - struct udp_sendto_ctx *ctx = (struct udp_sendto_ctx *) arg; - ctx->ret = udp_sendto(ctx->upcb, ctx->p, ctx->ip, ctx->port); -} - -static int mg_lwip_if_udp_send(struct mg_connection *nc, const void *data, - size_t len) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (nc->sock == INVALID_SOCKET || cs->pcb.udp == NULL) return -1; - struct udp_pcb *upcb = cs->pcb.udp; - struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM); -#if defined(LWIP_IPV4) && LWIP_IPV4 && defined(LWIP_IPV6) && LWIP_IPV6 - ip_addr_t ip = {.u_addr.ip4.addr = nc->sa.sin.sin_addr.s_addr, .type = 0}; -#else - ip_addr_t ip = {.addr = nc->sa.sin.sin_addr.s_addr}; -#endif - u16_t port = ntohs(nc->sa.sin.sin_port); - if (p == NULL) return 0; - memcpy(p->payload, data, len); - struct udp_sendto_ctx ctx = {.upcb = upcb, .p = p, .ip = &ip, .port = port}; - tcpip_callback(udp_sendto_tcpip, &ctx); - cs->err = ctx.ret; - pbuf_free(p); - return (cs->err == ERR_OK ? (int) len : -2); -} - -static int mg_lwip_if_can_send(struct mg_connection *nc, - struct mg_lwip_conn_state *cs) { - int can_send = 0; - if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) { - /* We have stuff to send, but can we? */ - if (nc->flags & MG_F_UDP) { - /* UDP is always ready for sending. */ - can_send = (cs->pcb.udp != NULL); - } else { - can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0); -/* See comment above. */ -#if CS_PLATFORM == CS_P_ESP8266 - if (cs->pcb.tcp->unacked != NULL) can_send = 0; -#endif - } - } - return can_send; -} - -struct tcp_recved_ctx { - struct tcp_pcb *tpcb; - size_t len; -}; - -void tcp_recved_tcpip(void *arg) { - struct tcp_recved_ctx *ctx = (struct tcp_recved_ctx *) arg; - if (ctx->tpcb != NULL) tcp_recved(ctx->tpcb, ctx->len); -} - -static int mg_lwip_if_tcp_recv(struct mg_connection *nc, void *buf, - size_t len) { - int res = 0; - char *bufp = buf; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (nc->sock == INVALID_SOCKET) return -1; - mgos_lock(); - while (cs->rx_chain != NULL && len > 0) { - struct pbuf *seg = cs->rx_chain; - size_t seg_len = (seg->len - cs->rx_offset); - size_t copy_len = MIN(len, seg_len); - - pbuf_copy_partial(seg, bufp, copy_len, cs->rx_offset); - len -= copy_len; - res += copy_len; - bufp += copy_len; - cs->rx_offset += copy_len; - if (cs->rx_offset == cs->rx_chain->len) { - cs->rx_chain = pbuf_dechain(cs->rx_chain); - pbuf_free(seg); - cs->rx_offset = 0; - } - } - mgos_unlock(); - if (res > 0) { - struct tcp_recved_ctx ctx = {.tpcb = cs->pcb.tcp, .len = res}; - tcpip_callback(tcp_recved_tcpip, &ctx); - } - return res; -} - -int mg_lwip_if_create_conn(struct mg_connection *nc) { - struct mg_lwip_conn_state *cs = - (struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs)); - if (cs == NULL) return 0; - cs->nc = nc; - nc->sock = (intptr_t) cs; - return 1; -} - -static void udp_remove_tcpip(void *arg) { - udp_remove((struct udp_pcb *) arg); -} - -void mg_lwip_if_destroy_conn(struct mg_connection *nc) { - if (nc->sock == INVALID_SOCKET) return; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (!(nc->flags & MG_F_UDP)) { - struct tcp_pcb *tpcb = cs->pcb.tcp; - if (tpcb != NULL) { - tcp_arg(tpcb, NULL); - DBG(("%p tcp_close %p", nc, tpcb)); - tcp_arg(tpcb, NULL); - tcpip_callback(tcp_close_tcpip, tpcb); - } - while (cs->rx_chain != NULL) { - struct pbuf *seg = cs->rx_chain; - cs->rx_chain = pbuf_dechain(cs->rx_chain); - pbuf_free(seg); - } - memset(cs, 0, sizeof(*cs)); - MG_FREE(cs); - } else if (nc->listener == NULL) { - /* Only close outgoing UDP pcb or listeners. */ - struct udp_pcb *upcb = cs->pcb.udp; - if (upcb != NULL) { - DBG(("%p udp_remove %p", nc, upcb)); - tcpip_callback(udp_remove_tcpip, upcb); - } - memset(cs, 0, sizeof(*cs)); - MG_FREE(cs); - } - nc->sock = INVALID_SOCKET; -} - -void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote, - union socket_address *sa) { - memset(sa, 0, sizeof(*sa)); - if (nc == NULL || nc->sock == INVALID_SOCKET) return; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (nc->flags & MG_F_UDP) { - struct udp_pcb *upcb = cs->pcb.udp; - if (remote) { - memcpy(sa, &nc->sa, sizeof(*sa)); - } else if (upcb != NULL) { - sa->sin.sin_port = htons(upcb->local_port); - SET_ADDR(sa, &upcb->local_ip); - } - } else { - struct tcp_pcb *tpcb = cs->pcb.tcp; - if (remote) { - memcpy(sa, &nc->sa, sizeof(*sa)); - } else if (tpcb != NULL) { - sa->sin.sin_port = htons(tpcb->local_port); - SET_ADDR(sa, &tpcb->local_ip); - } - } -} - -void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) { - nc->sock = sock; -} - -/* clang-format off */ -#define MG_LWIP_IFACE_VTABLE \ - { \ - mg_lwip_if_init, \ - mg_lwip_if_free, \ - mg_lwip_if_add_conn, \ - mg_lwip_if_remove_conn, \ - mg_lwip_if_poll, \ - mg_lwip_if_listen_tcp, \ - mg_lwip_if_listen_udp, \ - mg_lwip_if_connect_tcp, \ - mg_lwip_if_connect_udp, \ - mg_lwip_if_tcp_send, \ - mg_lwip_if_udp_send, \ - mg_lwip_if_tcp_recv, \ - mg_lwip_if_udp_recv, \ - mg_lwip_if_create_conn, \ - mg_lwip_if_destroy_conn, \ - mg_lwip_if_sock_set, \ - mg_lwip_if_get_conn_addr, \ - } -/* clang-format on */ - -const struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE; -#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL -const struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE; -#endif - -#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/lwip/mg_lwip_ev_mgr.c" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL - -#ifndef MG_SIG_QUEUE_LEN -#define MG_SIG_QUEUE_LEN 32 -#endif - -struct mg_ev_mgr_lwip_signal { - int sig; - struct mg_connection *nc; -}; - -struct mg_ev_mgr_lwip_data { - struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN]; - int sig_queue_len; - int start_index; -}; - -void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) { - struct mg_ev_mgr_lwip_data *md = - (struct mg_ev_mgr_lwip_data *) nc->iface->data; - mgos_lock(); - if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) { - mgos_unlock(); - return; - } - int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN; - md->sig_queue[end_index].sig = sig; - md->sig_queue[end_index].nc = nc; - md->sig_queue_len++; - mg_lwip_mgr_schedule_poll(nc->mgr); - mgos_unlock(); -} - -void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) { - struct mg_ev_mgr_lwip_data *md = - (struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data; - while (md->sig_queue_len > 0) { - mgos_lock(); - int i = md->start_index; - int sig = md->sig_queue[i].sig; - struct mg_connection *nc = md->sig_queue[i].nc; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - md->start_index = (i + 1) % MG_SIG_QUEUE_LEN; - md->sig_queue_len--; - mgos_unlock(); - if (nc->iface == NULL || nc->mgr == NULL) continue; - switch (sig) { - case MG_SIG_CONNECT_RESULT: { - mg_if_connect_cb(nc, cs->err); - break; - } - case MG_SIG_CLOSE_CONN: { - mg_close_conn(nc); - break; - } - case MG_SIG_RECV: { - cs->recv_pending = 0; - mg_if_can_recv_cb(nc); - mbuf_trim(&nc->recv_mbuf); - break; - } - case MG_SIG_TOMBSTONE: { - break; - } - case MG_SIG_ACCEPT: { - mg_lwip_handle_accept(nc); - break; - } - } - } -} - -void mg_lwip_if_init(struct mg_iface *iface) { - LOG(LL_INFO, ("Mongoose %s, LwIP %u.%u.%u", MG_VERSION, LWIP_VERSION_MAJOR, - LWIP_VERSION_MINOR, LWIP_VERSION_REVISION)); - iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data)); -} - -void mg_lwip_if_free(struct mg_iface *iface) { - MG_FREE(iface->data); - iface->data = NULL; -} - -void mg_lwip_if_add_conn(struct mg_connection *nc) { - (void) nc; -} - -void mg_lwip_if_remove_conn(struct mg_connection *nc) { - struct mg_ev_mgr_lwip_data *md = - (struct mg_ev_mgr_lwip_data *) nc->iface->data; - /* Walk the queue and null-out further signals for this conn. */ - for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) { - if (md->sig_queue[i].nc == nc) { - md->sig_queue[i].sig = MG_SIG_TOMBSTONE; - } - } -} - -time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) { - struct mg_mgr *mgr = iface->mgr; - int n = 0; - double now = mg_time(); - struct mg_connection *nc, *tmp; - double min_timer = 0; - int num_timers = 0; -#if 0 - DBG(("begin poll @%u", (unsigned int) (now * 1000))); -#endif - mg_ev_mgr_lwip_process_signals(mgr); - for (nc = mgr->active_connections; nc != NULL; nc = tmp) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - tmp = nc->next; - n++; - if (!mg_if_poll(nc, now)) continue; - if (nc->sock != INVALID_SOCKET && - !(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL && - cs->pcb.tcp->unsent != NULL) { - tcpip_callback(tcp_output_tcpip, cs->pcb.tcp); - } - if (nc->ev_timer_time > 0) { - if (num_timers == 0 || nc->ev_timer_time < min_timer) { - min_timer = nc->ev_timer_time; - } - num_timers++; - } - - if (nc->sock != INVALID_SOCKET) { - if (mg_lwip_if_can_send(nc, cs)) { - mg_if_can_send_cb(nc); - mbuf_trim(&nc->send_mbuf); - } - if (cs->rx_chain != NULL) { - mg_if_can_recv_cb(nc); - } else if (cs->draining_rx_chain) { - /* - * If the connection is about to close, and rx_chain is finally empty, - * send the MG_SIG_CLOSE_CONN signal - */ - mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); - } - } - } -#if 0 - DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms", - (unsigned int) (now * 1000), n, num_timers, - (unsigned int) (min_timer * 1000), timeout_ms)); -#endif - (void) timeout_ms; - return now; -} - -#endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/wince/wince_libc.c" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifdef WINCE - -const char *strerror(int err) { - /* - * TODO(alashkin): there is no strerror on WinCE; - * look for similar wce_xxxx function - */ - static char buf[10]; - snprintf(buf, sizeof(buf), "%d", err); - return buf; -} - -int open(const char *filename, int oflag, int pmode) { - /* - * TODO(alashkin): mg_open function is not used in mongoose - * but exists in documentation as utility function - * Shall we delete it at all or implement for WinCE as well? - */ - DebugBreak(); - return 0; /* for compiler */ -} - -int _wstati64(const wchar_t *path, cs_stat_t *st) { - DWORD fa = GetFileAttributesW(path); - if (fa == INVALID_FILE_ATTRIBUTES) { - return -1; - } - memset(st, 0, sizeof(*st)); - if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) { - HANDLE h; - FILETIME ftime; - st->st_mode |= _S_IFREG; - h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, NULL); - if (h == INVALID_HANDLE_VALUE) { - return -1; - } - st->st_size = GetFileSize(h, NULL); - GetFileTime(h, NULL, NULL, &ftime); - st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime + - ((uint64_t) ftime.dwHighDateTime << 32)) / - 10000000.0) - - 11644473600); - CloseHandle(h); - } else { - st->st_mode |= _S_IFDIR; - } - return 0; -} - -/* Windows CE doesn't have neither gmtime nor strftime */ -static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) { - FILETIME ft; - SYSTEMTIME systime; - if (t != NULL) { - uint64_t filetime = (*t + 11644473600) * 10000000; - ft.dwLowDateTime = filetime & 0xFFFFFFFF; - ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32; - FileTimeToSystemTime(&ft, &systime); - } else { - GetSystemTime(&systime); - } - /* There is no PRIu16 in WinCE SDK */ - snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear, - (int) systime.wMonth, (int) systime.wDay, (int) systime.wHour, - (int) systime.wMinute, (int) systime.wSecond); -} - -#endif -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/pic32/pic32_net_if.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ -#define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ - -/* Amalgamated: #include "mongoose/src/net_if.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifndef MG_ENABLE_NET_IF_PIC32 -#define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32 -#endif - -extern const struct mg_iface_vtable mg_pic32_iface_vtable; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/pic32/pic32_net_if.c" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if MG_ENABLE_NET_IF_PIC32 - -int mg_pic32_if_create_conn(struct mg_connection *nc) { - (void) nc; - return 1; -} - -void mg_pic32_if_recved(struct mg_connection *nc, size_t len) { - (void) nc; - (void) len; -} - -void mg_pic32_if_add_conn(struct mg_connection *nc) { - (void) nc; -} - -void mg_pic32_if_init(struct mg_iface *iface) { - (void) iface; - (void) mg_get_errno(); /* Shutup compiler */ -} - -void mg_pic32_if_free(struct mg_iface *iface) { - (void) iface; -} - -void mg_pic32_if_remove_conn(struct mg_connection *nc) { - (void) nc; -} - -void mg_pic32_if_destroy_conn(struct mg_connection *nc) { - if (nc->sock == INVALID_SOCKET) return; - /* For UDP, only close outgoing sockets or listeners. */ - if (!(nc->flags & MG_F_UDP)) { - /* Close TCP */ - TCPIP_TCP_Close((TCP_SOCKET) nc->sock); - } else if (nc->listener == NULL) { - /* Only close outgoing UDP or listeners. */ - TCPIP_UDP_Close((UDP_SOCKET) nc->sock); - } - - nc->sock = INVALID_SOCKET; -} - -int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { - nc->sock = TCPIP_UDP_ServerOpen( - sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 - : IP_ADDRESS_TYPE_IPV6, - ntohs(sa->sin.sin_port), - sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin); - if (nc->sock == INVALID_SOCKET) { - return -1; - } - return 0; -} - -void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf, - size_t len) { - mbuf_append(&nc->send_mbuf, buf, len); -} - -void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf, - size_t len) { - mbuf_append(&nc->send_mbuf, buf, len); -} - -int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { - nc->sock = TCPIP_TCP_ServerOpen( - sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 - : IP_ADDRESS_TYPE_IPV6, - ntohs(sa->sin.sin_port), - sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin); - memcpy(&nc->sa, sa, sizeof(*sa)); - if (nc->sock == INVALID_SOCKET) { - return -1; - } - return 0; -} - -static int mg_accept_conn(struct mg_connection *lc) { - struct mg_connection *nc; - TCP_SOCKET_INFO si; - union socket_address sa; - - nc = mg_if_accept_new_conn(lc); - - if (nc == NULL) { - return 0; - } - - nc->sock = lc->sock; - nc->flags &= ~MG_F_LISTENING; - - if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) { - return 0; - } - - if (si.addressType == IP_ADDRESS_TYPE_IPV4) { - sa.sin.sin_family = AF_INET; - sa.sin.sin_port = htons(si.remotePort); - sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val; - } else { - /* TODO(alashkin): do something with _potential_ IPv6 */ - memset(&sa, 0, sizeof(sa)); - } - - mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa)); - - return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0; -} - -char *inet_ntoa(struct in_addr in) { - static char addr[17]; - snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1, - (int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3, - (int) in.S_un.S_un_b.s_b4); - return addr; -} - -static void mg_handle_send(struct mg_connection *nc) { - uint16_t bytes_written = 0; - if (nc->flags & MG_F_UDP) { - if (!TCPIP_UDP_RemoteBind( - (UDP_SOCKET) nc->sock, - nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 - : IP_ADDRESS_TYPE_IPV6, - ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - return; - } - bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0); - if (bytes_written >= nc->send_mbuf.len) { - if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock, - (uint8_t *) nc->send_mbuf.buf, - nc->send_mbuf.len) != nc->send_mbuf.len) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - bytes_written = 0; - } - } - } else { - bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock); - if (bytes_written != 0) { - if (bytes_written > nc->send_mbuf.len) { - bytes_written = nc->send_mbuf.len; - } - if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock, - (uint8_t *) nc->send_mbuf.buf, - bytes_written) != bytes_written) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - bytes_written = 0; - } - } - } - - mg_if_sent_cb(nc, bytes_written); -} - -static void mg_handle_recv(struct mg_connection *nc) { - uint16_t bytes_read = 0; - uint8_t *buf = NULL; - if (nc->flags & MG_F_UDP) { - bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock); - if (bytes_read != 0 && - (nc->recv_mbuf_limit == -1 || - nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) { - buf = (uint8_t *) MG_MALLOC(bytes_read); - if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) != - bytes_read) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - bytes_read = 0; - MG_FREE(buf); - } - } - } else { - bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock); - if (bytes_read != 0) { - if (nc->recv_mbuf_limit != -1 && - nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) { - bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len; - } - buf = (uint8_t *) MG_MALLOC(bytes_read); - if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) != - bytes_read) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - MG_FREE(buf); - bytes_read = 0; - } - } - } - - if (bytes_read != 0) { - mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */); - } -} - -time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) { - struct mg_mgr *mgr = iface->mgr; - double now = mg_time(); - struct mg_connection *nc, *tmp; - - for (nc = mgr->active_connections; nc != NULL; nc = tmp) { - tmp = nc->next; - - if (nc->flags & MG_F_CONNECTING) { - /* processing connections */ - if (nc->flags & MG_F_UDP || - TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) { - mg_if_connect_cb(nc, 0); - } - } else if (nc->flags & MG_F_LISTENING) { - if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) { - /* accept new connections */ - mg_accept_conn(nc); - } - } else { - if (nc->send_mbuf.len != 0) { - mg_handle_send(nc); - } - - if (nc->recv_mbuf_limit == -1 || - nc->recv_mbuf.len < nc->recv_mbuf_limit) { - mg_handle_recv(nc); - } - } - } - - for (nc = mgr->active_connections; nc != NULL; nc = tmp) { - tmp = nc->next; - if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) || - (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) { - mg_close_conn(nc); - } - } - - return now; -} - -void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) { - nc->sock = sock; -} - -void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote, - union socket_address *sa) { - /* TODO(alaskin): not implemented yet */ -} - -void mg_pic32_if_connect_tcp(struct mg_connection *nc, - const union socket_address *sa) { - nc->sock = TCPIP_TCP_ClientOpen( - sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 - : IP_ADDRESS_TYPE_IPV6, - ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin); - nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0; -} - -void mg_pic32_if_connect_udp(struct mg_connection *nc) { - nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL); - nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0; -} - -/* clang-format off */ -#define MG_PIC32_IFACE_VTABLE \ - { \ - mg_pic32_if_init, \ - mg_pic32_if_free, \ - mg_pic32_if_add_conn, \ - mg_pic32_if_remove_conn, \ - mg_pic32_if_poll, \ - mg_pic32_if_listen_tcp, \ - mg_pic32_if_listen_udp, \ - mg_pic32_if_connect_tcp, \ - mg_pic32_if_connect_udp, \ - mg_pic32_if_tcp_send, \ - mg_pic32_if_udp_send, \ - mg_pic32_if_recved, \ - mg_pic32_if_create_conn, \ - mg_pic32_if_destroy_conn, \ - mg_pic32_if_sock_set, \ - mg_pic32_if_get_conn_addr, \ - } -/* clang-format on */ - -const struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE; -#if MG_NET_IF == MG_NET_IF_PIC32 -const struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE; -#endif - -#endif /* MG_ENABLE_NET_IF_PIC32 */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/windows/windows_direct.c" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifdef _WIN32 - -int rmdir(const char *dirname) { - return _rmdir(dirname); -} - -unsigned int sleep(unsigned int seconds) { - Sleep(seconds * 1000); - return 0; -} - -#endif /* _WIN32 */ diff --git a/util/mongoose.h b/util/mongoose.h deleted file mode 100644 index 0f85b18..0000000 --- a/util/mongoose.h +++ /dev/null @@ -1,6683 +0,0 @@ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_common.h" -#endif -/* - * Copyright (c) 2004-2013 Sergey Lyubka - * Copyright (c) 2013-2015 Cesanta Software Limited - * All rights reserved - * - * This software is dual-licensed: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. For the terms of this - * license, see . - * - * You are free to use this software under the terms of the GNU General - * Public License, but WITHOUT ANY WARRANTY; without even the implied - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * Alternatively, you can license this software under a commercial - * license, as set out in . - */ - -#ifndef CS_MONGOOSE_SRC_COMMON_H_ -#define CS_MONGOOSE_SRC_COMMON_H_ - -#define MG_VERSION "6.14" - -/* Local tweaks, applied before any of Mongoose's own headers. */ -#ifdef MG_LOCALS -#include -#endif - -#endif /* CS_MONGOOSE_SRC_COMMON_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platform.h" -#endif -#ifndef CS_COMMON_PLATFORM_H_ -#define CS_COMMON_PLATFORM_H_ - -/* - * For the "custom" platform, includes and dependencies can be - * provided through mg_locals.h. - */ -#define CS_P_CUSTOM 0 -#define CS_P_UNIX 1 -#define CS_P_WINDOWS 2 -#define CS_P_ESP32 15 -#define CS_P_ESP8266 3 -#define CS_P_CC3100 6 -#define CS_P_CC3200 4 -#define CS_P_CC3220 17 -#define CS_P_MSP432 5 -#define CS_P_TM4C129 14 -#define CS_P_MBED 7 -#define CS_P_WINCE 8 -#define CS_P_NXP_LPC 13 -#define CS_P_NXP_KINETIS 9 -#define CS_P_NRF51 12 -#define CS_P_NRF52 10 -#define CS_P_PIC32 11 -#define CS_P_STM32 16 -/* Next id: 18 */ - -/* If not specified explicitly, we guess platform by defines. */ -#ifndef CS_PLATFORM - -#if defined(TARGET_IS_MSP432P4XX) || defined(__MSP432P401R__) -#define CS_PLATFORM CS_P_MSP432 -#elif defined(cc3200) || defined(TARGET_IS_CC3200) -#define CS_PLATFORM CS_P_CC3200 -#elif defined(cc3220) || defined(TARGET_IS_CC3220) -#define CS_PLATFORM CS_P_CC3220 -#elif defined(__unix__) || defined(__APPLE__) -#define CS_PLATFORM CS_P_UNIX -#elif defined(WINCE) -#define CS_PLATFORM CS_P_WINCE -#elif defined(_WIN32) -#define CS_PLATFORM CS_P_WINDOWS -#elif defined(__MBED__) -#define CS_PLATFORM CS_P_MBED -#elif defined(__USE_LPCOPEN) -#define CS_PLATFORM CS_P_NXP_LPC -#elif defined(FRDM_K64F) || defined(FREEDOM) -#define CS_PLATFORM CS_P_NXP_KINETIS -#elif defined(PIC32) -#define CS_PLATFORM CS_P_PIC32 -#elif defined(ESP_PLATFORM) -#define CS_PLATFORM CS_P_ESP32 -#elif defined(ICACHE_FLASH) -#define CS_PLATFORM CS_P_ESP8266 -#elif defined(TARGET_IS_TM4C129_RA0) || defined(TARGET_IS_TM4C129_RA1) || \ - defined(TARGET_IS_TM4C129_RA2) -#define CS_PLATFORM CS_P_TM4C129 -#elif defined(STM32) -#define CS_PLATFORM CS_P_STM32 -#endif - -#ifndef CS_PLATFORM -#error "CS_PLATFORM is not specified and we couldn't guess it." -#endif - -#endif /* !defined(CS_PLATFORM) */ - -#define MG_NET_IF_SOCKET 1 -#define MG_NET_IF_SIMPLELINK 2 -#define MG_NET_IF_LWIP_LOW_LEVEL 3 -#define MG_NET_IF_PIC32 4 -#define MG_NET_IF_NULL 5 - -#define MG_SSL_IF_OPENSSL 1 -#define MG_SSL_IF_MBEDTLS 2 -#define MG_SSL_IF_SIMPLELINK 3 - -/* Amalgamated: #include "common/platforms/platform_unix.h" */ -/* Amalgamated: #include "common/platforms/platform_windows.h" */ -/* Amalgamated: #include "common/platforms/platform_esp32.h" */ -/* Amalgamated: #include "common/platforms/platform_esp8266.h" */ -/* Amalgamated: #include "common/platforms/platform_cc3100.h" */ -/* Amalgamated: #include "common/platforms/platform_cc3200.h" */ -/* Amalgamated: #include "common/platforms/platform_cc3220.h" */ -/* Amalgamated: #include "common/platforms/platform_mbed.h" */ -/* Amalgamated: #include "common/platforms/platform_nrf51.h" */ -/* Amalgamated: #include "common/platforms/platform_nrf52.h" */ -/* Amalgamated: #include "common/platforms/platform_wince.h" */ -/* Amalgamated: #include "common/platforms/platform_nxp_lpc.h" */ -/* Amalgamated: #include "common/platforms/platform_nxp_kinetis.h" */ -/* Amalgamated: #include "common/platforms/platform_pic32.h" */ -/* Amalgamated: #include "common/platforms/platform_stm32.h" */ - -/* Common stuff */ - -#if !defined(PRINTF_LIKE) -#if defined(__GNUC__) || defined(__clang__) || defined(__TI_COMPILER_VERSION__) -#define PRINTF_LIKE(f, a) __attribute__((format(printf, f, a))) -#else -#define PRINTF_LIKE(f, a) -#endif -#endif - -#if !defined(WEAK) -#if (defined(__GNUC__) || defined(__clang__) || \ - defined(__TI_COMPILER_VERSION__)) && \ - !defined(_WIN32) -#define WEAK __attribute__((weak)) -#else -#define WEAK -#endif -#endif - -#ifdef __GNUC__ -#define NORETURN __attribute__((noreturn)) -#define NOINLINE __attribute__((noinline)) -#define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) -#define NOINSTR __attribute__((no_instrument_function)) -#define DO_NOT_WARN_UNUSED __attribute__((unused)) -#else -#define NORETURN -#define NOINLINE -#define WARN_UNUSED_RESULT -#define NOINSTR -#define DO_NOT_WARN_UNUSED -#endif /* __GNUC__ */ - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0])) -#endif - -#endif /* CS_COMMON_PLATFORM_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_windows.h" -#endif -#ifndef CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_ -#if CS_PLATFORM == CS_P_WINDOWS - -/* - * MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) - * MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013) - * MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012) - * MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010) - * MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008) - * MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005) - * MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio 2003) - * MSVC++ 7.0 _MSC_VER == 1300 - * MSVC++ 6.0 _MSC_VER == 1200 - * MSVC++ 5.0 _MSC_VER == 1100 - */ -#ifdef _MSC_VER -#pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */ -#pragma warning(disable : 4204) /* missing c99 support */ -#endif - -#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS -#define _WINSOCK_DEPRECATED_NO_WARNINGS 1 -#endif - -#ifndef _CRT_SECURE_NO_WARNINGS -#define _CRT_SECURE_NO_WARNINGS -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -#pragma comment(lib, "ws2_32.lib") /* Linking with winsock library */ -#endif - -#include -#include -#include -#include - -#if _MSC_VER < 1700 -typedef int bool; -#else -#include -#endif - -#if defined(_MSC_VER) && _MSC_VER >= 1800 -#define strdup _strdup -#endif - -#ifndef EINPROGRESS -#define EINPROGRESS WSAEINPROGRESS -#endif -#ifndef EWOULDBLOCK -#define EWOULDBLOCK WSAEWOULDBLOCK -#endif -#ifndef __func__ -#define STRX(x) #x -#define STR(x) STRX(x) -#define __func__ __FILE__ ":" STR(__LINE__) -#endif -#define snprintf _snprintf -#define vsnprintf _vsnprintf -#define to64(x) _atoi64(x) -#if !defined(__MINGW32__) && !defined(__MINGW64__) -#define popen(x, y) _popen((x), (y)) -#define pclose(x) _pclose(x) -#define fileno _fileno -#endif -#if defined(_MSC_VER) && _MSC_VER >= 1400 -#define fseeko(x, y, z) _fseeki64((x), (y), (z)) -#else -#define fseeko(x, y, z) fseek((x), (y), (z)) -#endif -#if defined(_MSC_VER) && _MSC_VER <= 1200 -typedef unsigned long uintptr_t; -typedef long intptr_t; -#endif -typedef int socklen_t; -#if _MSC_VER >= 1700 -#include -#else -typedef signed char int8_t; -typedef unsigned char uint8_t; -typedef int int32_t; -typedef unsigned int uint32_t; -typedef short int16_t; -typedef unsigned short uint16_t; -typedef __int64 int64_t; -typedef unsigned __int64 uint64_t; -#endif -typedef SOCKET sock_t; -typedef uint32_t in_addr_t; -#ifndef UINT16_MAX -#define UINT16_MAX 65535 -#endif -#ifndef UINT32_MAX -#define UINT32_MAX 4294967295 -#endif -#ifndef pid_t -#define pid_t HANDLE -#endif -#define INT64_FMT "I64d" -#define INT64_X_FMT "I64x" -#define SIZE_T_FMT "Iu" -typedef struct _stati64 cs_stat_t; -#ifndef S_ISDIR -#define S_ISDIR(x) (((x) &_S_IFMT) == _S_IFDIR) -#endif -#ifndef S_ISREG -#define S_ISREG(x) (((x) &_S_IFMT) == _S_IFREG) -#endif -#define DIRSEP '\\' -#define CS_DEFINE_DIRENT - -#ifndef va_copy -#ifdef __va_copy -#define va_copy __va_copy -#else -#define va_copy(x, y) (x) = (y) -#endif -#endif - -#ifndef MG_MAX_HTTP_REQUEST_SIZE -#define MG_MAX_HTTP_REQUEST_SIZE 8192 -#endif - -#ifndef MG_MAX_HTTP_SEND_MBUF -#define MG_MAX_HTTP_SEND_MBUF 4096 -#endif - -#ifndef MG_MAX_HTTP_HEADERS -#define MG_MAX_HTTP_HEADERS 40 -#endif - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#ifndef MG_ENABLE_BROADCAST -#define MG_ENABLE_BROADCAST 1 -#endif - -#ifndef MG_ENABLE_DIRECTORY_LISTING -#define MG_ENABLE_DIRECTORY_LISTING 1 -#endif - -#ifndef MG_ENABLE_FILESYSTEM -#define MG_ENABLE_FILESYSTEM 1 -#endif - -#ifndef MG_ENABLE_HTTP_CGI -#define MG_ENABLE_HTTP_CGI MG_ENABLE_FILESYSTEM -#endif - -#ifndef MG_NET_IF -#define MG_NET_IF MG_NET_IF_SOCKET -#endif - -unsigned int sleep(unsigned int seconds); - -/* https://stackoverflow.com/questions/16647819/timegm-cross-platform */ -#define timegm _mkgmtime - -#define gmtime_r(a, b) \ - do { \ - *(b) = *gmtime(a); \ - } while (0) - -#endif /* CS_PLATFORM == CS_P_WINDOWS */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_unix.h" -#endif -#ifndef CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_ -#if CS_PLATFORM == CS_P_UNIX - -#ifndef _XOPEN_SOURCE -#define _XOPEN_SOURCE 600 -#endif - -/* wants this for C++ */ -#ifndef __STDC_FORMAT_MACROS -#define __STDC_FORMAT_MACROS -#endif - -/* C++ wants that for INT64_MAX */ -#ifndef __STDC_LIMIT_MACROS -#define __STDC_LIMIT_MACROS -#endif - -/* Enable fseeko() and ftello() functions */ -#ifndef _LARGEFILE_SOURCE -#define _LARGEFILE_SOURCE -#endif - -/* Enable 64-bit file offsets */ -#ifndef _FILE_OFFSET_BITS -#define _FILE_OFFSET_BITS 64 -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef __APPLE__ -#include -#ifndef BYTE_ORDER -#define LITTLE_ENDIAN __DARWIN_LITTLE_ENDIAN -#define BIG_ENDIAN __DARWIN_BIG_ENDIAN -#define PDP_ENDIAN __DARWIN_PDP_ENDIAN -#define BYTE_ORDER __DARWIN_BYTE_ORDER -#endif -#endif - -/* - * osx correctly avoids defining strtoll when compiling in strict ansi mode. - * c++ 11 standard defines strtoll as well. - * We require strtoll, and if your embedded pre-c99 compiler lacks one, please - * implement a shim. - */ -#if !(defined(__cplusplus) && __cplusplus >= 201103L) && \ - !(defined(__DARWIN_C_LEVEL) && __DARWIN_C_LEVEL >= 200809L) -long long strtoll(const char *, char **, int); -#endif - -typedef int sock_t; -#define INVALID_SOCKET (-1) -#define SIZE_T_FMT "zu" -typedef struct stat cs_stat_t; -#define DIRSEP '/' -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 - -#ifndef __cdecl -#define __cdecl -#endif - -#ifndef va_copy -#ifdef __va_copy -#define va_copy __va_copy -#else -#define va_copy(x, y) (x) = (y) -#endif -#endif - -#define closesocket(x) close(x) - -#ifndef MG_MAX_HTTP_REQUEST_SIZE -#define MG_MAX_HTTP_REQUEST_SIZE 8192 -#endif - -#ifndef MG_MAX_HTTP_SEND_MBUF -#define MG_MAX_HTTP_SEND_MBUF 4096 -#endif - -#ifndef MG_MAX_HTTP_HEADERS -#define MG_MAX_HTTP_HEADERS 40 -#endif - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#ifndef MG_ENABLE_BROADCAST -#define MG_ENABLE_BROADCAST 1 -#endif - -#ifndef MG_ENABLE_DIRECTORY_LISTING -#define MG_ENABLE_DIRECTORY_LISTING 1 -#endif - -#ifndef MG_ENABLE_FILESYSTEM -#define MG_ENABLE_FILESYSTEM 1 -#endif - -#ifndef MG_ENABLE_HTTP_CGI -#define MG_ENABLE_HTTP_CGI MG_ENABLE_FILESYSTEM -#endif - -#ifndef MG_NET_IF -#define MG_NET_IF MG_NET_IF_SOCKET -#endif - -#ifndef MG_HOSTS_FILE_NAME -#define MG_HOSTS_FILE_NAME "/etc/hosts" -#endif - -#ifndef MG_RESOLV_CONF_FILE_NAME -#define MG_RESOLV_CONF_FILE_NAME "/etc/resolv.conf" -#endif - -#endif /* CS_PLATFORM == CS_P_UNIX */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_esp32.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_ -#if CS_PLATFORM == CS_P_ESP32 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define DIRSEP '/' -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define __cdecl -#define _FILE_OFFSET_BITS 32 - -#define MG_LWIP 1 - -#ifndef MG_NET_IF -#define MG_NET_IF MG_NET_IF_SOCKET -#endif - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#endif /* CS_PLATFORM == CS_P_ESP32 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_esp8266.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_ -#if CS_PLATFORM == CS_P_ESP8266 - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define DIRSEP '/' -#if !defined(MGOS_VFS_DEFINE_DIRENT) -#define CS_DEFINE_DIRENT -#endif - -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define __cdecl -#define _FILE_OFFSET_BITS 32 - -#define MG_LWIP 1 - -/* struct timeval is defined in sys/time.h. */ -#define LWIP_TIMEVAL_PRIVATE 0 - -#ifndef MG_NET_IF -#include -#if LWIP_SOCKET /* RTOS SDK has LWIP sockets */ -#define MG_NET_IF MG_NET_IF_SOCKET -#else -#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL -#endif -#endif - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#define inet_ntop(af, src, dst, size) \ - (((af) == AF_INET) ? ipaddr_ntoa_r((const ip_addr_t *) (src), (dst), (size)) \ - : NULL) -#define inet_pton(af, src, dst) \ - (((af) == AF_INET) ? ipaddr_aton((src), (ip_addr_t *) (dst)) : 0) - -#endif /* CS_PLATFORM == CS_P_ESP8266 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_cc3100.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_ -#if CS_PLATFORM == CS_P_CC3100 - -#include -#include -#include -#include -#include -#include -#include - -#define MG_NET_IF MG_NET_IF_SIMPLELINK -#define MG_SSL_IF MG_SSL_IF_SIMPLELINK - -/* - * CC3100 SDK and STM32 SDK include headers w/out path, just like - * #include "simplelink.h". As result, we have to add all required directories - * into Makefile IPATH and do the same thing (include w/out path) - */ - -#include -#include -#undef timeval - -typedef int sock_t; -#define INVALID_SOCKET (-1) - -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define SIZE_T_FMT "u" - -#define SOMAXCONN 8 - -const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); -char *inet_ntoa(struct in_addr in); -int inet_pton(int af, const char *src, void *dst); - -#endif /* CS_PLATFORM == CS_P_CC3100 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_cc3200.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ -#if CS_PLATFORM == CS_P_CC3200 - -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef __TI_COMPILER_VERSION__ -#include -#include -#endif - -#define MG_NET_IF MG_NET_IF_SIMPLELINK -#define MG_SSL_IF MG_SSL_IF_SIMPLELINK - -/* Only SPIFFS supports directories, SLFS does not. */ -#if defined(CC3200_FS_SPIFFS) && !defined(MG_ENABLE_DIRECTORY_LISTING) -#define MG_ENABLE_DIRECTORY_LISTING 1 -#endif - -/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */ - -typedef int sock_t; -#define INVALID_SOCKET (-1) -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define DIRSEP '/' -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define __cdecl - -#define fileno(x) -1 - -/* Some functions we implement for Mongoose. */ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __TI_COMPILER_VERSION__ -struct SlTimeval_t; -#define timeval SlTimeval_t -int gettimeofday(struct timeval *t, void *tz); -int settimeofday(const struct timeval *tv, const void *tz); - -int asprintf(char **strp, const char *fmt, ...); - -#endif - -/* TI's libc does not have stat & friends, add them. */ -#ifdef __TI_COMPILER_VERSION__ - -#include - -typedef unsigned int mode_t; -typedef size_t _off_t; -typedef long ssize_t; - -struct stat { - int st_ino; - mode_t st_mode; - int st_nlink; - time_t st_mtime; - off_t st_size; -}; - -int _stat(const char *pathname, struct stat *st); -int stat(const char *pathname, struct stat *st); - -#define __S_IFMT 0170000 - -#define __S_IFDIR 0040000 -#define __S_IFCHR 0020000 -#define __S_IFREG 0100000 - -#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask)) - -#define S_IFDIR __S_IFDIR -#define S_IFCHR __S_IFCHR -#define S_IFREG __S_IFREG -#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR) -#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG) - -/* 5.x series compilers don't have va_copy, 16.x do. */ -#if __TI_COMPILER_VERSION__ < 16000000 -#define va_copy(apc, ap) ((apc) = (ap)) -#endif - -#endif /* __TI_COMPILER_VERSION__ */ - -#ifdef CC3200_FS_SLFS -#define MG_FS_SLFS -#endif - -#if (defined(CC3200_FS_SPIFFS) || defined(CC3200_FS_SLFS)) && \ - !defined(MG_ENABLE_FILESYSTEM) -#define MG_ENABLE_FILESYSTEM 1 -#define CS_DEFINE_DIRENT -#endif - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* CS_PLATFORM == CS_P_CC3200 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_cc3220.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3220_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_CC3220_H_ -#if CS_PLATFORM == CS_P_CC3220 - -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef __TI_COMPILER_VERSION__ -#include -#include -#endif - -#define MG_NET_IF MG_NET_IF_SIMPLELINK -#ifndef MG_SSL_IF -#define MG_SSL_IF MG_SSL_IF_SIMPLELINK -#endif - -/* Only SPIFFS supports directories, SLFS does not. */ -#if defined(CC3220_FS_SPIFFS) && !defined(MG_ENABLE_DIRECTORY_LISTING) -#define MG_ENABLE_DIRECTORY_LISTING 1 -#endif - -/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */ - -typedef int sock_t; -#define INVALID_SOCKET (-1) -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define DIRSEP '/' -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define __cdecl - -#define fileno(x) -1 - -/* Some functions we implement for Mongoose. */ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __TI_COMPILER_VERSION__ -struct SlTimeval_t; -#define timeval SlTimeval_t -int gettimeofday(struct timeval *t, void *tz); -int settimeofday(const struct timeval *tv, const void *tz); - -int asprintf(char **strp, const char *fmt, ...); - -#endif - -/* TI's libc does not have stat & friends, add them. */ -#ifdef __TI_COMPILER_VERSION__ - -#include - -typedef unsigned int mode_t; -typedef size_t _off_t; -typedef long ssize_t; - -struct stat { - int st_ino; - mode_t st_mode; - int st_nlink; - time_t st_mtime; - off_t st_size; -}; - -int _stat(const char *pathname, struct stat *st); -int stat(const char *pathname, struct stat *st); - -#define __S_IFMT 0170000 - -#define __S_IFDIR 0040000 -#define __S_IFCHR 0020000 -#define __S_IFREG 0100000 - -#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask)) - -#define S_IFDIR __S_IFDIR -#define S_IFCHR __S_IFCHR -#define S_IFREG __S_IFREG -#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR) -#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG) - -#endif /* __TI_COMPILER_VERSION__ */ - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* CS_PLATFORM == CS_P_CC3220 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_msp432.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_ -#if CS_PLATFORM == CS_P_MSP432 - -#include -#include -#include -#include -#include -#include -#include - -#ifndef __TI_COMPILER_VERSION__ -#include -#include -#endif - -#define MG_NET_IF MG_NET_IF_SIMPLELINK -#define MG_SSL_IF MG_SSL_IF_SIMPLELINK - -/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */ - -typedef int sock_t; -#define INVALID_SOCKET (-1) -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define DIRSEP '/' -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define __cdecl - -#define fileno(x) -1 - -/* Some functions we implement for Mongoose. */ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __TI_COMPILER_VERSION__ -struct SlTimeval_t; -#define timeval SlTimeval_t -int gettimeofday(struct timeval *t, void *tz); -#endif - -/* TI's libc does not have stat & friends, add them. */ -#ifdef __TI_COMPILER_VERSION__ - -#include - -typedef unsigned int mode_t; -typedef size_t _off_t; -typedef long ssize_t; - -struct stat { - int st_ino; - mode_t st_mode; - int st_nlink; - time_t st_mtime; - off_t st_size; -}; - -int _stat(const char *pathname, struct stat *st); -#define stat(a, b) _stat(a, b) - -#define __S_IFMT 0170000 - -#define __S_IFDIR 0040000 -#define __S_IFCHR 0020000 -#define __S_IFREG 0100000 - -#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask)) - -#define S_IFDIR __S_IFDIR -#define S_IFCHR __S_IFCHR -#define S_IFREG __S_IFREG -#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR) -#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG) - -/* As of 5.2.7, TI compiler does not support va_copy() yet. */ -#define va_copy(apc, ap) ((apc) = (ap)) - -#endif /* __TI_COMPILER_VERSION__ */ - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#if (defined(CC3200_FS_SPIFFS) || defined(CC3200_FS_SLFS)) && \ - !defined(MG_ENABLE_FILESYSTEM) -#define MG_ENABLE_FILESYSTEM 1 -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* CS_PLATFORM == CS_P_MSP432 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_tm4c129.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_ -#if CS_PLATFORM == CS_P_TM4C129 - -#include -#include -#include -#include -#include -#include -#include - -#ifndef __TI_COMPILER_VERSION__ -#include -#include -#endif - -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define DIRSEP '/' -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define __cdecl - -#ifndef MG_NET_IF -#include -#if LWIP_SOCKET -#define MG_NET_IF MG_NET_IF_SOCKET -#else -#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL -#endif -#define MG_LWIP 1 -#elif MG_NET_IF == MG_NET_IF_SIMPLELINK -/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */ -#endif - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#ifdef __TI_COMPILER_VERSION__ -/* As of 5.2.8, TI compiler does not support va_copy() yet. */ -#define va_copy(apc, ap) ((apc) = (ap)) -#endif /* __TI_COMPILER_VERSION__ */ - -#ifdef __cplusplus -} -#endif - -#endif /* CS_PLATFORM == CS_P_TM4C129 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_mbed.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_MBED_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_MBED_H_ -#if CS_PLATFORM == CS_P_MBED - -/* - * mbed.h contains C++ code (e.g. templates), thus, it should be processed - * only if included directly to startup file (ex: main.cpp) - */ -#ifdef __cplusplus -/* Amalgamated: #include "mbed.h" */ -#endif /* __cplusplus */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -typedef struct stat cs_stat_t; -#define DIRSEP '/' - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -/* - * mbed can be compiled with the ARM compiler which - * just doesn't come with a gettimeofday shim - * because it's a BSD API and ARM targets embedded - * non-unix platforms. - */ -#if defined(__ARMCC_VERSION) || defined(__ICCARM__) -#define _TIMEVAL_DEFINED -#define gettimeofday _gettimeofday - -/* copied from GCC on ARM; for some reason useconds are signed */ -typedef long suseconds_t; /* microseconds (signed) */ -struct timeval { - time_t tv_sec; /* seconds */ - suseconds_t tv_usec; /* and microseconds */ -}; - -#endif - -#if MG_NET_IF == MG_NET_IF_SIMPLELINK - -#define MG_SIMPLELINK_NO_OSI 1 - -#include - -typedef int sock_t; -#define INVALID_SOCKET (-1) - -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define SIZE_T_FMT "u" - -#define SOMAXCONN 8 - -const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); -char *inet_ntoa(struct in_addr in); -int inet_pton(int af, const char *src, void *dst); -int inet_aton(const char *cp, struct in_addr *inp); -in_addr_t inet_addr(const char *cp); - -#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */ - -#endif /* CS_PLATFORM == CS_P_MBED */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_MBED_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_nrf51.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_ -#if CS_PLATFORM == CS_P_NRF51 - -#include -#include -#include -#include -#include -#include - -#define to64(x) strtoll(x, NULL, 10) - -#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL -#define MG_LWIP 1 -#define MG_ENABLE_IPV6 1 - -/* - * For ARM C Compiler, make lwip to export `struct timeval`; for other - * compilers, suppress it. - */ -#if !defined(__ARMCC_VERSION) -#define LWIP_TIMEVAL_PRIVATE 0 -#else -struct timeval; -int gettimeofday(struct timeval *tp, void *tzp); -#endif - -#define INT64_FMT PRId64 -#define SIZE_T_FMT "u" - -/* - * ARM C Compiler doesn't have strdup, so we provide it - */ -#define CS_ENABLE_STRDUP defined(__ARMCC_VERSION) - -#endif /* CS_PLATFORM == CS_P_NRF51 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_nrf52.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_ -#if CS_PLATFORM == CS_P_NRF52 - -#include -#include -#include -#include -#include -#include -#include -#include - -#define to64(x) strtoll(x, NULL, 10) - -#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL -#define MG_LWIP 1 -#define MG_ENABLE_IPV6 1 - -#if !defined(ENOSPC) -#define ENOSPC 28 /* No space left on device */ -#endif - -/* - * For ARM C Compiler, make lwip to export `struct timeval`; for other - * compilers, suppress it. - */ -#if !defined(__ARMCC_VERSION) -#define LWIP_TIMEVAL_PRIVATE 0 -#endif - -#define INT64_FMT PRId64 -#define SIZE_T_FMT "u" - -/* - * ARM C Compiler doesn't have strdup, so we provide it - */ -#define CS_ENABLE_STRDUP defined(__ARMCC_VERSION) - -#endif /* CS_PLATFORM == CS_P_NRF52 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/cs_simplelink.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_ -#define CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_ - -#if defined(MG_NET_IF) && MG_NET_IF == MG_NET_IF_SIMPLELINK - -/* If simplelink.h is already included, all bets are off. */ -#if !defined(__SIMPLELINK_H__) - -#include - -#ifndef __TI_COMPILER_VERSION__ -#undef __CONCAT -#undef FD_CLR -#undef FD_ISSET -#undef FD_SET -#undef FD_SETSIZE -#undef FD_ZERO -#undef fd_set -#endif - -#if CS_PLATFORM == CS_P_CC3220 -#include -#include -#include -#include -#else -/* We want to disable SL_INC_STD_BSD_API_NAMING, so we include user.h ourselves - * and undef it. */ -#define PROVISIONING_API_H_ -#include -#undef PROVISIONING_API_H_ -#undef SL_INC_STD_BSD_API_NAMING - -#include -#include -#endif /* CS_PLATFORM == CS_P_CC3220 */ - -/* Now define only the subset of the BSD API that we use. - * Notably, close(), read() and write() are not defined. */ -#define AF_INET SL_AF_INET - -#define socklen_t SlSocklen_t -#define sockaddr SlSockAddr_t -#define sockaddr_in SlSockAddrIn_t -#define in_addr SlInAddr_t - -#define SOCK_STREAM SL_SOCK_STREAM -#define SOCK_DGRAM SL_SOCK_DGRAM - -#define htonl sl_Htonl -#define ntohl sl_Ntohl -#define htons sl_Htons -#define ntohs sl_Ntohs - -#ifndef EACCES -#define EACCES SL_EACCES -#endif -#ifndef EAFNOSUPPORT -#define EAFNOSUPPORT SL_EAFNOSUPPORT -#endif -#ifndef EAGAIN -#define EAGAIN SL_EAGAIN -#endif -#ifndef EBADF -#define EBADF SL_EBADF -#endif -#ifndef EINVAL -#define EINVAL SL_EINVAL -#endif -#ifndef ENOMEM -#define ENOMEM SL_ENOMEM -#endif -#ifndef EWOULDBLOCK -#define EWOULDBLOCK SL_EWOULDBLOCK -#endif - -#define SOMAXCONN 8 - -#ifdef __cplusplus -extern "C" { -#endif - -const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); -char *inet_ntoa(struct in_addr in); -int inet_pton(int af, const char *src, void *dst); - -struct mg_mgr; -struct mg_connection; - -typedef void (*mg_init_cb)(struct mg_mgr *mgr); -bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init); - -void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg); - -int sl_fs_init(void); - -void sl_restart_cb(struct mg_mgr *mgr); - -int sl_set_ssl_opts(int sock, struct mg_connection *nc); - -#ifdef __cplusplus -} -#endif - -#endif /* !defined(__SIMPLELINK_H__) */ - -/* Compatibility with older versions of SimpleLink */ -#if SL_MAJOR_VERSION_NUM < 2 - -#define SL_ERROR_BSD_EAGAIN SL_EAGAIN -#define SL_ERROR_BSD_EALREADY SL_EALREADY -#define SL_ERROR_BSD_ENOPROTOOPT SL_ENOPROTOOPT -#define SL_ERROR_BSD_ESECDATEERROR SL_ESECDATEERROR -#define SL_ERROR_BSD_ESECSNOVERIFY SL_ESECSNOVERIFY -#define SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM SL_FS_ERR_FAILED_TO_ALLOCATE_MEM -#define SL_ERROR_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY \ - SL_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY -#define SL_ERROR_FS_FILE_NAME_EXIST SL_FS_FILE_NAME_EXIST -#define SL_ERROR_FS_FILE_NOT_EXISTS SL_FS_ERR_FILE_NOT_EXISTS -#define SL_ERROR_FS_NO_AVAILABLE_NV_INDEX SL_FS_ERR_NO_AVAILABLE_NV_INDEX -#define SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE SL_FS_ERR_NO_AVAILABLE_BLOCKS -#define SL_ERROR_FS_NOT_SUPPORTED SL_FS_ERR_NOT_SUPPORTED -#define SL_ERROR_FS_WRONG_FILE_NAME SL_FS_WRONG_FILE_NAME -#define SL_ERROR_FS_INVALID_HANDLE SL_FS_ERR_INVALID_HANDLE -#define SL_NETCFG_MAC_ADDRESS_GET SL_MAC_ADDRESS_GET -#define SL_SOCKET_FD_ZERO SL_FD_ZERO -#define SL_SOCKET_FD_SET SL_FD_SET -#define SL_SOCKET_FD_ISSET SL_FD_ISSET -#define SL_SO_SECURE_DOMAIN_NAME_VERIFICATION SO_SECURE_DOMAIN_NAME_VERIFICATION - -#define SL_FS_READ FS_MODE_OPEN_READ -#define SL_FS_WRITE FS_MODE_OPEN_WRITE - -#define SL_FI_FILE_SIZE(fi) ((fi).FileLen) -#define SL_FI_FILE_MAX_SIZE(fi) ((fi).AllocatedLen) - -#define SlDeviceVersion_t SlVersionFull -#define sl_DeviceGet sl_DevGet -#define SL_DEVICE_GENERAL SL_DEVICE_GENERAL_CONFIGURATION -#define SL_LEN_TYPE _u8 -#define SL_OPT_TYPE _u8 - -#else /* SL_MAJOR_VERSION_NUM >= 2 */ - -#define FS_MODE_OPEN_CREATE(max_size, flag) \ - (SL_FS_CREATE | SL_FS_CREATE_MAX_SIZE(max_size)) -#define SL_FI_FILE_SIZE(fi) ((fi).Len) -#define SL_FI_FILE_MAX_SIZE(fi) ((fi).MaxSize) - -#define SL_LEN_TYPE _u16 -#define SL_OPT_TYPE _u16 - -#endif /* SL_MAJOR_VERSION_NUM < 2 */ - -int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token); - -#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */ - -#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_wince.h" -#endif -#ifndef CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_ - -#if CS_PLATFORM == CS_P_WINCE - -/* - * MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) - * MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013) - * MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012) - * MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010) - * MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008) - * MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005) - * MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio 2003) - * MSVC++ 7.0 _MSC_VER == 1300 - * MSVC++ 6.0 _MSC_VER == 1200 - * MSVC++ 5.0 _MSC_VER == 1100 - */ -#pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */ -#pragma warning(disable : 4204) /* missing c99 support */ - -#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS -#define _WINSOCK_DEPRECATED_NO_WARNINGS 1 -#endif - -#ifndef _CRT_SECURE_NO_WARNINGS -#define _CRT_SECURE_NO_WARNINGS -#endif - -#include -#include -#include -#include -#include -#include - -#pragma comment(lib, "ws2.lib") /* Linking with WinCE winsock library */ - -#include -#include -#include - -#define strdup _strdup - -#ifndef EINPROGRESS -#define EINPROGRESS WSAEINPROGRESS -#endif - -#ifndef EWOULDBLOCK -#define EWOULDBLOCK WSAEWOULDBLOCK -#endif - -#ifndef EAGAIN -#define EAGAIN EWOULDBLOCK -#endif - -#ifndef __func__ -#define STRX(x) #x -#define STR(x) STRX(x) -#define __func__ __FILE__ ":" STR(__LINE__) -#endif - -#define snprintf _snprintf -#define fileno _fileno -#define vsnprintf _vsnprintf -#define sleep(x) Sleep((x) *1000) -#define to64(x) _atoi64(x) -#define rmdir _rmdir - -#if defined(_MSC_VER) && _MSC_VER >= 1400 -#define fseeko(x, y, z) _fseeki64((x), (y), (z)) -#else -#define fseeko(x, y, z) fseek((x), (y), (z)) -#endif - -typedef int socklen_t; - -#if _MSC_VER >= 1700 -#include -#else -typedef signed char int8_t; -typedef unsigned char uint8_t; -typedef int int32_t; -typedef unsigned int uint32_t; -typedef short int16_t; -typedef unsigned short uint16_t; -typedef __int64 int64_t; -typedef unsigned __int64 uint64_t; -#endif - -typedef SOCKET sock_t; -typedef uint32_t in_addr_t; - -#ifndef UINT16_MAX -#define UINT16_MAX 65535 -#endif - -#ifndef UINT32_MAX -#define UINT32_MAX 4294967295 -#endif - -#ifndef pid_t -#define pid_t HANDLE -#endif - -#define INT64_FMT "I64d" -#define INT64_X_FMT "I64x" -/* TODO(alashkin): check if this is correct */ -#define SIZE_T_FMT "u" - -#define DIRSEP '\\' -#define CS_DEFINE_DIRENT - -#ifndef va_copy -#ifdef __va_copy -#define va_copy __va_copy -#else -#define va_copy(x, y) (x) = (y) -#endif -#endif - -#ifndef MG_MAX_HTTP_REQUEST_SIZE -#define MG_MAX_HTTP_REQUEST_SIZE 8192 -#endif - -#ifndef MG_MAX_HTTP_SEND_MBUF -#define MG_MAX_HTTP_SEND_MBUF 4096 -#endif - -#ifndef MG_MAX_HTTP_HEADERS -#define MG_MAX_HTTP_HEADERS 40 -#endif - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#define abort() DebugBreak(); - -#ifndef BUFSIZ -#define BUFSIZ 4096 -#endif -/* - * Explicitly disabling MG_ENABLE_THREADS for WinCE - * because they are enabled for _WIN32 by default - */ -#ifndef MG_ENABLE_THREADS -#define MG_ENABLE_THREADS 0 -#endif - -#ifndef MG_ENABLE_FILESYSTEM -#define MG_ENABLE_FILESYSTEM 1 -#endif - -#ifndef MG_NET_IF -#define MG_NET_IF MG_NET_IF_SOCKET -#endif - -typedef struct _stati64 { - uint32_t st_mtime; - uint32_t st_size; - uint32_t st_mode; -} cs_stat_t; - -/* - * WinCE 6.0 has a lot of useful definitions in ATL (not windows.h) headers - * use #ifdefs to avoid conflicts - */ - -#ifndef ENOENT -#define ENOENT ERROR_PATH_NOT_FOUND -#endif - -#ifndef EACCES -#define EACCES ERROR_ACCESS_DENIED -#endif - -#ifndef ENOMEM -#define ENOMEM ERROR_NOT_ENOUGH_MEMORY -#endif - -#ifndef _UINTPTR_T_DEFINED -typedef unsigned int *uintptr_t; -#endif - -#define _S_IFREG 2 -#define _S_IFDIR 4 - -#ifndef S_ISDIR -#define S_ISDIR(x) (((x) &_S_IFDIR) != 0) -#endif - -#ifndef S_ISREG -#define S_ISREG(x) (((x) &_S_IFREG) != 0) -#endif - -int open(const char *filename, int oflag, int pmode); -int _wstati64(const wchar_t *path, cs_stat_t *st); -const char *strerror(); - -#endif /* CS_PLATFORM == CS_P_WINCE */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_nxp_lpc.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_ - -#if CS_PLATFORM == CS_P_NXP_LPC - -#include -#include -#include - -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define INT64_FMT "lld" -#define INT64_X_FMT "llx" -#define __cdecl - -#define MG_LWIP 1 - -#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL - -/* - * LPCXpress comes with 3 C library implementations: Newlib, NewlibNano and - *Redlib. - * See https://community.nxp.com/message/630860 for more details. - * - * Redlib is the default and lacks certain things, so we provide them. - */ -#ifdef __REDLIB_INTERFACE_VERSION__ - -/* Let LWIP define timeval for us. */ -#define LWIP_TIMEVAL_PRIVATE 1 - -#define va_copy(d, s) __builtin_va_copy(d, s) - -#define CS_ENABLE_TO64 1 -#define to64(x) cs_to64(x) - -#define CS_ENABLE_STRDUP 1 - -#else - -#include -#define LWIP_TIMEVAL_PRIVATE 0 -#define to64(x) strtoll(x, NULL, 10) - -#endif - -#endif /* CS_PLATFORM == CS_P_NXP_LPC */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_nxp_kinetis.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_ - -#if CS_PLATFORM == CS_P_NXP_KINETIS - -#include -#include -#include -#include - -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT "lld" -#define INT64_X_FMT "llx" -#define __cdecl - -#define MG_LWIP 1 - -#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL - -/* struct timeval is defined in sys/time.h. */ -#define LWIP_TIMEVAL_PRIVATE 0 - -#endif /* CS_PLATFORM == CS_P_NXP_KINETIS */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_pic32.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_ - -#if CS_PLATFORM == CS_P_PIC32 - -#define MG_NET_IF MG_NET_IF_PIC32 - -#include -#include -#include -#include - -#include -#include - -#include - -typedef TCP_SOCKET sock_t; -#define to64(x) strtoll(x, NULL, 10) - -#define SIZE_T_FMT "lu" -#define INT64_FMT "lld" - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -char *inet_ntoa(struct in_addr in); - -#endif /* CS_PLATFORM == CS_P_PIC32 */ - -#endif /* CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_stm32.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_STM32_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_STM32_H_ -#if CS_PLATFORM == CS_P_STM32 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT "lld" -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define DIRSEP '/' - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#ifndef MG_ENABLE_FILESYSTEM -#define MG_ENABLE_FILESYSTEM 1 -#endif - -#endif /* CS_PLATFORM == CS_P_STM32 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_STM32_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/lwip/mg_lwip.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_ -#define CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_ - -#ifndef MG_LWIP -#define MG_LWIP 0 -#endif - -#if MG_LWIP - -/* - * When compiling for nRF5x chips with arm-none-eabi-gcc, it has BYTE_ORDER - * already defined, so in order to avoid warnings in lwip, we have to undefine - * it. - * - * TODO: Check if in the future versions of nRF5 SDK that changes. - * Current version of nRF51 SDK: 0.8.0 - * nRF5 SDK: 0.9.0 - */ -#if CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52 -#undef BYTE_ORDER -#endif - -#include -#include -#include -#include -#include -#include - -#ifndef LWIP_PROVIDE_ERRNO -#include -#endif - -#if LWIP_SOCKET -#include -#else -/* We really need the definitions from sockets.h. */ -#undef LWIP_SOCKET -#define LWIP_SOCKET 1 -#include -#undef LWIP_SOCKET -#define LWIP_SOCKET 0 -#endif - -#define INVALID_SOCKET (-1) -#define SOMAXCONN 10 -typedef int sock_t; - -#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL -struct mg_mgr; -struct mg_connection; -void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle, - int interval, int count); -#endif - -/* For older version of LWIP */ -#ifndef ipX_2_ip -#define ipX_2_ip(x) (x) -#endif - -#endif /* MG_LWIP */ - -#endif /* CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/cs_md5.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_MD5_H_ -#define CS_COMMON_MD5_H_ - -/* Amalgamated: #include "common/platform.h" */ - -#ifndef CS_DISABLE_MD5 -#define CS_DISABLE_MD5 0 -#endif - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -typedef struct { - uint32_t buf[4]; - uint32_t bits[2]; - unsigned char in[64]; -} cs_md5_ctx; - -void cs_md5_init(cs_md5_ctx *c); -void cs_md5_update(cs_md5_ctx *c, const unsigned char *data, size_t len); -void cs_md5_final(unsigned char *md, cs_md5_ctx *c); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_COMMON_MD5_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/cs_sha1.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_SHA1_H_ -#define CS_COMMON_SHA1_H_ - -#ifndef CS_DISABLE_SHA1 -#define CS_DISABLE_SHA1 0 -#endif - -#if !CS_DISABLE_SHA1 - -/* Amalgamated: #include "common/platform.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -typedef struct { - uint32_t state[5]; - uint32_t count[2]; - unsigned char buffer[64]; -} cs_sha1_ctx; - -void cs_sha1_init(cs_sha1_ctx *); -void cs_sha1_update(cs_sha1_ctx *, const unsigned char *data, uint32_t len); -void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *); -void cs_hmac_sha1(const unsigned char *key, size_t key_len, - const unsigned char *text, size_t text_len, - unsigned char out[20]); -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_DISABLE_SHA1 */ - -#endif /* CS_COMMON_SHA1_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/cs_time.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_CS_TIME_H_ -#define CS_COMMON_CS_TIME_H_ - -#include - -/* Amalgamated: #include "common/platform.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* Sub-second granularity time(). */ -double cs_time(void); - -/* - * Similar to (non-standard) timegm, converts broken-down time into the number - * of seconds since Unix Epoch. - */ -double cs_timegm(const struct tm *tm); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_COMMON_CS_TIME_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/mg_str.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_MG_STR_H_ -#define CS_COMMON_MG_STR_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* Describes chunk of memory */ -struct mg_str { - const char *p; /* Memory chunk pointer */ - size_t len; /* Memory chunk length */ -}; - -/* - * Helper function for creating mg_str struct from plain C string. - * `NULL` is allowed and becomes `{NULL, 0}`. - */ -struct mg_str mg_mk_str(const char *s); - -/* - * Like `mg_mk_str`, but takes string length explicitly. - */ -struct mg_str mg_mk_str_n(const char *s, size_t len); - -/* Macro for initializing mg_str. */ -#define MG_MK_STR(str_literal) \ - { str_literal, sizeof(str_literal) - 1 } -#define MG_MK_STR_N(str_literal, len) \ - { str_literal, len } -#define MG_NULL_STR \ - { NULL, 0 } - -/* - * Cross-platform version of `strcmp()` where where first string is - * specified by `struct mg_str`. - */ -int mg_vcmp(const struct mg_str *str2, const char *str1); - -/* - * Cross-platform version of `strncasecmp()` where first string is - * specified by `struct mg_str`. - */ -int mg_vcasecmp(const struct mg_str *str2, const char *str1); - -/* Creates a copy of s (heap-allocated). */ -struct mg_str mg_strdup(const struct mg_str s); - -/* - * Creates a copy of s (heap-allocated). - * Resulting string is NUL-terminated (but NUL is not included in len). - */ -struct mg_str mg_strdup_nul(const struct mg_str s); - -/* - * Locates character in a string. - */ -const char *mg_strchr(const struct mg_str s, int c); - -/* - * Compare two `mg_str`s; return value is the same as `strcmp`. - */ -int mg_strcmp(const struct mg_str str1, const struct mg_str str2); - -/* - * Like `mg_strcmp`, but compares at most `n` characters. - */ -int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n); - -/* - * Free the string (assuming it was heap allocated). - */ -void mg_strfree(struct mg_str *s); - -/* - * Finds the first occurrence of a substring `needle` in the `haystack`. - */ -const char *mg_strstr(const struct mg_str haystack, const struct mg_str needle); - -/* Strip whitespace at the start and the end of s */ -struct mg_str mg_strstrip(struct mg_str s); - -/* Returns 1 if s starts with the given prefix. */ -int mg_str_starts_with(struct mg_str s, struct mg_str prefix); - -#ifdef __cplusplus -} -#endif - -#endif /* CS_COMMON_MG_STR_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/mbuf.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Mbufs are mutable/growing memory buffers, like C++ strings. - * Mbuf can append data to the end of a buffer or insert data into arbitrary - * position in the middle of a buffer. The buffer grows automatically when - * needed. - */ - -#ifndef CS_COMMON_MBUF_H_ -#define CS_COMMON_MBUF_H_ - -#include -/* Amalgamated: #include "common/platform.h" */ - -#if defined(__cplusplus) -extern "C" { -#endif - -#ifndef MBUF_SIZE_MULTIPLIER -#define MBUF_SIZE_MULTIPLIER 1.5 -#endif - -#ifndef MBUF_SIZE_MAX_HEADROOM -#ifdef BUFSIZ -#define MBUF_SIZE_MAX_HEADROOM BUFSIZ -#else -#define MBUF_SIZE_MAX_HEADROOM 1024 -#endif -#endif - -/* Memory buffer descriptor */ -struct mbuf { - char *buf; /* Buffer pointer */ - size_t len; /* Data length. Data is located between offset 0 and len. */ - size_t size; /* Buffer size allocated by realloc(1). Must be >= len */ -}; - -/* - * Initialises an Mbuf. - * `initial_capacity` specifies the initial capacity of the mbuf. - */ -void mbuf_init(struct mbuf *, size_t initial_capacity); - -/* Frees the space allocated for the mbuffer and resets the mbuf structure. */ -void mbuf_free(struct mbuf *); - -/* - * Appends data to the Mbuf. - * - * Returns the number of bytes appended or 0 if out of memory. - */ -size_t mbuf_append(struct mbuf *, const void *data, size_t data_size); - -/* - * Appends data to the Mbuf and frees it (data must be heap-allocated). - * - * Returns the number of bytes appended or 0 if out of memory. - * data is freed irrespective of return value. - */ -size_t mbuf_append_and_free(struct mbuf *, void *data, size_t data_size); - -/* - * Inserts data at a specified offset in the Mbuf. - * - * Existing data will be shifted forwards and the buffer will - * be grown if necessary. - * Returns the number of bytes inserted. - */ -size_t mbuf_insert(struct mbuf *, size_t, const void *, size_t); - -/* Removes `data_size` bytes from the beginning of the buffer. */ -void mbuf_remove(struct mbuf *, size_t data_size); - -/* - * Resizes an Mbuf. - * - * If `new_size` is smaller than buffer's `len`, the - * resize is not performed. - */ -void mbuf_resize(struct mbuf *, size_t new_size); - -/* Moves the state from one mbuf to the other. */ -void mbuf_move(struct mbuf *from, struct mbuf *to); - -/* Removes all the data from mbuf (if any). */ -void mbuf_clear(struct mbuf *); - -/* Shrinks an Mbuf by resizing its `size` to `len`. */ -void mbuf_trim(struct mbuf *); - -#if defined(__cplusplus) -} -#endif /* __cplusplus */ - -#endif /* CS_COMMON_MBUF_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/cs_base64.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_CS_BASE64_H_ -#define CS_COMMON_CS_BASE64_H_ - -#ifndef DISABLE_BASE64 -#define DISABLE_BASE64 0 -#endif - -#if !DISABLE_BASE64 - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void (*cs_base64_putc_t)(char, void *); - -struct cs_base64_ctx { - /* cannot call it putc because it's a macro on some environments */ - cs_base64_putc_t b64_putc; - unsigned char chunk[3]; - int chunk_size; - void *user_data; -}; - -void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t putc, - void *user_data); -void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len); -void cs_base64_finish(struct cs_base64_ctx *ctx); - -void cs_base64_encode(const unsigned char *src, int src_len, char *dst); -void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len); - -/* - * Decodes a base64 string `s` length `len` into `dst`. - * `dst` must have enough space to hold the result. - * `*dec_len` will contain the resulting length of the string in `dst` - * while return value will return number of processed bytes in `src`. - * Return value == len indicates successful processing of all the data. - */ -int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len); - -#ifdef __cplusplus -} -#endif - -#endif /* DISABLE_BASE64 */ - -#endif /* CS_COMMON_CS_BASE64_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/str_util.h" -#endif -/* - * Copyright (c) 2014-2018 Cesanta Software Limited - * All rights reserved - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CS_COMMON_STR_UTIL_H_ -#define CS_COMMON_STR_UTIL_H_ - -#include -#include - -/* Amalgamated: #include "common/mg_str.h" */ -/* Amalgamated: #include "common/platform.h" */ - -#ifndef CS_ENABLE_STRDUP -#define CS_ENABLE_STRDUP 0 -#endif - -#ifndef CS_ENABLE_TO64 -#define CS_ENABLE_TO64 0 -#endif - -/* - * Expands to a string representation of its argument: e.g. - * `CS_STRINGIFY_LIT(5) expands to "5"` - */ -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -#define CS_STRINGIFY_LIT(...) #__VA_ARGS__ -#else -#define CS_STRINGIFY_LIT(x) #x -#endif - -/* - * Expands to a string representation of its argument, which is allowed - * to be a macro: e.g. - * - * #define FOO 123 - * CS_STRINGIFY_MACRO(FOO) - * - * expands to 123. - */ -#define CS_STRINGIFY_MACRO(x) CS_STRINGIFY_LIT(x) - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Equivalent of standard `strnlen()`. - */ -size_t c_strnlen(const char *s, size_t maxlen); - -/* - * Equivalent of standard `snprintf()`. - */ -int c_snprintf(char *buf, size_t buf_size, const char *format, ...) - PRINTF_LIKE(3, 4); - -/* - * Equivalent of standard `vsnprintf()`. - */ -int c_vsnprintf(char *buf, size_t buf_size, const char *format, va_list ap); - -/* - * Find the first occurrence of find in s, where the search is limited to the - * first slen characters of s. - */ -const char *c_strnstr(const char *s, const char *find, size_t slen); - -/* - * Stringify binary data. Output buffer size must be 2 * size_of_input + 1 - * because each byte of input takes 2 bytes in string representation - * plus 1 byte for the terminating \0 character. - */ -void cs_to_hex(char *to, const unsigned char *p, size_t len); - -/* - * Convert stringified binary data back to binary. - * Does the reverse of `cs_to_hex()`. - */ -void cs_from_hex(char *to, const char *p, size_t len); - -#if CS_ENABLE_STRDUP -/* - * Equivalent of standard `strdup()`, defined if only `CS_ENABLE_STRDUP` is 1. - */ -char *strdup(const char *src); -#endif - -#if CS_ENABLE_TO64 -#include -/* - * Simple string -> int64 conversion routine. - */ -int64_t cs_to64(const char *s); -#endif - -/* - * Cross-platform version of `strncasecmp()`. - */ -int mg_ncasecmp(const char *s1, const char *s2, size_t len); - -/* - * Cross-platform version of `strcasecmp()`. - */ -int mg_casecmp(const char *s1, const char *s2); - -/* - * Prints message to the buffer. If the buffer is large enough to hold the - * message, it returns buffer. If buffer is to small, it allocates a large - * enough buffer on heap and returns allocated buffer. - * This is a supposed use case: - * - * ```c - * char buf[5], *p = buf; - * mg_avprintf(&p, sizeof(buf), "%s", "hi there"); - * use_p_somehow(p); - * if (p != buf) { - * free(p); - * } - * ``` - * - * The purpose of this is to avoid malloc-ing if generated strings are small. - */ -int mg_asprintf(char **buf, size_t size, const char *fmt, ...) - PRINTF_LIKE(3, 4); - -/* Same as mg_asprintf, but takes varargs list. */ -int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap); - -/* - * A helper function for traversing a comma separated list of values. - * It returns a list pointer shifted to the next value or NULL if the end - * of the list found. - * The value is stored in a val vector. If the value has a form "x=y", then - * eq_val vector is initialised to point to the "y" part, and val vector length - * is adjusted to point only to "x". - * If the list is just a comma separated list of entries, like "aa,bb,cc" then - * `eq_val` will contain zero-length string. - * - * The purpose of this function is to parse comma separated string without - * any copying/memory allocation. - */ -const char *mg_next_comma_list_entry(const char *list, struct mg_str *val, - struct mg_str *eq_val); - -/* - * Like `mg_next_comma_list_entry()`, but takes `list` as `struct mg_str`. - * NB: Test return value's .p, not .len. On last itreation that yields result - * .len will be 0 but .p will not. When finished, .p will be NULL. - */ -struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val, - struct mg_str *eq_val); - -/* - * Matches 0-terminated string (mg_match_prefix) or string with given length - * mg_match_prefix_n against a glob pattern. Glob syntax: - * ``` - * - * matches zero or more characters until a slash character / - * - ** matches zero or more characters - * - ? Matches exactly one character which is not a slash / - * - | or , divides alternative patterns - * - any other character matches itself - * ``` - * Match is case-insensitive. Return number of bytes matched. - * Examples: - * ``` - * mg_match_prefix("a*f", len, "abcdefgh") == 6 - * mg_match_prefix("a*f", len, "abcdexgh") == 0 - * mg_match_prefix("a*f|de*,xy", len, "defgh") == 5 - * mg_match_prefix("?*", len, "abc") == 3 - * mg_match_prefix("?*", len, "") == 0 - * ``` - */ -size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str); - -/* - * Like `mg_match_prefix()`, but takes `pattern` and `str` as `struct mg_str`. - */ -size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str); - -#ifdef __cplusplus -} -#endif - -#endif /* CS_COMMON_STR_UTIL_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/queue.h" -#endif -/* clang-format off */ -/*- - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)queue.h 8.5 (Berkeley) 8/20/94 - * $FreeBSD$ - */ - -#ifndef _SYS_QUEUE_H_ -#define _SYS_QUEUE_H_ - -/* - * This file defines four types of data structures: singly-linked lists, - * singly-linked tail queues, lists and tail queues. - * - * A singly-linked list is headed by a single forward pointer. The elements - * are singly linked for minimum space and pointer manipulation overhead at - * the expense of O(n) removal for arbitrary elements. New elements can be - * added to the list after an existing element or at the head of the list. - * Elements being removed from the head of the list should use the explicit - * macro for this purpose for optimum efficiency. A singly-linked list may - * only be traversed in the forward direction. Singly-linked lists are ideal - * for applications with large datasets and few or no removals or for - * implementing a LIFO queue. - * - * A singly-linked tail queue is headed by a pair of pointers, one to the - * head of the list and the other to the tail of the list. The elements are - * singly linked for minimum space and pointer manipulation overhead at the - * expense of O(n) removal for arbitrary elements. New elements can be added - * to the list after an existing element, at the head of the list, or at the - * end of the list. Elements being removed from the head of the tail queue - * should use the explicit macro for this purpose for optimum efficiency. - * A singly-linked tail queue may only be traversed in the forward direction. - * Singly-linked tail queues are ideal for applications with large datasets - * and few or no removals or for implementing a FIFO queue. - * - * A list is headed by a single forward pointer (or an array of forward - * pointers for a hash table header). The elements are doubly linked - * so that an arbitrary element can be removed without a need to - * traverse the list. New elements can be added to the list before - * or after an existing element or at the head of the list. A list - * may be traversed in either direction. - * - * A tail queue is headed by a pair of pointers, one to the head of the - * list and the other to the tail of the list. The elements are doubly - * linked so that an arbitrary element can be removed without a need to - * traverse the list. New elements can be added to the list before or - * after an existing element, at the head of the list, or at the end of - * the list. A tail queue may be traversed in either direction. - * - * For details on the use of these macros, see the queue(3) manual page. - * - * - * SLIST LIST STAILQ TAILQ - * _HEAD + + + + - * _CLASS_HEAD + + + + - * _HEAD_INITIALIZER + + + + - * _ENTRY + + + + - * _CLASS_ENTRY + + + + - * _INIT + + + + - * _EMPTY + + + + - * _FIRST + + + + - * _NEXT + + + + - * _PREV - + - + - * _LAST - - + + - * _FOREACH + + + + - * _FOREACH_FROM + + + + - * _FOREACH_SAFE + + + + - * _FOREACH_FROM_SAFE + + + + - * _FOREACH_REVERSE - - - + - * _FOREACH_REVERSE_FROM - - - + - * _FOREACH_REVERSE_SAFE - - - + - * _FOREACH_REVERSE_FROM_SAFE - - - + - * _INSERT_HEAD + + + + - * _INSERT_BEFORE - + - + - * _INSERT_AFTER + + + + - * _INSERT_TAIL - - + + - * _CONCAT - - + + - * _REMOVE_AFTER + - + - - * _REMOVE_HEAD + - + - - * _REMOVE + + + + - * _SWAP + + + + - * - */ -#ifdef QUEUE_MACRO_DEBUG -/* Store the last 2 places the queue element or head was altered */ -struct qm_trace { - unsigned long lastline; - unsigned long prevline; - const char *lastfile; - const char *prevfile; -}; - -#define TRACEBUF struct qm_trace trace; -#define TRACEBUF_INITIALIZER { __LINE__, 0, __FILE__, NULL } , -#define TRASHIT(x) do {(x) = (void *)-1;} while (0) -#define QMD_SAVELINK(name, link) void **name = (void *)&(link) - -#define QMD_TRACE_HEAD(head) do { \ - (head)->trace.prevline = (head)->trace.lastline; \ - (head)->trace.prevfile = (head)->trace.lastfile; \ - (head)->trace.lastline = __LINE__; \ - (head)->trace.lastfile = __FILE__; \ -} while (0) - -#define QMD_TRACE_ELEM(elem) do { \ - (elem)->trace.prevline = (elem)->trace.lastline; \ - (elem)->trace.prevfile = (elem)->trace.lastfile; \ - (elem)->trace.lastline = __LINE__; \ - (elem)->trace.lastfile = __FILE__; \ -} while (0) - -#else -#define QMD_TRACE_ELEM(elem) -#define QMD_TRACE_HEAD(head) -#define QMD_SAVELINK(name, link) -#define TRACEBUF -#define TRACEBUF_INITIALIZER -#define TRASHIT(x) -#endif /* QUEUE_MACRO_DEBUG */ - -#ifdef __cplusplus -/* - * In C++ there can be structure lists and class lists: - */ -#define QUEUE_TYPEOF(type) type -#else -#define QUEUE_TYPEOF(type) struct type -#endif - -/* - * Singly-linked List declarations. - */ -#define SLIST_HEAD(name, type) \ -struct name { \ - struct type *slh_first; /* first element */ \ -} - -#define SLIST_CLASS_HEAD(name, type) \ -struct name { \ - class type *slh_first; /* first element */ \ -} - -#define SLIST_HEAD_INITIALIZER(head) \ - { NULL } - -#define SLIST_ENTRY(type) \ -struct { \ - struct type *sle_next; /* next element */ \ -} - -#define SLIST_CLASS_ENTRY(type) \ -struct { \ - class type *sle_next; /* next element */ \ -} - -/* - * Singly-linked List functions. - */ -#define SLIST_EMPTY(head) ((head)->slh_first == NULL) - -#define SLIST_FIRST(head) ((head)->slh_first) - -#define SLIST_FOREACH(var, head, field) \ - for ((var) = SLIST_FIRST((head)); \ - (var); \ - (var) = SLIST_NEXT((var), field)) - -#define SLIST_FOREACH_FROM(var, head, field) \ - for ((var) = ((var) ? (var) : SLIST_FIRST((head))); \ - (var); \ - (var) = SLIST_NEXT((var), field)) - -#define SLIST_FOREACH_SAFE(var, head, field, tvar) \ - for ((var) = SLIST_FIRST((head)); \ - (var) && ((tvar) = SLIST_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define SLIST_FOREACH_FROM_SAFE(var, head, field, tvar) \ - for ((var) = ((var) ? (var) : SLIST_FIRST((head))); \ - (var) && ((tvar) = SLIST_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define SLIST_FOREACH_PREVPTR(var, varp, head, field) \ - for ((varp) = &SLIST_FIRST((head)); \ - ((var) = *(varp)) != NULL; \ - (varp) = &SLIST_NEXT((var), field)) - -#define SLIST_INIT(head) do { \ - SLIST_FIRST((head)) = NULL; \ -} while (0) - -#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ - SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field); \ - SLIST_NEXT((slistelm), field) = (elm); \ -} while (0) - -#define SLIST_INSERT_HEAD(head, elm, field) do { \ - SLIST_NEXT((elm), field) = SLIST_FIRST((head)); \ - SLIST_FIRST((head)) = (elm); \ -} while (0) - -#define SLIST_NEXT(elm, field) ((elm)->field.sle_next) - -#define SLIST_REMOVE(head, elm, type, field) do { \ - QMD_SAVELINK(oldnext, (elm)->field.sle_next); \ - if (SLIST_FIRST((head)) == (elm)) { \ - SLIST_REMOVE_HEAD((head), field); \ - } \ - else { \ - QUEUE_TYPEOF(type) *curelm = SLIST_FIRST(head); \ - while (SLIST_NEXT(curelm, field) != (elm)) \ - curelm = SLIST_NEXT(curelm, field); \ - SLIST_REMOVE_AFTER(curelm, field); \ - } \ - TRASHIT(*oldnext); \ -} while (0) - -#define SLIST_REMOVE_AFTER(elm, field) do { \ - SLIST_NEXT(elm, field) = \ - SLIST_NEXT(SLIST_NEXT(elm, field), field); \ -} while (0) - -#define SLIST_REMOVE_HEAD(head, field) do { \ - SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field); \ -} while (0) - -#define SLIST_SWAP(head1, head2, type) do { \ - QUEUE_TYPEOF(type) *swap_first = SLIST_FIRST(head1); \ - SLIST_FIRST(head1) = SLIST_FIRST(head2); \ - SLIST_FIRST(head2) = swap_first; \ -} while (0) - -/* - * Singly-linked Tail queue declarations. - */ -#define STAILQ_HEAD(name, type) \ -struct name { \ - struct type *stqh_first;/* first element */ \ - struct type **stqh_last;/* addr of last next element */ \ -} - -#define STAILQ_CLASS_HEAD(name, type) \ -struct name { \ - class type *stqh_first; /* first element */ \ - class type **stqh_last; /* addr of last next element */ \ -} - -#define STAILQ_HEAD_INITIALIZER(head) \ - { NULL, &(head).stqh_first } - -#define STAILQ_ENTRY(type) \ -struct { \ - struct type *stqe_next; /* next element */ \ -} - -#define STAILQ_CLASS_ENTRY(type) \ -struct { \ - class type *stqe_next; /* next element */ \ -} - -/* - * Singly-linked Tail queue functions. - */ -#define STAILQ_CONCAT(head1, head2) do { \ - if (!STAILQ_EMPTY((head2))) { \ - *(head1)->stqh_last = (head2)->stqh_first; \ - (head1)->stqh_last = (head2)->stqh_last; \ - STAILQ_INIT((head2)); \ - } \ -} while (0) - -#define STAILQ_EMPTY(head) ((head)->stqh_first == NULL) - -#define STAILQ_FIRST(head) ((head)->stqh_first) - -#define STAILQ_FOREACH(var, head, field) \ - for((var) = STAILQ_FIRST((head)); \ - (var); \ - (var) = STAILQ_NEXT((var), field)) - -#define STAILQ_FOREACH_FROM(var, head, field) \ - for ((var) = ((var) ? (var) : STAILQ_FIRST((head))); \ - (var); \ - (var) = STAILQ_NEXT((var), field)) - -#define STAILQ_FOREACH_SAFE(var, head, field, tvar) \ - for ((var) = STAILQ_FIRST((head)); \ - (var) && ((tvar) = STAILQ_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define STAILQ_FOREACH_FROM_SAFE(var, head, field, tvar) \ - for ((var) = ((var) ? (var) : STAILQ_FIRST((head))); \ - (var) && ((tvar) = STAILQ_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define STAILQ_INIT(head) do { \ - STAILQ_FIRST((head)) = NULL; \ - (head)->stqh_last = &STAILQ_FIRST((head)); \ -} while (0) - -#define STAILQ_INSERT_AFTER(head, tqelm, elm, field) do { \ - if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\ - (head)->stqh_last = &STAILQ_NEXT((elm), field); \ - STAILQ_NEXT((tqelm), field) = (elm); \ -} while (0) - -#define STAILQ_INSERT_HEAD(head, elm, field) do { \ - if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL) \ - (head)->stqh_last = &STAILQ_NEXT((elm), field); \ - STAILQ_FIRST((head)) = (elm); \ -} while (0) - -#define STAILQ_INSERT_TAIL(head, elm, field) do { \ - STAILQ_NEXT((elm), field) = NULL; \ - *(head)->stqh_last = (elm); \ - (head)->stqh_last = &STAILQ_NEXT((elm), field); \ -} while (0) - -#define STAILQ_LAST(head, type, field) \ - (STAILQ_EMPTY((head)) ? NULL : \ - __containerof((head)->stqh_last, \ - QUEUE_TYPEOF(type), field.stqe_next)) - -#define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next) - -#define STAILQ_REMOVE(head, elm, type, field) do { \ - QMD_SAVELINK(oldnext, (elm)->field.stqe_next); \ - if (STAILQ_FIRST((head)) == (elm)) { \ - STAILQ_REMOVE_HEAD((head), field); \ - } \ - else { \ - QUEUE_TYPEOF(type) *curelm = STAILQ_FIRST(head); \ - while (STAILQ_NEXT(curelm, field) != (elm)) \ - curelm = STAILQ_NEXT(curelm, field); \ - STAILQ_REMOVE_AFTER(head, curelm, field); \ - } \ - TRASHIT(*oldnext); \ -} while (0) - -#define STAILQ_REMOVE_AFTER(head, elm, field) do { \ - if ((STAILQ_NEXT(elm, field) = \ - STAILQ_NEXT(STAILQ_NEXT(elm, field), field)) == NULL) \ - (head)->stqh_last = &STAILQ_NEXT((elm), field); \ -} while (0) - -#define STAILQ_REMOVE_HEAD(head, field) do { \ - if ((STAILQ_FIRST((head)) = \ - STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL) \ - (head)->stqh_last = &STAILQ_FIRST((head)); \ -} while (0) - -#define STAILQ_SWAP(head1, head2, type) do { \ - QUEUE_TYPEOF(type) *swap_first = STAILQ_FIRST(head1); \ - QUEUE_TYPEOF(type) **swap_last = (head1)->stqh_last; \ - STAILQ_FIRST(head1) = STAILQ_FIRST(head2); \ - (head1)->stqh_last = (head2)->stqh_last; \ - STAILQ_FIRST(head2) = swap_first; \ - (head2)->stqh_last = swap_last; \ - if (STAILQ_EMPTY(head1)) \ - (head1)->stqh_last = &STAILQ_FIRST(head1); \ - if (STAILQ_EMPTY(head2)) \ - (head2)->stqh_last = &STAILQ_FIRST(head2); \ -} while (0) - - -/* - * List declarations. - */ -#define LIST_HEAD(name, type) \ -struct name { \ - struct type *lh_first; /* first element */ \ -} - -#define LIST_CLASS_HEAD(name, type) \ -struct name { \ - class type *lh_first; /* first element */ \ -} - -#define LIST_HEAD_INITIALIZER(head) \ - { NULL } - -#define LIST_ENTRY(type) \ -struct { \ - struct type *le_next; /* next element */ \ - struct type **le_prev; /* address of previous next element */ \ -} - -#define LIST_CLASS_ENTRY(type) \ -struct { \ - class type *le_next; /* next element */ \ - class type **le_prev; /* address of previous next element */ \ -} - -/* - * List functions. - */ - -#if (defined(_KERNEL) && defined(INVARIANTS)) -#define QMD_LIST_CHECK_HEAD(head, field) do { \ - if (LIST_FIRST((head)) != NULL && \ - LIST_FIRST((head))->field.le_prev != \ - &LIST_FIRST((head))) \ - panic("Bad list head %p first->prev != head", (head)); \ -} while (0) - -#define QMD_LIST_CHECK_NEXT(elm, field) do { \ - if (LIST_NEXT((elm), field) != NULL && \ - LIST_NEXT((elm), field)->field.le_prev != \ - &((elm)->field.le_next)) \ - panic("Bad link elm %p next->prev != elm", (elm)); \ -} while (0) - -#define QMD_LIST_CHECK_PREV(elm, field) do { \ - if (*(elm)->field.le_prev != (elm)) \ - panic("Bad link elm %p prev->next != elm", (elm)); \ -} while (0) -#else -#define QMD_LIST_CHECK_HEAD(head, field) -#define QMD_LIST_CHECK_NEXT(elm, field) -#define QMD_LIST_CHECK_PREV(elm, field) -#endif /* (_KERNEL && INVARIANTS) */ - -#define LIST_EMPTY(head) ((head)->lh_first == NULL) - -#define LIST_FIRST(head) ((head)->lh_first) - -#define LIST_FOREACH(var, head, field) \ - for ((var) = LIST_FIRST((head)); \ - (var); \ - (var) = LIST_NEXT((var), field)) - -#define LIST_FOREACH_FROM(var, head, field) \ - for ((var) = ((var) ? (var) : LIST_FIRST((head))); \ - (var); \ - (var) = LIST_NEXT((var), field)) - -#define LIST_FOREACH_SAFE(var, head, field, tvar) \ - for ((var) = LIST_FIRST((head)); \ - (var) && ((tvar) = LIST_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define LIST_FOREACH_FROM_SAFE(var, head, field, tvar) \ - for ((var) = ((var) ? (var) : LIST_FIRST((head))); \ - (var) && ((tvar) = LIST_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define LIST_INIT(head) do { \ - LIST_FIRST((head)) = NULL; \ -} while (0) - -#define LIST_INSERT_AFTER(listelm, elm, field) do { \ - QMD_LIST_CHECK_NEXT(listelm, field); \ - if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\ - LIST_NEXT((listelm), field)->field.le_prev = \ - &LIST_NEXT((elm), field); \ - LIST_NEXT((listelm), field) = (elm); \ - (elm)->field.le_prev = &LIST_NEXT((listelm), field); \ -} while (0) - -#define LIST_INSERT_BEFORE(listelm, elm, field) do { \ - QMD_LIST_CHECK_PREV(listelm, field); \ - (elm)->field.le_prev = (listelm)->field.le_prev; \ - LIST_NEXT((elm), field) = (listelm); \ - *(listelm)->field.le_prev = (elm); \ - (listelm)->field.le_prev = &LIST_NEXT((elm), field); \ -} while (0) - -#define LIST_INSERT_HEAD(head, elm, field) do { \ - QMD_LIST_CHECK_HEAD((head), field); \ - if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL) \ - LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\ - LIST_FIRST((head)) = (elm); \ - (elm)->field.le_prev = &LIST_FIRST((head)); \ -} while (0) - -#define LIST_NEXT(elm, field) ((elm)->field.le_next) - -#define LIST_PREV(elm, head, type, field) \ - ((elm)->field.le_prev == &LIST_FIRST((head)) ? NULL : \ - __containerof((elm)->field.le_prev, \ - QUEUE_TYPEOF(type), field.le_next)) - -#define LIST_REMOVE(elm, field) do { \ - QMD_SAVELINK(oldnext, (elm)->field.le_next); \ - QMD_SAVELINK(oldprev, (elm)->field.le_prev); \ - QMD_LIST_CHECK_NEXT(elm, field); \ - QMD_LIST_CHECK_PREV(elm, field); \ - if (LIST_NEXT((elm), field) != NULL) \ - LIST_NEXT((elm), field)->field.le_prev = \ - (elm)->field.le_prev; \ - *(elm)->field.le_prev = LIST_NEXT((elm), field); \ - TRASHIT(*oldnext); \ - TRASHIT(*oldprev); \ -} while (0) - -#define LIST_SWAP(head1, head2, type, field) do { \ - QUEUE_TYPEOF(type) *swap_tmp = LIST_FIRST(head1); \ - LIST_FIRST((head1)) = LIST_FIRST((head2)); \ - LIST_FIRST((head2)) = swap_tmp; \ - if ((swap_tmp = LIST_FIRST((head1))) != NULL) \ - swap_tmp->field.le_prev = &LIST_FIRST((head1)); \ - if ((swap_tmp = LIST_FIRST((head2))) != NULL) \ - swap_tmp->field.le_prev = &LIST_FIRST((head2)); \ -} while (0) - -/* - * Tail queue declarations. - */ -#define TAILQ_HEAD(name, type) \ -struct name { \ - struct type *tqh_first; /* first element */ \ - struct type **tqh_last; /* addr of last next element */ \ - TRACEBUF \ -} - -#define TAILQ_CLASS_HEAD(name, type) \ -struct name { \ - class type *tqh_first; /* first element */ \ - class type **tqh_last; /* addr of last next element */ \ - TRACEBUF \ -} - -#define TAILQ_HEAD_INITIALIZER(head) \ - { NULL, &(head).tqh_first, TRACEBUF_INITIALIZER } - -#define TAILQ_ENTRY(type) \ -struct { \ - struct type *tqe_next; /* next element */ \ - struct type **tqe_prev; /* address of previous next element */ \ - TRACEBUF \ -} - -#define TAILQ_CLASS_ENTRY(type) \ -struct { \ - class type *tqe_next; /* next element */ \ - class type **tqe_prev; /* address of previous next element */ \ - TRACEBUF \ -} - -/* - * Tail queue functions. - */ -#if (defined(_KERNEL) && defined(INVARIANTS)) -#define QMD_TAILQ_CHECK_HEAD(head, field) do { \ - if (!TAILQ_EMPTY(head) && \ - TAILQ_FIRST((head))->field.tqe_prev != \ - &TAILQ_FIRST((head))) \ - panic("Bad tailq head %p first->prev != head", (head)); \ -} while (0) - -#define QMD_TAILQ_CHECK_TAIL(head, field) do { \ - if (*(head)->tqh_last != NULL) \ - panic("Bad tailq NEXT(%p->tqh_last) != NULL", (head)); \ -} while (0) - -#define QMD_TAILQ_CHECK_NEXT(elm, field) do { \ - if (TAILQ_NEXT((elm), field) != NULL && \ - TAILQ_NEXT((elm), field)->field.tqe_prev != \ - &((elm)->field.tqe_next)) \ - panic("Bad link elm %p next->prev != elm", (elm)); \ -} while (0) - -#define QMD_TAILQ_CHECK_PREV(elm, field) do { \ - if (*(elm)->field.tqe_prev != (elm)) \ - panic("Bad link elm %p prev->next != elm", (elm)); \ -} while (0) -#else -#define QMD_TAILQ_CHECK_HEAD(head, field) -#define QMD_TAILQ_CHECK_TAIL(head, headname) -#define QMD_TAILQ_CHECK_NEXT(elm, field) -#define QMD_TAILQ_CHECK_PREV(elm, field) -#endif /* (_KERNEL && INVARIANTS) */ - -#define TAILQ_CONCAT(head1, head2, field) do { \ - if (!TAILQ_EMPTY(head2)) { \ - *(head1)->tqh_last = (head2)->tqh_first; \ - (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ - (head1)->tqh_last = (head2)->tqh_last; \ - TAILQ_INIT((head2)); \ - QMD_TRACE_HEAD(head1); \ - QMD_TRACE_HEAD(head2); \ - } \ -} while (0) - -#define TAILQ_EMPTY(head) ((head)->tqh_first == NULL) - -#define TAILQ_FIRST(head) ((head)->tqh_first) - -#define TAILQ_FOREACH(var, head, field) \ - for ((var) = TAILQ_FIRST((head)); \ - (var); \ - (var) = TAILQ_NEXT((var), field)) - -#define TAILQ_FOREACH_FROM(var, head, field) \ - for ((var) = ((var) ? (var) : TAILQ_FIRST((head))); \ - (var); \ - (var) = TAILQ_NEXT((var), field)) - -#define TAILQ_FOREACH_SAFE(var, head, field, tvar) \ - for ((var) = TAILQ_FIRST((head)); \ - (var) && ((tvar) = TAILQ_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define TAILQ_FOREACH_FROM_SAFE(var, head, field, tvar) \ - for ((var) = ((var) ? (var) : TAILQ_FIRST((head))); \ - (var) && ((tvar) = TAILQ_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ - for ((var) = TAILQ_LAST((head), headname); \ - (var); \ - (var) = TAILQ_PREV((var), headname, field)) - -#define TAILQ_FOREACH_REVERSE_FROM(var, head, headname, field) \ - for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname)); \ - (var); \ - (var) = TAILQ_PREV((var), headname, field)) - -#define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar) \ - for ((var) = TAILQ_LAST((head), headname); \ - (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1); \ - (var) = (tvar)) - -#define TAILQ_FOREACH_REVERSE_FROM_SAFE(var, head, headname, field, tvar) \ - for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname)); \ - (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1); \ - (var) = (tvar)) - -#define TAILQ_INIT(head) do { \ - TAILQ_FIRST((head)) = NULL; \ - (head)->tqh_last = &TAILQ_FIRST((head)); \ - QMD_TRACE_HEAD(head); \ -} while (0) - -#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ - QMD_TAILQ_CHECK_NEXT(listelm, field); \ - if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\ - TAILQ_NEXT((elm), field)->field.tqe_prev = \ - &TAILQ_NEXT((elm), field); \ - else { \ - (head)->tqh_last = &TAILQ_NEXT((elm), field); \ - QMD_TRACE_HEAD(head); \ - } \ - TAILQ_NEXT((listelm), field) = (elm); \ - (elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field); \ - QMD_TRACE_ELEM(&(elm)->field); \ - QMD_TRACE_ELEM(&(listelm)->field); \ -} while (0) - -#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ - QMD_TAILQ_CHECK_PREV(listelm, field); \ - (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ - TAILQ_NEXT((elm), field) = (listelm); \ - *(listelm)->field.tqe_prev = (elm); \ - (listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field); \ - QMD_TRACE_ELEM(&(elm)->field); \ - QMD_TRACE_ELEM(&(listelm)->field); \ -} while (0) - -#define TAILQ_INSERT_HEAD(head, elm, field) do { \ - QMD_TAILQ_CHECK_HEAD(head, field); \ - if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL) \ - TAILQ_FIRST((head))->field.tqe_prev = \ - &TAILQ_NEXT((elm), field); \ - else \ - (head)->tqh_last = &TAILQ_NEXT((elm), field); \ - TAILQ_FIRST((head)) = (elm); \ - (elm)->field.tqe_prev = &TAILQ_FIRST((head)); \ - QMD_TRACE_HEAD(head); \ - QMD_TRACE_ELEM(&(elm)->field); \ -} while (0) - -#define TAILQ_INSERT_TAIL(head, elm, field) do { \ - QMD_TAILQ_CHECK_TAIL(head, field); \ - TAILQ_NEXT((elm), field) = NULL; \ - (elm)->field.tqe_prev = (head)->tqh_last; \ - *(head)->tqh_last = (elm); \ - (head)->tqh_last = &TAILQ_NEXT((elm), field); \ - QMD_TRACE_HEAD(head); \ - QMD_TRACE_ELEM(&(elm)->field); \ -} while (0) - -#define TAILQ_LAST(head, headname) \ - (*(((struct headname *)((head)->tqh_last))->tqh_last)) - -#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) - -#define TAILQ_PREV(elm, headname, field) \ - (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) - -#define TAILQ_REMOVE(head, elm, field) do { \ - QMD_SAVELINK(oldnext, (elm)->field.tqe_next); \ - QMD_SAVELINK(oldprev, (elm)->field.tqe_prev); \ - QMD_TAILQ_CHECK_NEXT(elm, field); \ - QMD_TAILQ_CHECK_PREV(elm, field); \ - if ((TAILQ_NEXT((elm), field)) != NULL) \ - TAILQ_NEXT((elm), field)->field.tqe_prev = \ - (elm)->field.tqe_prev; \ - else { \ - (head)->tqh_last = (elm)->field.tqe_prev; \ - QMD_TRACE_HEAD(head); \ - } \ - *(elm)->field.tqe_prev = TAILQ_NEXT((elm), field); \ - TRASHIT(*oldnext); \ - TRASHIT(*oldprev); \ - QMD_TRACE_ELEM(&(elm)->field); \ -} while (0) - -#define TAILQ_SWAP(head1, head2, type, field) do { \ - QUEUE_TYPEOF(type) *swap_first = (head1)->tqh_first; \ - QUEUE_TYPEOF(type) **swap_last = (head1)->tqh_last; \ - (head1)->tqh_first = (head2)->tqh_first; \ - (head1)->tqh_last = (head2)->tqh_last; \ - (head2)->tqh_first = swap_first; \ - (head2)->tqh_last = swap_last; \ - if ((swap_first = (head1)->tqh_first) != NULL) \ - swap_first->field.tqe_prev = &(head1)->tqh_first; \ - else \ - (head1)->tqh_last = &(head1)->tqh_first; \ - if ((swap_first = (head2)->tqh_first) != NULL) \ - swap_first->field.tqe_prev = &(head2)->tqh_first; \ - else \ - (head2)->tqh_last = &(head2)->tqh_first; \ -} while (0) - -#endif /* !_SYS_QUEUE_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_features.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_MONGOOSE_SRC_FEATURES_H_ -#define CS_MONGOOSE_SRC_FEATURES_H_ - -#ifndef MG_DISABLE_HTTP_DIGEST_AUTH -#define MG_DISABLE_HTTP_DIGEST_AUTH 0 -#endif - -#ifndef MG_DISABLE_HTTP_KEEP_ALIVE -#define MG_DISABLE_HTTP_KEEP_ALIVE 0 -#endif - -#ifndef MG_DISABLE_PFS -#define MG_DISABLE_PFS 0 -#endif - -#ifndef MG_DISABLE_WS_RANDOM_MASK -#define MG_DISABLE_WS_RANDOM_MASK 0 -#endif - -#ifndef MG_ENABLE_ASYNC_RESOLVER -#define MG_ENABLE_ASYNC_RESOLVER 1 -#endif - -#ifndef MG_ENABLE_BROADCAST -#define MG_ENABLE_BROADCAST 0 -#endif - -#ifndef MG_ENABLE_COAP -#define MG_ENABLE_COAP 0 -#endif - -#ifndef MG_ENABLE_DEBUG -#define MG_ENABLE_DEBUG 0 -#endif - -#ifndef MG_ENABLE_DIRECTORY_LISTING -#define MG_ENABLE_DIRECTORY_LISTING 0 -#endif - -#ifndef MG_ENABLE_DNS -#define MG_ENABLE_DNS 1 -#endif - -#ifndef MG_ENABLE_DNS_SERVER -#define MG_ENABLE_DNS_SERVER 0 -#endif - -#ifndef MG_ENABLE_FAKE_DAVLOCK -#define MG_ENABLE_FAKE_DAVLOCK 0 -#endif - -#ifndef MG_ENABLE_FILESYSTEM -#define MG_ENABLE_FILESYSTEM 0 -#endif - -#ifndef MG_ENABLE_GETADDRINFO -#define MG_ENABLE_GETADDRINFO 0 -#endif - -#ifndef MG_ENABLE_HEXDUMP -#define MG_ENABLE_HEXDUMP CS_ENABLE_STDIO -#endif - -#ifndef MG_ENABLE_HTTP -#define MG_ENABLE_HTTP 1 -#endif - -#ifndef MG_ENABLE_HTTP_CGI -#define MG_ENABLE_HTTP_CGI 0 -#endif - -#ifndef MG_ENABLE_HTTP_SSI -#define MG_ENABLE_HTTP_SSI MG_ENABLE_FILESYSTEM -#endif - -#ifndef MG_ENABLE_HTTP_SSI_EXEC -#define MG_ENABLE_HTTP_SSI_EXEC 0 -#endif - -#ifndef MG_ENABLE_HTTP_STREAMING_MULTIPART -#define MG_ENABLE_HTTP_STREAMING_MULTIPART 0 -#endif - -#ifndef MG_ENABLE_HTTP_WEBDAV -#define MG_ENABLE_HTTP_WEBDAV 0 -#endif - -#ifndef MG_ENABLE_HTTP_WEBSOCKET -#define MG_ENABLE_HTTP_WEBSOCKET MG_ENABLE_HTTP -#endif - -#ifndef MG_ENABLE_IPV6 -#define MG_ENABLE_IPV6 0 -#endif - -#ifndef MG_ENABLE_MQTT -#define MG_ENABLE_MQTT 1 -#endif - -#ifndef MG_ENABLE_SOCKS -#define MG_ENABLE_SOCKS 0 -#endif - -#ifndef MG_ENABLE_MQTT_BROKER -#define MG_ENABLE_MQTT_BROKER 0 -#endif - -#ifndef MG_ENABLE_SSL -#define MG_ENABLE_SSL 0 -#endif - -#ifndef MG_ENABLE_SYNC_RESOLVER -#define MG_ENABLE_SYNC_RESOLVER 0 -#endif - -#ifndef MG_ENABLE_STDIO -#define MG_ENABLE_STDIO CS_ENABLE_STDIO -#endif - -#ifndef MG_NET_IF -#define MG_NET_IF MG_NET_IF_SOCKET -#endif - -#ifndef MG_SSL_IF -#define MG_SSL_IF MG_SSL_IF_OPENSSL -#endif - -#ifndef MG_ENABLE_THREADS /* ifdef-ok */ -#ifdef _WIN32 -#define MG_ENABLE_THREADS 1 -#else -#define MG_ENABLE_THREADS 0 -#endif -#endif - -#if MG_ENABLE_DEBUG && !defined(CS_ENABLE_DEBUG) -#define CS_ENABLE_DEBUG 1 -#endif - -/* MQTT broker requires MQTT */ -#if MG_ENABLE_MQTT_BROKER && !MG_ENABLE_MQTT -#undef MG_ENABLE_MQTT -#define MG_ENABLE_MQTT 1 -#endif - -#ifndef MG_ENABLE_HTTP_URL_REWRITES -#define MG_ENABLE_HTTP_URL_REWRITES \ - (CS_PLATFORM == CS_P_WINDOWS || CS_PLATFORM == CS_P_UNIX) -#endif - -#ifndef MG_ENABLE_SNTP -#define MG_ENABLE_SNTP 0 -#endif - -#ifndef MG_ENABLE_EXTRA_ERRORS_DESC -#define MG_ENABLE_EXTRA_ERRORS_DESC 0 -#endif - -#ifndef MG_ENABLE_CALLBACK_USERDATA -#define MG_ENABLE_CALLBACK_USERDATA 0 -#endif - -#if MG_ENABLE_CALLBACK_USERDATA -#define MG_UD_ARG(ud) , ud -#define MG_CB(cb, ud) cb, ud -#else -#define MG_UD_ARG(ud) -#define MG_CB(cb, ud) cb -#endif - -#endif /* CS_MONGOOSE_SRC_FEATURES_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_net_if.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_MONGOOSE_SRC_NET_IF_H_ -#define CS_MONGOOSE_SRC_NET_IF_H_ - -/* Amalgamated: #include "common/platform.h" */ - -/* - * Internal async networking core interface. - * Consists of calls made by the core, which should not block, - * and callbacks back into the core ("..._cb"). - * Callbacks may (will) cause methods to be invoked from within, - * but methods are not allowed to invoke callbacks inline. - * - * Implementation must ensure that only one callback is invoked at any time. - */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#define MG_MAIN_IFACE 0 - -struct mg_mgr; -struct mg_connection; -union socket_address; - -struct mg_iface_vtable; - -struct mg_iface { - struct mg_mgr *mgr; - void *data; /* Implementation-specific data */ - const struct mg_iface_vtable *vtable; -}; - -struct mg_iface_vtable { - void (*init)(struct mg_iface *iface); - void (*free)(struct mg_iface *iface); - void (*add_conn)(struct mg_connection *nc); - void (*remove_conn)(struct mg_connection *nc); - time_t (*poll)(struct mg_iface *iface, int timeout_ms); - - /* Set up a listening TCP socket on a given address. rv = 0 -> ok. */ - int (*listen_tcp)(struct mg_connection *nc, union socket_address *sa); - /* Request that a "listening" UDP socket be created. */ - int (*listen_udp)(struct mg_connection *nc, union socket_address *sa); - - /* Request that a TCP connection is made to the specified address. */ - void (*connect_tcp)(struct mg_connection *nc, const union socket_address *sa); - /* Open a UDP socket. Doesn't actually connect anything. */ - void (*connect_udp)(struct mg_connection *nc); - - /* Send functions for TCP and UDP. Sent data is copied before return. */ - int (*tcp_send)(struct mg_connection *nc, const void *buf, size_t len); - int (*udp_send)(struct mg_connection *nc, const void *buf, size_t len); - - int (*tcp_recv)(struct mg_connection *nc, void *buf, size_t len); - int (*udp_recv)(struct mg_connection *nc, void *buf, size_t len, - union socket_address *sa, size_t *sa_len); - - /* Perform interface-related connection initialization. Return 1 on ok. */ - int (*create_conn)(struct mg_connection *nc); - /* Perform interface-related cleanup on connection before destruction. */ - void (*destroy_conn)(struct mg_connection *nc); - - /* Associate a socket to a connection. */ - void (*sock_set)(struct mg_connection *nc, sock_t sock); - - /* Put connection's address into *sa, local (remote = 0) or remote. */ - void (*get_conn_addr)(struct mg_connection *nc, int remote, - union socket_address *sa); -}; - -extern const struct mg_iface_vtable *mg_ifaces[]; -extern int mg_num_ifaces; - -/* Creates a new interface instance. */ -struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable, - struct mg_mgr *mgr); - -/* - * Find an interface with a given implementation. The search is started from - * interface `from`, exclusive. Returns NULL if none is found. - */ -struct mg_iface *mg_find_iface(struct mg_mgr *mgr, - const struct mg_iface_vtable *vtable, - struct mg_iface *from); -/* - * Deliver a new TCP connection. Returns NULL in case on error (unable to - * create connection, in which case interface state should be discarded. - * This is phase 1 of the two-phase process - MG_EV_ACCEPT will be delivered - * when mg_if_accept_tcp_cb is invoked. - */ -struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc); -void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa, - size_t sa_len); - -/* Callback invoked by connect methods. err = 0 -> ok, != 0 -> error. */ -void mg_if_connect_cb(struct mg_connection *nc, int err); -/* - * Callback that tells the core that data can be received. - * Core will use tcp/udp_recv to retrieve the data. - */ -void mg_if_can_recv_cb(struct mg_connection *nc); -void mg_if_can_send_cb(struct mg_connection *nc); -/* - * Receive callback. - * buf must be heap-allocated and ownership is transferred to the core. - */ -void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len, - union socket_address *sa, size_t sa_len); - -/* void mg_if_close_conn(struct mg_connection *nc); */ - -/* Deliver a POLL event to the connection. */ -int mg_if_poll(struct mg_connection *nc, double now); - -/* - * Return minimal timer value amoung connections in the manager. - * Returns 0 if there aren't any timers. - */ -double mg_mgr_min_timer(const struct mg_mgr *mgr); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_MONGOOSE_SRC_NET_IF_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_ssl_if.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_MONGOOSE_SRC_SSL_IF_H_ -#define CS_MONGOOSE_SRC_SSL_IF_H_ - -#if MG_ENABLE_SSL - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -struct mg_ssl_if_ctx; -struct mg_connection; - -void mg_ssl_if_init(); - -enum mg_ssl_if_result { - MG_SSL_OK = 0, - MG_SSL_WANT_READ = -1, - MG_SSL_WANT_WRITE = -2, - MG_SSL_ERROR = -3, -}; - -struct mg_ssl_if_conn_params { - const char *cert; - const char *key; - const char *ca_cert; - const char *server_name; - const char *cipher_suites; - const char *psk_identity; - const char *psk_key; -}; - -enum mg_ssl_if_result mg_ssl_if_conn_init( - struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, - const char **err_msg); -enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, - struct mg_connection *lc); -void mg_ssl_if_conn_close_notify(struct mg_connection *nc); -void mg_ssl_if_conn_free(struct mg_connection *nc); - -enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc); -int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size); -int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* MG_ENABLE_SSL */ - -#endif /* CS_MONGOOSE_SRC_SSL_IF_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_net.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - * This software is dual-licensed: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. For the terms of this - * license, see . - * - * You are free to use this software under the terms of the GNU General - * Public License, but WITHOUT ANY WARRANTY; without even the implied - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * Alternatively, you can license this software under a commercial - * license, as set out in . - */ - -/* - * === Core API: TCP/UDP/SSL - * - * NOTE: Mongoose manager is single threaded. It does not protect - * its data structures by mutexes, therefore all functions that are dealing - * with a particular event manager should be called from the same thread, - * with exception of the `mg_broadcast()` function. It is fine to have different - * event managers handled by different threads. - */ - -#ifndef CS_MONGOOSE_SRC_NET_H_ -#define CS_MONGOOSE_SRC_NET_H_ - -/* Amalgamated: #include "mg_common.h" */ -/* Amalgamated: #include "mg_net_if.h" */ -/* Amalgamated: #include "common/mbuf.h" */ - -#ifndef MG_VPRINTF_BUFFER_SIZE -#define MG_VPRINTF_BUFFER_SIZE 100 -#endif - -#ifdef MG_USE_READ_WRITE -#define MG_RECV_FUNC(s, b, l, f) read(s, b, l) -#define MG_SEND_FUNC(s, b, l, f) write(s, b, l) -#else -#define MG_RECV_FUNC(s, b, l, f) recv(s, b, l, f) -#define MG_SEND_FUNC(s, b, l, f) send(s, b, l, f) -#endif - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -union socket_address { - struct sockaddr sa; - struct sockaddr_in sin; -#if MG_ENABLE_IPV6 - struct sockaddr_in6 sin6; -#else - struct sockaddr sin6; -#endif -}; - -struct mg_connection; - -/* - * Callback function (event handler) prototype. Must be defined by the user. - * Mongoose calls the event handler, passing the events defined below. - */ -typedef void (*mg_event_handler_t)(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)); - -/* Events. Meaning of event parameter (evp) is given in the comment. */ -#define MG_EV_POLL 0 /* Sent to each connection on each mg_mgr_poll() call */ -#define MG_EV_ACCEPT 1 /* New connection accepted. union socket_address * */ -#define MG_EV_CONNECT 2 /* connect() succeeded or failed. int * */ -#define MG_EV_RECV 3 /* Data has been received. int *num_bytes */ -#define MG_EV_SEND 4 /* Data has been written to a socket. int *num_bytes */ -#define MG_EV_CLOSE 5 /* Connection is closed. NULL */ -#define MG_EV_TIMER 6 /* now >= conn->ev_timer_time. double * */ - -/* - * Mongoose event manager. - */ -struct mg_mgr { - struct mg_connection *active_connections; -#if MG_ENABLE_HEXDUMP - const char *hexdump_file; /* Debug hexdump file path */ -#endif -#if MG_ENABLE_BROADCAST - sock_t ctl[2]; /* Socketpair for mg_broadcast() */ -#endif - void *user_data; /* User data */ - int num_ifaces; - int num_calls; - struct mg_iface **ifaces; /* network interfaces */ - const char *nameserver; /* DNS server to use */ -}; - -/* - * Mongoose connection. - */ -struct mg_connection { - struct mg_connection *next, *prev; /* mg_mgr::active_connections linkage */ - struct mg_connection *listener; /* Set only for accept()-ed connections */ - struct mg_mgr *mgr; /* Pointer to containing manager */ - - sock_t sock; /* Socket to the remote peer */ - int err; - union socket_address sa; /* Remote peer address */ - size_t recv_mbuf_limit; /* Max size of recv buffer */ - struct mbuf recv_mbuf; /* Received data */ - struct mbuf send_mbuf; /* Data scheduled for sending */ - time_t last_io_time; /* Timestamp of the last socket IO */ - double ev_timer_time; /* Timestamp of the future MG_EV_TIMER */ -#if MG_ENABLE_SSL - void *ssl_if_data; /* SSL library data. */ -#endif - mg_event_handler_t proto_handler; /* Protocol-specific event handler */ - void *proto_data; /* Protocol-specific data */ - void (*proto_data_destructor)(void *proto_data); - mg_event_handler_t handler; /* Event handler function */ - void *user_data; /* User-specific data */ - union { - void *v; - /* - * the C standard is fussy about fitting function pointers into - * void pointers, since some archs might have fat pointers for functions. - */ - mg_event_handler_t f; - } priv_1; - void *priv_2; - void *mgr_data; /* Implementation-specific event manager's data. */ - struct mg_iface *iface; - unsigned long flags; -/* Flags set by Mongoose */ -#define MG_F_LISTENING (1 << 0) /* This connection is listening */ -#define MG_F_UDP (1 << 1) /* This connection is UDP */ -#define MG_F_RESOLVING (1 << 2) /* Waiting for async resolver */ -#define MG_F_CONNECTING (1 << 3) /* connect() call in progress */ -#define MG_F_SSL (1 << 4) /* SSL is enabled on the connection */ -#define MG_F_SSL_HANDSHAKE_DONE (1 << 5) /* SSL hanshake has completed */ -#define MG_F_WANT_READ (1 << 6) /* SSL specific */ -#define MG_F_WANT_WRITE (1 << 7) /* SSL specific */ -#define MG_F_IS_WEBSOCKET (1 << 8) /* Websocket specific */ -#define MG_F_RECV_AND_CLOSE (1 << 9) /* Drain rx and close the connection. */ - -/* Flags that are settable by user */ -#define MG_F_SEND_AND_CLOSE (1 << 10) /* Push remaining data and close */ -#define MG_F_CLOSE_IMMEDIATELY (1 << 11) /* Disconnect */ -#define MG_F_WEBSOCKET_NO_DEFRAG (1 << 12) /* Websocket specific */ -#define MG_F_DELETE_CHUNK (1 << 13) /* HTTP specific */ -#define MG_F_ENABLE_BROADCAST (1 << 14) /* Allow broadcast address usage */ - -#define MG_F_USER_1 (1 << 20) /* Flags left for application */ -#define MG_F_USER_2 (1 << 21) -#define MG_F_USER_3 (1 << 22) -#define MG_F_USER_4 (1 << 23) -#define MG_F_USER_5 (1 << 24) -#define MG_F_USER_6 (1 << 25) -}; - -/* - * Initialise Mongoose manager. Side effect: ignores SIGPIPE signal. - * `mgr->user_data` field will be initialised with a `user_data` parameter. - * That is an arbitrary pointer, where the user code can associate some data - * with the particular Mongoose manager. For example, a C++ wrapper class - * could be written in which case `user_data` can hold a pointer to the - * class instance. - */ -void mg_mgr_init(struct mg_mgr *mgr, void *user_data); - -/* - * Optional parameters to `mg_mgr_init_opt()`. - * - * If `main_iface` is not NULL, it will be used as the main interface in the - * default interface set. The pointer will be free'd by `mg_mgr_free`. - * Otherwise, the main interface will be autodetected based on the current - * platform. - * - * If `num_ifaces` is 0 and `ifaces` is NULL, the default interface set will be - * used. - * This is an advanced option, as it requires you to construct a full interface - * set, including special networking interfaces required by some optional - * features such as TCP tunneling. Memory backing `ifaces` and each of the - * `num_ifaces` pointers it contains will be reclaimed by `mg_mgr_free`. - */ -struct mg_mgr_init_opts { - const struct mg_iface_vtable *main_iface; - int num_ifaces; - const struct mg_iface_vtable **ifaces; - const char *nameserver; -}; - -/* - * Like `mg_mgr_init` but with more options. - * - * Notably, this allows you to create a manger and choose - * dynamically which networking interface implementation to use. - */ -void mg_mgr_init_opt(struct mg_mgr *mgr, void *user_data, - struct mg_mgr_init_opts opts); - -/* - * De-initialises Mongoose manager. - * - * Closes and deallocates all active connections. - */ -void mg_mgr_free(struct mg_mgr *mgr); - -/* - * This function performs the actual IO and must be called in a loop - * (an event loop). It returns number of user events generated (except POLLs). - * `milli` is the maximum number of milliseconds to sleep. - * `mg_mgr_poll()` checks all connections for IO readiness. If at least one - * of the connections is IO-ready, `mg_mgr_poll()` triggers the respective - * event handlers and returns. - */ -int mg_mgr_poll(struct mg_mgr *mgr, int milli); - -#if MG_ENABLE_BROADCAST -/* - * Passes a message of a given length to all connections. - * - * Must be called from a thread that does NOT call `mg_mgr_poll()`. - * Note that `mg_broadcast()` is the only function - * that can be, and must be, called from a different (non-IO) thread. - * - * `func` callback function will be called by the IO thread for each - * connection. When called, the event will be `MG_EV_POLL`, and a message will - * be passed as the `ev_data` pointer. Maximum message size is capped - * by `MG_CTL_MSG_MESSAGE_SIZE` which is set to 8192 bytes by default. - */ -void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data, - size_t len); -#endif - -/* - * Iterates over all active connections. - * - * Returns the next connection from the list - * of active connections or `NULL` if there are no more connections. Below - * is the iteration idiom: - * - * ```c - * for (c = mg_next(srv, NULL); c != NULL; c = mg_next(srv, c)) { - * // Do something with connection `c` - * } - * ``` - */ -struct mg_connection *mg_next(struct mg_mgr *mgr, struct mg_connection *c); - -/* - * Optional parameters to `mg_add_sock_opt()`. - * - * `flags` is an initial `struct mg_connection::flags` bitmask to set, - * see `MG_F_*` flags definitions. - */ -struct mg_add_sock_opts { - void *user_data; /* Initial value for connection's user_data */ - unsigned int flags; /* Initial connection flags */ - const char **error_string; /* Placeholder for the error string */ - struct mg_iface *iface; /* Interface instance */ -}; - -/* - * Creates a connection, associates it with the given socket and event handler - * and adds it to the manager. - * - * For more options see the `mg_add_sock_opt` variant. - */ -struct mg_connection *mg_add_sock(struct mg_mgr *mgr, sock_t sock, - MG_CB(mg_event_handler_t handler, - void *user_data)); - -/* - * Creates a connection, associates it with the given socket and event handler - * and adds to the manager. - * - * See the `mg_add_sock_opts` structure for a description of the options. - */ -struct mg_connection *mg_add_sock_opt(struct mg_mgr *mgr, sock_t sock, - MG_CB(mg_event_handler_t handler, - void *user_data), - struct mg_add_sock_opts opts); - -/* - * Optional parameters to `mg_bind_opt()`. - * - * `flags` is an initial `struct mg_connection::flags` bitmask to set, - * see `MG_F_*` flags definitions. - */ -struct mg_bind_opts { - void *user_data; /* Initial value for connection's user_data */ - unsigned int flags; /* Extra connection flags */ - const char **error_string; /* Placeholder for the error string */ - struct mg_iface *iface; /* Interface instance */ -#if MG_ENABLE_SSL - /* - * SSL settings. - * - * Server certificate to present to clients or client certificate to - * present to tunnel dispatcher (for tunneled connections). - */ - const char *ssl_cert; - /* Private key corresponding to the certificate. If ssl_cert is set but - * ssl_key is not, ssl_cert is used. */ - const char *ssl_key; - /* CA bundle used to verify client certificates or tunnel dispatchers. */ - const char *ssl_ca_cert; - /* Colon-delimited list of acceptable cipher suites. - * Names depend on the library used, for example: - * - * ECDH-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256 (OpenSSL) - * TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256 - * (mbedTLS) - * - * For OpenSSL the list can be obtained by running "openssl ciphers". - * For mbedTLS, names can be found in library/ssl_ciphersuites.c - * If NULL, a reasonable default is used. - */ - const char *ssl_cipher_suites; -#endif -}; - -/* - * Creates a listening connection. - * - * See `mg_bind_opt` for full documentation. - */ -struct mg_connection *mg_bind(struct mg_mgr *mgr, const char *address, - MG_CB(mg_event_handler_t handler, - void *user_data)); -/* - * Creates a listening connection. - * - * The `address` parameter specifies which address to bind to. It's format is - * the same as for the `mg_connect()` call, where `HOST` part is optional. - * `address` can be just a port number, e.g. `:8000`. To bind to a specific - * interface, an IP address can be specified, e.g. `1.2.3.4:8000`. By default, - * a TCP connection is created. To create UDP connection, prepend `udp://` - * prefix, e.g. `udp://:8000`. To summarize, `address` parameter has following - * format: `[PROTO://][IP_ADDRESS]:PORT`, where `PROTO` could be `tcp` or - * `udp`. - * - * See the `mg_bind_opts` structure for a description of the optional - * parameters. - * - * Returns a new listening connection or `NULL` on error. - * NOTE: The connection remains owned by the manager, do not free(). - */ -struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address, - MG_CB(mg_event_handler_t handler, - void *user_data), - struct mg_bind_opts opts); - -/* Optional parameters to `mg_connect_opt()` */ -struct mg_connect_opts { - void *user_data; /* Initial value for connection's user_data */ - unsigned int flags; /* Extra connection flags */ - const char **error_string; /* Placeholder for the error string */ - struct mg_iface *iface; /* Interface instance */ - const char *nameserver; /* DNS server to use, NULL for default */ -#if MG_ENABLE_SSL - /* - * SSL settings. - * Client certificate to present to the server. - */ - const char *ssl_cert; - /* - * Private key corresponding to the certificate. - * If ssl_cert is set but ssl_key is not, ssl_cert is used. - */ - const char *ssl_key; - /* - * Verify server certificate using this CA bundle. If set to "*", then SSL - * is enabled but no cert verification is performed. - */ - const char *ssl_ca_cert; - /* Colon-delimited list of acceptable cipher suites. - * Names depend on the library used, for example: - * - * ECDH-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256 (OpenSSL) - * TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256 - * (mbedTLS) - * - * For OpenSSL the list can be obtained by running "openssl ciphers". - * For mbedTLS, names can be found in library/ssl_ciphersuites.c - * If NULL, a reasonable default is used. - */ - const char *ssl_cipher_suites; - /* - * Server name verification. If ssl_ca_cert is set and the certificate has - * passed verification, its subject will be verified against this string. - * By default (if ssl_server_name is NULL) hostname part of the address will - * be used. Wildcard matching is supported. A special value of "*" disables - * name verification. - */ - const char *ssl_server_name; - /* - * PSK identity and key. Identity is a NUL-terminated string and key is a hex - * string. Key must be either 16 or 32 bytes (32 or 64 hex digits) for AES-128 - * or AES-256 respectively. - * Note: Default list of cipher suites does not include PSK suites, if you - * want to use PSK you will need to set ssl_cipher_suites as well. - */ - const char *ssl_psk_identity; - const char *ssl_psk_key; -#endif -}; - -/* - * Connects to a remote host. - * - * See `mg_connect_opt()` for full documentation. - */ -struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address, - MG_CB(mg_event_handler_t handler, - void *user_data)); - -/* - * Connects to a remote host. - * - * The `address` format is `[PROTO://]HOST:PORT`. `PROTO` could be `tcp` or - * `udp`. `HOST` could be an IP address, - * IPv6 address (if Mongoose is compiled with `-DMG_ENABLE_IPV6`) or a host - * name. If `HOST` is a name, Mongoose will resolve it asynchronously. Examples - * of valid addresses: `google.com:80`, `udp://1.2.3.4:53`, `10.0.0.1:443`, - * `[::1]:80` - * - * See the `mg_connect_opts` structure for a description of the optional - * parameters. - * - * Returns a new outbound connection or `NULL` on error. - * - * NOTE: The connection remains owned by the manager, do not free(). - * - * NOTE: To enable IPv6 addresses `-DMG_ENABLE_IPV6` should be specified - * in the compilation flags. - * - * NOTE: The new connection will receive `MG_EV_CONNECT` as its first event - * which will report the connect success status. - * If the asynchronous resolution fails or the `connect()` syscall fails for - * whatever reason (e.g. with `ECONNREFUSED` or `ENETUNREACH`), then - * `MG_EV_CONNECT` event will report failure. Code example below: - * - * ```c - * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { - * int connect_status; - * - * switch (ev) { - * case MG_EV_CONNECT: - * connect_status = * (int *) ev_data; - * if (connect_status == 0) { - * // Success - * } else { - * // Error - * printf("connect() error: %s\n", strerror(connect_status)); - * } - * break; - * ... - * } - * } - * - * ... - * mg_connect(mgr, "my_site.com:80", ev_handler); - * ``` - */ -struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address, - MG_CB(mg_event_handler_t handler, - void *user_data), - struct mg_connect_opts opts); - -#if MG_ENABLE_SSL && MG_NET_IF != MG_NET_IF_SIMPLELINK -/* - * Note: This function is deprecated. Please, use SSL options in - * mg_connect_opt. - * - * Enables SSL for a given connection. - * `cert` is a server certificate file name for a listening connection - * or a client certificate file name for an outgoing connection. - * The certificate files must be in PEM format. The server certificate file - * must contain a certificate, concatenated with a private key, optionally - * concatenated with DH parameters. - * `ca_cert` is a CA certificate or NULL if peer verification is not - * required. - * Return: NULL on success or error message on error. - */ -const char *mg_set_ssl(struct mg_connection *nc, const char *cert, - const char *ca_cert); -#endif - -/* - * Sends data to the connection. - * - * Note that sending functions do not actually push data to the socket. - * They just append data to the output buffer. MG_EV_SEND will be delivered when - * the data has actually been pushed out. - */ -void mg_send(struct mg_connection *, const void *buf, int len); - -/* Enables format string warnings for mg_printf */ -#if defined(__GNUC__) -__attribute__((format(printf, 2, 3))) -#endif -/* don't separate from mg_printf declaration */ - -/* - * Sends `printf`-style formatted data to the connection. - * - * See `mg_send` for more details on send semantics. - */ -int mg_printf(struct mg_connection *, const char *fmt, ...); - -/* Same as `mg_printf()`, but takes `va_list ap` as an argument. */ -int mg_vprintf(struct mg_connection *, const char *fmt, va_list ap); - -/* - * Creates a socket pair. - * `sock_type` can be either `SOCK_STREAM` or `SOCK_DGRAM`. - * Returns 0 on failure and 1 on success. - */ -int mg_socketpair(sock_t[2], int sock_type); - -#if MG_ENABLE_SYNC_RESOLVER -/* - * Convert domain name into IP address. - * - * This is a utility function. If compilation flags have - * `-DMG_ENABLE_GETADDRINFO`, then `getaddrinfo()` call is used for name - * resolution. Otherwise, `gethostbyname()` is used. - * - * CAUTION: this function can block. - * Return 1 on success, 0 on failure. - */ -int mg_resolve(const char *domain_name, char *ip_addr_buf, size_t buf_len); -#endif - -/* - * Verify given IP address against the ACL. - * - * `remote_ip` - an IPv4 address to check, in host byte order - * `acl` - a comma separated list of IP subnets: `x.x.x.x/x` or `x.x.x.x`. - * Each subnet is - * prepended by either a - or a + sign. A plus sign means allow, where a - * minus sign means deny. If a subnet mask is omitted, such as `-1.2.3.4`, - * it means that only that single IP address is denied. - * Subnet masks may vary from 0 to 32, inclusive. The default setting - * is to allow all access. On each request the full list is traversed, - * and the last match wins. Example: - * - * `-0.0.0.0/0,+192.168/16` - deny all accesses, only allow 192.168/16 subnet - * - * To learn more about subnet masks, see this - * link:https://en.wikipedia.org/wiki/Subnetwork[Wikipedia page on Subnetwork]. - * - * Returns -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. - */ -int mg_check_ip_acl(const char *acl, uint32_t remote_ip); - -/* - * Schedules an MG_EV_TIMER event to be delivered at `timestamp` time. - * `timestamp` is UNIX time (the number of seconds since Epoch). It is - * `double` instead of `time_t` to allow for sub-second precision. - * Returns the old timer value. - * - * Example: set the connect timeout to 1.5 seconds: - * - * ``` - * c = mg_connect(&mgr, "cesanta.com", ev_handler); - * mg_set_timer(c, mg_time() + 1.5); - * ... - * - * void ev_handler(struct mg_connection *c, int ev, void *ev_data) { - * switch (ev) { - * case MG_EV_CONNECT: - * mg_set_timer(c, 0); // Clear connect timer - * break; - * case MG_EV_TIMER: - * log("Connect timeout"); - * c->flags |= MG_F_CLOSE_IMMEDIATELY; - * break; - * ``` - */ -double mg_set_timer(struct mg_connection *c, double timestamp); - -/* - * A sub-second precision version of time(). - */ -double mg_time(void); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_MONGOOSE_SRC_NET_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_uri.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* - * === URI - */ - -#ifndef CS_MONGOOSE_SRC_URI_H_ -#define CS_MONGOOSE_SRC_URI_H_ - -/* Amalgamated: #include "mg_net.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* - * Parses an URI and fills string chunks with locations of the respective - * uri components within the input uri string. NULL pointers will be - * ignored. - * - * General syntax: - * - * [scheme://[user_info@]]host[:port][/path][?query][#fragment] - * - * Example: - * - * foo.com:80 - * tcp://foo.com:1234 - * http://foo.com:80/bar?baz=1 - * https://user:pw@foo.com:443/blah - * - * `path` will include the leading slash. `query` won't include the leading `?`. - * `host` can contain embedded colons if surrounded by square brackets in order - * to support IPv6 literal addresses. - * - * - * Returns 0 on success, -1 on error. - */ -int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme, - struct mg_str *user_info, struct mg_str *host, - unsigned int *port, struct mg_str *path, struct mg_str *query, - struct mg_str *fragment); - -/* - * Assemble URI from parts. Any of the inputs can be NULL or zero-length mg_str. - * - * If normalize_path is true, path is normalized by resolving relative refs. - * - * Result is a heap-allocated string (uri->p must be free()d after use). - * - * Returns 0 on success, -1 on error. - */ -int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info, - const struct mg_str *host, unsigned int port, - const struct mg_str *path, const struct mg_str *query, - const struct mg_str *fragment, int normalize_path, - struct mg_str *uri); - -int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* CS_MONGOOSE_SRC_URI_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_util.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* - * === Utility API - */ - -#ifndef CS_MONGOOSE_SRC_UTIL_H_ -#define CS_MONGOOSE_SRC_UTIL_H_ - -#include - -/* Amalgamated: #include "mg_common.h" */ -/* Amalgamated: #include "mg_net_if.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifndef MG_MAX_PATH -#ifdef PATH_MAX -#define MG_MAX_PATH PATH_MAX -#else -#define MG_MAX_PATH 256 -#endif -#endif - -/* - * Fetches substring from input string `s`, `end` into `v`. - * Skips initial delimiter characters. Records first non-delimiter character - * at the beginning of substring `v`. Then scans the rest of the string - * until a delimiter character or end-of-string is found. - * `delimiters` is a 0-terminated string containing delimiter characters. - * Either one of `delimiters` or `end_string` terminates the search. - * Returns an `s` pointer, advanced forward where parsing has stopped. - */ -const char *mg_skip(const char *s, const char *end_string, - const char *delimiters, struct mg_str *v); - -/* - * Decodes base64-encoded string `s`, `len` into the destination `dst`. - * The destination has to have enough space to hold the decoded buffer. - * Decoding stops either when all strings have been decoded or invalid an - * character appeared. - * Destination is '\0'-terminated. - * Returns the number of decoded characters. On success, that should be equal - * to `len`. On error (invalid character) the return value is smaller then - * `len`. - */ -int mg_base64_decode(const unsigned char *s, int len, char *dst); - -/* - * Base64-encode chunk of memory `src`, `src_len` into the destination `dst`. - * Destination has to have enough space to hold encoded buffer. - * Destination is '\0'-terminated. - */ -void mg_base64_encode(const unsigned char *src, int src_len, char *dst); - -#if MG_ENABLE_FILESYSTEM -/* - * Performs a 64-bit `stat()` call against a given file. - * - * `path` should be UTF8 encoded. - * - * Return value is the same as for `stat()` syscall. - */ -int mg_stat(const char *path, cs_stat_t *st); - -/* - * Opens the given file and returns a file stream. - * - * `path` and `mode` should be UTF8 encoded. - * - * Return value is the same as for the `fopen()` call. - */ -FILE *mg_fopen(const char *path, const char *mode); - -/* - * Opens the given file and returns a file stream. - * - * `path` should be UTF8 encoded. - * - * Return value is the same as for the `open()` syscall. - */ -int mg_open(const char *path, int flag, int mode); - -/* - * Reads data from the given file stream. - * - * Return value is a number of bytes readen. - */ -size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f); - -/* - * Writes data to the given file stream. - * - * Return value is a number of bytes wtitten. - */ -size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f); - -#endif /* MG_ENABLE_FILESYSTEM */ - -#if MG_ENABLE_THREADS -/* - * Starts a new detached thread. - * Arguments and semantics are the same as pthead's `pthread_create()`. - * `thread_func` is a thread function, `thread_func_param` is a parameter - * that is passed to the thread function. - */ -void *mg_start_thread(void *(*thread_func)(void *), void *thread_func_param); -#endif - -void mg_set_close_on_exec(sock_t); - -#define MG_SOCK_STRINGIFY_IP 1 -#define MG_SOCK_STRINGIFY_PORT 2 -#define MG_SOCK_STRINGIFY_REMOTE 4 -/* - * Converts a connection's local or remote address into string. - * - * The `flags` parameter is a bit mask that controls the behaviour, - * see `MG_SOCK_STRINGIFY_*` definitions. - * - * - MG_SOCK_STRINGIFY_IP - print IP address - * - MG_SOCK_STRINGIFY_PORT - print port number - * - MG_SOCK_STRINGIFY_REMOTE - print remote peer's IP/port, not local address - * - * If both port number and IP address are printed, they are separated by `:`. - * If compiled with `-DMG_ENABLE_IPV6`, IPv6 addresses are supported. - * Return length of the stringified address. - */ -int mg_conn_addr_to_str(struct mg_connection *c, char *buf, size_t len, - int flags); -#if MG_NET_IF == MG_NET_IF_SOCKET -/* Legacy interface. */ -void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags); -#endif - -/* - * Convert the socket's address into string. - * - * `flags` is MG_SOCK_STRINGIFY_IP and/or MG_SOCK_STRINGIFY_PORT. - */ -int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len, - int flags); - -#if MG_ENABLE_HEXDUMP -/* - * Generates a human-readable hexdump of memory chunk. - * - * Takes a memory buffer `buf` of length `len` and creates a hex dump of that - * buffer in `dst`. The generated output is a-la hexdump(1). - * Returns the length of generated string, excluding terminating `\0`. If - * returned length is bigger than `dst_len`, the overflow bytes are discarded. - */ -int mg_hexdump(const void *buf, int len, char *dst, int dst_len); - -/* Same as mg_hexdump, but with output going to file instead of a buffer. */ -void mg_hexdumpf(FILE *fp, const void *buf, int len); - -/* - * Generates human-readable hexdump of the data sent or received by the - * connection. `path` is a file name where hexdump should be written. - * `num_bytes` is a number of bytes sent/received. `ev` is one of the `MG_*` - * events sent to an event handler. This function is supposed to be called from - * the event handler. - */ -void mg_hexdump_connection(struct mg_connection *nc, const char *path, - const void *buf, int num_bytes, int ev); -#endif - -/* - * Returns true if target platform is big endian. - */ -int mg_is_big_endian(void); - -/* - * Use with cs_base64_init/update/finish in order to write out base64 in chunks. - */ -void mg_mbuf_append_base64_putc(char ch, void *user_data); - -/* - * Encode `len` bytes starting at `data` as base64 and append them to an mbuf. - */ -void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len); - -/* - * Generate a Basic Auth header and appends it to buf. - * If pass is NULL, then user is expected to contain the credentials pair - * already encoded as `user:pass`. - */ -void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass, - struct mbuf *buf); - -/* - * URL-escape the specified string. - * All characters acept letters, numbers and characters listed in - * `safe` are escaped. If `hex_upper`is true, `A-F` are used for hex digits. - * Input need not be NUL-terminated, but the returned string is. - * Returned string is heap-allocated and must be free()'d. - */ -#define MG_URL_ENCODE_F_SPACE_AS_PLUS (1 << 0) -#define MG_URL_ENCODE_F_UPPERCASE_HEX (1 << 1) -struct mg_str mg_url_encode_opt(const struct mg_str src, - const struct mg_str safe, unsigned int flags); - -/* Same as `mg_url_encode_opt(src, "._-$,;~()/", 0)`. */ -struct mg_str mg_url_encode(const struct mg_str src); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* CS_MONGOOSE_SRC_UTIL_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* - * === Common API reference - */ - -#ifndef CS_MONGOOSE_SRC_HTTP_H_ -#define CS_MONGOOSE_SRC_HTTP_H_ - -#if MG_ENABLE_HTTP - -/* Amalgamated: #include "mg_net.h" */ -/* Amalgamated: #include "common/mg_str.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifndef MG_MAX_HTTP_HEADERS -#define MG_MAX_HTTP_HEADERS 20 -#endif - -#ifndef MG_MAX_HTTP_REQUEST_SIZE -#define MG_MAX_HTTP_REQUEST_SIZE 1024 -#endif - -#ifndef MG_MAX_HTTP_SEND_MBUF -#define MG_MAX_HTTP_SEND_MBUF 1024 -#endif - -#ifndef MG_CGI_ENVIRONMENT_SIZE -#define MG_CGI_ENVIRONMENT_SIZE 8192 -#endif - -/* HTTP message */ -struct http_message { - struct mg_str message; /* Whole message: request line + headers + body */ - struct mg_str body; /* Message body. 0-length for requests with no body */ - - /* HTTP Request line (or HTTP response line) */ - struct mg_str method; /* "GET" */ - struct mg_str uri; /* "/my_file.html" */ - struct mg_str proto; /* "HTTP/1.1" -- for both request and response */ - - /* For responses, code and response status message are set */ - int resp_code; - struct mg_str resp_status_msg; - - /* - * Query-string part of the URI. For example, for HTTP request - * GET /foo/bar?param1=val1¶m2=val2 - * | uri | query_string | - * - * Note that question mark character doesn't belong neither to the uri, - * nor to the query_string - */ - struct mg_str query_string; - - /* Headers */ - struct mg_str header_names[MG_MAX_HTTP_HEADERS]; - struct mg_str header_values[MG_MAX_HTTP_HEADERS]; -}; - -#if MG_ENABLE_HTTP_WEBSOCKET -/* WebSocket message */ -struct websocket_message { - unsigned char *data; - size_t size; - unsigned char flags; -}; -#endif - -/* HTTP multipart part */ -struct mg_http_multipart_part { - const char *file_name; - const char *var_name; - struct mg_str data; - int status; /* <0 on error */ - void *user_data; - /* - * User handler can indicate how much of the data was consumed - * by setting this variable. By default, it is assumed that all - * data has been consumed by the handler. - * If not all data was consumed, user's handler will be invoked again later - * with the remainder. - */ - size_t num_data_consumed; -}; - -/* SSI call context */ -struct mg_ssi_call_ctx { - struct http_message *req; /* The request being processed. */ - struct mg_str file; /* Filesystem path of the file being processed. */ - struct mg_str arg; /* The argument passed to the tag: . */ -}; - -/* HTTP and websocket events. void *ev_data is described in a comment. */ -#define MG_EV_HTTP_REQUEST 100 /* struct http_message * */ -#define MG_EV_HTTP_REPLY 101 /* struct http_message * */ -#define MG_EV_HTTP_CHUNK 102 /* struct http_message * */ -#define MG_EV_SSI_CALL 105 /* char * */ -#define MG_EV_SSI_CALL_CTX 106 /* struct mg_ssi_call_ctx * */ - -#if MG_ENABLE_HTTP_WEBSOCKET -#define MG_EV_WEBSOCKET_HANDSHAKE_REQUEST 111 /* struct http_message * */ -#define MG_EV_WEBSOCKET_HANDSHAKE_DONE 112 /* struct http_message * */ -#define MG_EV_WEBSOCKET_FRAME 113 /* struct websocket_message * */ -#define MG_EV_WEBSOCKET_CONTROL_FRAME 114 /* struct websocket_message * */ -#endif - -#if MG_ENABLE_HTTP_STREAMING_MULTIPART -#define MG_EV_HTTP_MULTIPART_REQUEST 121 /* struct http_message */ -#define MG_EV_HTTP_PART_BEGIN 122 /* struct mg_http_multipart_part */ -#define MG_EV_HTTP_PART_DATA 123 /* struct mg_http_multipart_part */ -#define MG_EV_HTTP_PART_END 124 /* struct mg_http_multipart_part */ -/* struct mg_http_multipart_part */ -#define MG_EV_HTTP_MULTIPART_REQUEST_END 125 -#endif - -/* - * Attaches a built-in HTTP event handler to the given connection. - * The user-defined event handler will receive following extra events: - * - * - MG_EV_HTTP_REQUEST: HTTP request has arrived. Parsed HTTP request - * is passed as - * `struct http_message` through the handler's `void *ev_data` pointer. - * - MG_EV_HTTP_REPLY: The HTTP reply has arrived. The parsed HTTP reply is - * passed as `struct http_message` through the handler's `void *ev_data` - * pointer. - * - MG_EV_HTTP_CHUNK: The HTTP chunked-encoding chunk has arrived. - * The parsed HTTP reply is passed as `struct http_message` through the - * handler's `void *ev_data` pointer. `http_message::body` would contain - * incomplete, reassembled HTTP body. - * It will grow with every new chunk that arrives, and it can - * potentially consume a lot of memory. An event handler may process - * the body as chunks are coming, and signal Mongoose to delete processed - * body by setting `MG_F_DELETE_CHUNK` in `mg_connection::flags`. When - * the last zero chunk is received, - * Mongoose sends `MG_EV_HTTP_REPLY` event with - * full reassembled body (if handler did not signal to delete chunks) or - * with empty body (if handler did signal to delete chunks). - * - MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: server has received the WebSocket - * handshake request. `ev_data` contains parsed HTTP request. - * - MG_EV_WEBSOCKET_HANDSHAKE_DONE: server has completed the WebSocket - * handshake. `ev_data` is a `struct http_message` containing the - * client's request (server mode) or server's response (client). - * In client mode handler can examine `resp_code`, which should be 101. - * - MG_EV_WEBSOCKET_FRAME: new WebSocket frame has arrived. `ev_data` is - * `struct websocket_message *` - * - * When compiled with MG_ENABLE_HTTP_STREAMING_MULTIPART, Mongoose parses - * multipart requests and splits them into separate events: - * - MG_EV_HTTP_MULTIPART_REQUEST: Start of the request. - * This event is sent before body is parsed. After this, the user - * should expect a sequence of PART_BEGIN/DATA/END requests. - * This is also the last time when headers and other request fields are - * accessible. - * - MG_EV_HTTP_PART_BEGIN: Start of a part of a multipart message. - * Argument: mg_http_multipart_part with var_name and file_name set - * (if present). No data is passed in this message. - * - MG_EV_HTTP_PART_DATA: new portion of data from the multipart message. - * Argument: mg_http_multipart_part. var_name and file_name are preserved, - * data is available in mg_http_multipart_part.data. - * - MG_EV_HTTP_PART_END: End of the current part. var_name, file_name are - * the same, no data in the message. If status is 0, then the part is - * properly terminated with a boundary, status < 0 means that connection - * was terminated. - * - MG_EV_HTTP_MULTIPART_REQUEST_END: End of the multipart request. - * Argument: mg_http_multipart_part, var_name and file_name are NULL, - * status = 0 means request was properly closed, < 0 means connection - * was terminated (note: in this case both PART_END and REQUEST_END are - * delivered). - */ -void mg_set_protocol_http_websocket(struct mg_connection *nc); - -#if MG_ENABLE_HTTP_WEBSOCKET -/* - * Send websocket handshake to the server. - * - * `nc` must be a valid connection, connected to a server. `uri` is an URI - * to fetch, extra_headers` is extra HTTP headers to send or `NULL`. - * - * This function is intended to be used by websocket client. - * - * Note that the Host header is mandatory in HTTP/1.1 and must be - * included in `extra_headers`. `mg_send_websocket_handshake2` offers - * a better API for that. - * - * Deprecated in favour of `mg_send_websocket_handshake2` - */ -void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri, - const char *extra_headers); - -/* - * Send websocket handshake to the server. - * - * `nc` must be a valid connection, connected to a server. `uri` is an URI - * to fetch, `host` goes into the `Host` header, `protocol` goes into the - * `Sec-WebSocket-Proto` header (NULL to omit), extra_headers` is extra HTTP - * headers to send or `NULL`. - * - * This function is intended to be used by websocket client. - */ -void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path, - const char *host, const char *protocol, - const char *extra_headers); - -/* Like mg_send_websocket_handshake2 but also passes basic auth header */ -void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path, - const char *host, const char *protocol, - const char *extra_headers, const char *user, - const char *pass); - -/* Same as mg_send_websocket_handshake3 but with strings not necessarily - * NUL-temrinated */ -void mg_send_websocket_handshake3v(struct mg_connection *nc, - const struct mg_str path, - const struct mg_str host, - const struct mg_str protocol, - const struct mg_str extra_headers, - const struct mg_str user, - const struct mg_str pass); - -/* - * Helper function that creates an outbound WebSocket connection. - * - * `url` is a URL to connect to. It must be properly URL-encoded, e.g. have - * no spaces, etc. By default, `mg_connect_ws()` sends Connection and - * Host headers. `extra_headers` is an extra HTTP header to send, e.g. - * `"User-Agent: my-app\r\n"`. - * If `protocol` is not NULL, then a `Sec-WebSocket-Protocol` header is sent. - * - * Examples: - * - * ```c - * nc1 = mg_connect_ws(mgr, ev_handler_1, "ws://echo.websocket.org", NULL, - * NULL); - * nc2 = mg_connect_ws(mgr, ev_handler_1, "wss://echo.websocket.org", NULL, - * NULL); - * nc3 = mg_connect_ws(mgr, ev_handler_1, "ws://api.cesanta.com", - * "clubby.cesanta.com", NULL); - * ``` - */ -struct mg_connection *mg_connect_ws(struct mg_mgr *mgr, - MG_CB(mg_event_handler_t event_handler, - void *user_data), - const char *url, const char *protocol, - const char *extra_headers); - -/* - * Helper function that creates an outbound WebSocket connection - * - * Mostly identical to `mg_connect_ws`, but allows to provide extra parameters - * (for example, SSL parameters) - */ -struct mg_connection *mg_connect_ws_opt( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - struct mg_connect_opts opts, const char *url, const char *protocol, - const char *extra_headers); - -/* - * Send WebSocket frame to the remote end. - * - * `op_and_flags` specifies the frame's type. It's one of: - * - * - WEBSOCKET_OP_CONTINUE - * - WEBSOCKET_OP_TEXT - * - WEBSOCKET_OP_BINARY - * - WEBSOCKET_OP_CLOSE - * - WEBSOCKET_OP_PING - * - WEBSOCKET_OP_PONG - * - * Orred with one of the flags: - * - * - WEBSOCKET_DONT_FIN: Don't set the FIN flag on the frame to be sent. - * - * `data` and `data_len` contain frame data. - */ -void mg_send_websocket_frame(struct mg_connection *nc, int op_and_flags, - const void *data, size_t data_len); - -/* - * Like `mg_send_websocket_frame()`, but composes a single frame from multiple - * buffers. - */ -void mg_send_websocket_framev(struct mg_connection *nc, int op_and_flags, - const struct mg_str *strings, int num_strings); - -/* - * Sends WebSocket frame to the remote end. - * - * Like `mg_send_websocket_frame()`, but allows to create formatted messages - * with `printf()`-like semantics. - */ -void mg_printf_websocket_frame(struct mg_connection *nc, int op_and_flags, - const char *fmt, ...); - -/* Websocket opcodes, from http://tools.ietf.org/html/rfc6455 */ -#define WEBSOCKET_OP_CONTINUE 0 -#define WEBSOCKET_OP_TEXT 1 -#define WEBSOCKET_OP_BINARY 2 -#define WEBSOCKET_OP_CLOSE 8 -#define WEBSOCKET_OP_PING 9 -#define WEBSOCKET_OP_PONG 10 - -/* - * If set causes the FIN flag to not be set on outbound - * frames. This enables sending multiple fragments of a single - * logical message. - * - * The WebSocket protocol mandates that if the FIN flag of a data - * frame is not set, the next frame must be a WEBSOCKET_OP_CONTINUE. - * The last frame must have the FIN bit set. - * - * Note that mongoose will automatically defragment incoming messages, - * so this flag is used only on outbound messages. - */ -#define WEBSOCKET_DONT_FIN 0x100 - -#endif /* MG_ENABLE_HTTP_WEBSOCKET */ - -/* - * Decodes a URL-encoded string. - * - * Source string is specified by (`src`, `src_len`), and destination is - * (`dst`, `dst_len`). If `is_form_url_encoded` is non-zero, then - * `+` character is decoded as a blank space character. This function - * guarantees to NUL-terminate the destination. If destination is too small, - * then the source string is partially decoded and `-1` is returned. - *Otherwise, - * a length of the decoded string is returned, not counting final NUL. - */ -int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, - int is_form_url_encoded); - -extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[], - const size_t *msg_lens, uint8_t *digest); -extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[], - const size_t *msg_lens, uint8_t *digest); - -/* - * Flags for `mg_http_is_authorized()`. - */ -#define MG_AUTH_FLAG_IS_DIRECTORY (1 << 0) -#define MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE (1 << 1) -#define MG_AUTH_FLAG_ALLOW_MISSING_FILE (1 << 2) - -/* - * Checks whether an http request is authorized. `domain` is the authentication - * realm, `passwords_file` is a htdigest file (can be created e.g. with - * `htdigest` utility). If either `domain` or `passwords_file` is NULL, this - * function always returns 1; otherwise checks the authentication in the - * http request and returns 1 only if there is a match; 0 otherwise. - */ -int mg_http_is_authorized(struct http_message *hm, struct mg_str path, - const char *domain, const char *passwords_file, - int flags); - -/* - * Sends 401 Unauthorized response. - */ -void mg_http_send_digest_auth_request(struct mg_connection *c, - const char *domain); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* MG_ENABLE_HTTP */ - -#endif /* CS_MONGOOSE_SRC_HTTP_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http_server.h" -#endif -/* - * === Server API reference - */ - -#ifndef CS_MONGOOSE_SRC_HTTP_SERVER_H_ -#define CS_MONGOOSE_SRC_HTTP_SERVER_H_ - -#if MG_ENABLE_HTTP - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* - * Parses a HTTP message. - * - * `is_req` should be set to 1 if parsing a request, 0 if reply. - * - * Returns the number of bytes parsed. If HTTP message is - * incomplete `0` is returned. On parse error, a negative number is returned. - */ -int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req); - -/* - * Searches and returns the header `name` in parsed HTTP message `hm`. - * If header is not found, NULL is returned. Example: - * - * struct mg_str *host_hdr = mg_get_http_header(hm, "Host"); - */ -struct mg_str *mg_get_http_header(struct http_message *hm, const char *name); - -/* - * Parses the HTTP header `hdr`. Finds variable `var_name` and stores its value - * in the buffer `*buf`, `buf_size`. If the buffer size is not enough, - * allocates a buffer of required size and writes it to `*buf`, similar to - * asprintf(). The caller should always check whether the buffer was updated, - * and free it if so. - * - * This function is supposed to parse cookies, authentication headers, etc. - * Example (error handling omitted): - * - * char user_buf[20]; - * char *user = user_buf; - * struct mg_str *hdr = mg_get_http_header(hm, "Authorization"); - * mg_http_parse_header2(hdr, "username", &user, sizeof(user_buf)); - * // ... do something useful with user - * if (user != user_buf) { - * free(user); - * } - * - * Returns the length of the variable's value. If variable is not found, 0 is - * returned. - */ -int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf, - size_t buf_size); - -/* - * DEPRECATED: use mg_http_parse_header2() instead. - * - * Same as mg_http_parse_header2(), but takes buffer as a `char *` (instead of - * `char **`), and thus it cannot allocate a new buffer if the provided one - * is not enough, and just returns 0 in that case. - */ -int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf, - size_t buf_size) -#ifdef __GNUC__ - __attribute__((deprecated)) -#endif - ; - -/* - * Gets and parses the Authorization: Basic header - * Returns -1 if no Authorization header is found, or if - * mg_parse_http_basic_auth - * fails parsing the resulting header. - */ -int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len, - char *pass, size_t pass_len); - -/* - * Parses the Authorization: Basic header - * Returns -1 iif the authorization type is not "Basic" or any other error such - * as incorrectly encoded base64 user password pair. - */ -int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len, - char *pass, size_t pass_len); - -/* - * Parses the buffer `buf`, `buf_len` that contains multipart form data chunks. - * Stores the chunk name in a `var_name`, `var_name_len` buffer. - * If a chunk is an uploaded file, then `file_name`, `file_name_len` is - * filled with an uploaded file name. `chunk`, `chunk_len` - * points to the chunk data. - * - * Return: number of bytes to skip to the next chunk or 0 if there are - * no more chunks. - * - * Usage example: - * - * ```c - * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { - * switch(ev) { - * case MG_EV_HTTP_REQUEST: { - * struct http_message *hm = (struct http_message *) ev_data; - * char var_name[100], file_name[100]; - * const char *chunk; - * size_t chunk_len, n1, n2; - * - * n1 = n2 = 0; - * while ((n2 = mg_parse_multipart(hm->body.p + n1, - * hm->body.len - n1, - * var_name, sizeof(var_name), - * file_name, sizeof(file_name), - * &chunk, &chunk_len)) > 0) { - * printf("var: %s, file_name: %s, size: %d, chunk: [%.*s]\n", - * var_name, file_name, (int) chunk_len, - * (int) chunk_len, chunk); - * n1 += n2; - * } - * } - * break; - * ``` - */ -size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name, - size_t var_name_len, char *file_name, - size_t file_name_len, const char **chunk, - size_t *chunk_len); - -/* - * Fetches a HTTP form variable. - * - * Fetches a variable `name` from a `buf` into a buffer specified by `dst`, - * `dst_len`. The destination is always zero-terminated. Returns the length of - * a fetched variable. If not found, 0 is returned. `buf` must be valid - * url-encoded buffer. If destination is too small or an error occured, - * negative number is returned. - */ -int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst, - size_t dst_len); - -#if MG_ENABLE_FILESYSTEM -/* - * This structure defines how `mg_serve_http()` works. - * Best practice is to set only required settings, and leave the rest as NULL. - */ -struct mg_serve_http_opts { - /* Path to web root directory */ - const char *document_root; - - /* List of index files. Default is "" */ - const char *index_files; - - /* - * Leave as NULL to disable authentication. - * To enable directory protection with authentication, set this to ".htpasswd" - * Then, creating ".htpasswd" file in any directory automatically protects - * it with digest authentication. - * Use `mongoose` web server binary, or `htdigest` Apache utility to - * create/manipulate passwords file. - * Make sure `auth_domain` is set to a valid domain name. - */ - const char *per_directory_auth_file; - - /* Authorization domain (domain name of this web server) */ - const char *auth_domain; - - /* - * Leave as NULL to disable authentication. - * Normally, only selected directories in the document root are protected. - * If absolutely every access to the web server needs to be authenticated, - * regardless of the URI, set this option to the path to the passwords file. - * Format of that file is the same as ".htpasswd" file. Make sure that file - * is located outside document root to prevent people fetching it. - */ - const char *global_auth_file; - - /* Set to "no" to disable directory listing. Enabled by default. */ - const char *enable_directory_listing; - - /* - * SSI files pattern. If not set, "**.shtml$|**.shtm$" is used. - * - * All files that match ssi_pattern are treated as SSI. - * - * Server Side Includes (SSI) is a simple interpreted server-side scripting - * language which is most commonly used to include the contents of a file - * into a web page. It can be useful when it is desirable to include a common - * piece of code throughout a website, for example, headers and footers. - * - * In order for a webpage to recognize an SSI-enabled HTML file, the - * filename should end with a special extension, by default the extension - * should be either .shtml or .shtm - * - * Unknown SSI directives are silently ignored by Mongoose. Currently, - * the following SSI directives are supported: - * <!--#include FILE_TO_INCLUDE --> - * <!--#exec "COMMAND_TO_EXECUTE" --> - * <!--#call COMMAND --> - * - * Note that <!--#include ...> directive supports three path - *specifications: - * - * <!--#include virtual="path" --> Path is relative to web server root - * <!--#include abspath="path" --> Path is absolute or relative to the - * web server working dir - * <!--#include file="path" -->, Path is relative to current document - * <!--#include "path" --> - * - * The include directive may be used to include the contents of a file or - * the result of running a CGI script. - * - * The exec directive is used to execute - * a command on a server, and show command's output. Example: - * - * <!--#exec "ls -l" --> - * - * The call directive is a way to invoke a C handler from the HTML page. - * On each occurence of <!--#call COMMAND OPTIONAL_PARAMS> directive, - * Mongoose calls a registered event handler with MG_EV_SSI_CALL event, - * and event parameter will point to the COMMAND OPTIONAL_PARAMS string. - * An event handler can output any text, for example by calling - * `mg_printf()`. This is a flexible way of generating a web page on - * server side by calling a C event handler. Example: - * - * <!--#call foo --> ... <!--#call bar --> - * - * In the event handler: - * case MG_EV_SSI_CALL: { - * const char *param = (const char *) ev_data; - * if (strcmp(param, "foo") == 0) { - * mg_printf(c, "hello from foo"); - * } else if (strcmp(param, "bar") == 0) { - * mg_printf(c, "hello from bar"); - * } - * break; - * } - */ - const char *ssi_pattern; - - /* IP ACL. By default, NULL, meaning all IPs are allowed to connect */ - const char *ip_acl; - -#if MG_ENABLE_HTTP_URL_REWRITES - /* URL rewrites. - * - * Comma-separated list of `uri_pattern=url_file_or_directory_path` rewrites. - * When HTTP request is received, Mongoose constructs a file name from the - * requested URI by combining `document_root` and the URI. However, if the - * rewrite option is used and `uri_pattern` matches requested URI, then - * `document_root` is ignored. Instead, `url_file_or_directory_path` is used, - * which should be a full path name or a path relative to the web server's - * current working directory. It can also be an URI (http:// or https://) - * in which case mongoose will behave as a reverse proxy for that destination. - * - * Note that `uri_pattern`, as all Mongoose patterns, is a prefix pattern. - * - * If uri_pattern starts with `@` symbol, then Mongoose compares it with the - * HOST header of the request. If they are equal, Mongoose sets document root - * to `file_or_directory_path`, implementing virtual hosts support. - * Example: `@foo.com=/document/root/for/foo.com` - * - * If `uri_pattern` starts with `%` symbol, then Mongoose compares it with - * the listening port. If they match, then Mongoose issues a 301 redirect. - * For example, to redirect all HTTP requests to the - * HTTPS port, do `%80=https://my.site.com`. Note that the request URI is - * automatically appended to the redirect location. - */ - const char *url_rewrites; -#endif - - /* DAV document root. If NULL, DAV requests are going to fail. */ - const char *dav_document_root; - - /* - * DAV passwords file. If NULL, DAV requests are going to fail. - * If passwords file is set to "-", then DAV auth is disabled. - */ - const char *dav_auth_file; - - /* Glob pattern for the files to hide. */ - const char *hidden_file_pattern; - - /* Set to non-NULL to enable CGI, e.g. **.cgi$|**.php$" */ - const char *cgi_file_pattern; - - /* If not NULL, ignore CGI script hashbang and use this interpreter */ - const char *cgi_interpreter; - - /* - * Comma-separated list of Content-Type overrides for path suffixes, e.g. - * ".txt=text/plain; charset=utf-8,.c=text/plain" - */ - const char *custom_mime_types; - - /* - * Extra HTTP headers to add to each server response. - * Example: to enable CORS, set this to "Access-Control-Allow-Origin: *". - */ - const char *extra_headers; -}; - -/* - * Serves given HTTP request according to the `options`. - * - * Example code snippet: - * - * ```c - * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { - * struct http_message *hm = (struct http_message *) ev_data; - * struct mg_serve_http_opts opts = { .document_root = "/var/www" }; // C99 - * - * switch (ev) { - * case MG_EV_HTTP_REQUEST: - * mg_serve_http(nc, hm, opts); - * break; - * default: - * break; - * } - * } - * ``` - */ -void mg_serve_http(struct mg_connection *nc, struct http_message *hm, - struct mg_serve_http_opts opts); - -/* - * Serves a specific file with a given MIME type and optional extra headers. - * - * Example code snippet: - * - * ```c - * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { - * switch (ev) { - * case MG_EV_HTTP_REQUEST: { - * struct http_message *hm = (struct http_message *) ev_data; - * mg_http_serve_file(nc, hm, "file.txt", - * mg_mk_str("text/plain"), mg_mk_str("")); - * break; - * } - * ... - * } - * } - * ``` - */ -void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm, - const char *path, const struct mg_str mime_type, - const struct mg_str extra_headers); - -#if MG_ENABLE_HTTP_STREAMING_MULTIPART - -/* Callback prototype for `mg_file_upload_handler()`. */ -typedef struct mg_str (*mg_fu_fname_fn)(struct mg_connection *nc, - struct mg_str fname); - -/* - * File upload handler. - * This handler can be used to implement file uploads with minimum code. - * This handler will process MG_EV_HTTP_PART_* events and store file data into - * a local file. - * `local_name_fn` will be invoked with whatever name was provided by the client - * and will expect the name of the local file to open. A return value of NULL - * will abort file upload (client will get a "403 Forbidden" response). If - * non-null, the returned string must be heap-allocated and will be freed by - * the caller. - * Exception: it is ok to return the same string verbatim. - * - * Example: - * - * ```c - * struct mg_str upload_fname(struct mg_connection *nc, struct mg_str fname) { - * // Just return the same filename. Do not actually do this except in test! - * // fname is user-controlled and needs to be sanitized. - * return fname; - * } - * void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { - * switch (ev) { - * ... - * case MG_EV_HTTP_PART_BEGIN: - * case MG_EV_HTTP_PART_DATA: - * case MG_EV_HTTP_PART_END: - * mg_file_upload_handler(nc, ev, ev_data, upload_fname); - * break; - * } - * } - * ``` - */ -void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data, - mg_fu_fname_fn local_name_fn - MG_UD_ARG(void *user_data)); -#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ -#endif /* MG_ENABLE_FILESYSTEM */ - -/* - * Registers a callback for a specified http endpoint - * Note: if callback is registered it is called instead of the - * callback provided in mg_bind - * - * Example code snippet: - * - * ```c - * static void handle_hello1(struct mg_connection *nc, int ev, void *ev_data) { - * (void) ev; (void) ev_data; - * mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello1]"); - * nc->flags |= MG_F_SEND_AND_CLOSE; - * } - * - * static void handle_hello2(struct mg_connection *nc, int ev, void *ev_data) { - * (void) ev; (void) ev_data; - * mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello2]"); - * nc->flags |= MG_F_SEND_AND_CLOSE; - * } - * - * void init() { - * nc = mg_bind(&mgr, local_addr, cb1); - * mg_register_http_endpoint(nc, "/hello1", handle_hello1); - * mg_register_http_endpoint(nc, "/hello1/hello2", handle_hello2); - * } - * ``` - */ -void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path, - MG_CB(mg_event_handler_t handler, - void *user_data)); - -struct mg_http_endpoint_opts { - void *user_data; - /* Authorization domain (realm) */ - const char *auth_domain; - const char *auth_file; -}; - -void mg_register_http_endpoint_opt(struct mg_connection *nc, - const char *uri_path, - mg_event_handler_t handler, - struct mg_http_endpoint_opts opts); - -/* - * Authenticates a HTTP request against an opened password file. - * Returns 1 if authenticated, 0 otherwise. - */ -int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain, - FILE *fp); - -/* - * Authenticates given response params against an opened password file. - * Returns 1 if authenticated, 0 otherwise. - * - * It's used by mg_http_check_digest_auth(). - */ -int mg_check_digest_auth(struct mg_str method, struct mg_str uri, - struct mg_str username, struct mg_str cnonce, - struct mg_str response, struct mg_str qop, - struct mg_str nc, struct mg_str nonce, - struct mg_str auth_domain, FILE *fp); - -/* - * Sends buffer `buf` of size `len` to the client using chunked HTTP encoding. - * This function sends the buffer size as hex number + newline first, then - * the buffer itself, then the newline. For example, - * `mg_send_http_chunk(nc, "foo", 3)` will append the `3\r\nfoo\r\n` string - * to the `nc->send_mbuf` output IO buffer. - * - * NOTE: The HTTP header "Transfer-Encoding: chunked" should be sent prior to - * using this function. - * - * NOTE: do not forget to send an empty chunk at the end of the response, - * to tell the client that everything was sent. Example: - * - * ``` - * mg_printf_http_chunk(nc, "%s", "my response!"); - * mg_send_http_chunk(nc, "", 0); // Tell the client we're finished - * ``` - */ -void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len); - -/* - * Sends a printf-formatted HTTP chunk. - * Functionality is similar to `mg_send_http_chunk()`. - */ -void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...); - -/* - * Sends the response status line. - * If `extra_headers` is not NULL, then `extra_headers` are also sent - * after the response line. `extra_headers` must NOT end end with new line. - * Example: - * - * mg_send_response_line(nc, 200, "Access-Control-Allow-Origin: *"); - * - * Will result in: - * - * HTTP/1.1 200 OK\r\n - * Access-Control-Allow-Origin: *\r\n - */ -void mg_send_response_line(struct mg_connection *nc, int status_code, - const char *extra_headers); - -/* - * Sends an error response. If reason is NULL, the message will be inferred - * from the error code (if supported). - */ -void mg_http_send_error(struct mg_connection *nc, int code, const char *reason); - -/* - * Sends a redirect response. - * `status_code` should be either 301 or 302 and `location` point to the - * new location. - * If `extra_headers` is not empty, then `extra_headers` are also sent - * after the response line. `extra_headers` must NOT end end with new line. - * - * Example: - * - * mg_http_send_redirect(nc, 302, mg_mk_str("/login"), mg_mk_str(NULL)); - */ -void mg_http_send_redirect(struct mg_connection *nc, int status_code, - const struct mg_str location, - const struct mg_str extra_headers); - -/* - * Sends the response line and headers. - * This function sends the response line with the `status_code`, and - * automatically - * sends one header: either "Content-Length" or "Transfer-Encoding". - * If `content_length` is negative, then "Transfer-Encoding: chunked" header - * is sent, otherwise, "Content-Length" header is sent. - * - * NOTE: If `Transfer-Encoding` is `chunked`, then message body must be sent - * using `mg_send_http_chunk()` or `mg_printf_http_chunk()` functions. - * Otherwise, `mg_send()` or `mg_printf()` must be used. - * Extra headers could be set through `extra_headers`. Note `extra_headers` - * must NOT be terminated by a new line. - */ -void mg_send_head(struct mg_connection *n, int status_code, - int64_t content_length, const char *extra_headers); - -/* - * Sends a printf-formatted HTTP chunk, escaping HTML tags. - */ -void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...); - -#if MG_ENABLE_HTTP_URL_REWRITES -/* - * Proxies a given request to a given upstream http server. The path prefix - * in `mount` will be stripped of the path requested to the upstream server, - * e.g. if mount is /api and upstream is http://localhost:8001/foo - * then an incoming request to /api/bar will cause a request to - * http://localhost:8001/foo/bar - * - * EXPERIMENTAL API. Please use http_serve_http + url_rewrites if a static - * mapping is good enough. - */ -void mg_http_reverse_proxy(struct mg_connection *nc, - const struct http_message *hm, struct mg_str mount, - struct mg_str upstream); -#endif - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* MG_ENABLE_HTTP */ - -#endif /* CS_MONGOOSE_SRC_HTTP_SERVER_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http_client.h" -#endif -/* - * === Client API reference - */ - -#ifndef CS_MONGOOSE_SRC_HTTP_CLIENT_H_ -#define CS_MONGOOSE_SRC_HTTP_CLIENT_H_ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* - * Helper function that creates an outbound HTTP connection. - * - * `url` is the URL to fetch. It must be properly URL-encoded, e.g. have - * no spaces, etc. By default, `mg_connect_http()` sends the Connection and - * Host headers. `extra_headers` is an extra HTTP header to send, e.g. - * `"User-Agent: my-app\r\n"`. - * If `post_data` is NULL, then a GET request is created. Otherwise, a POST - * request is created with the specified POST data. Note that if the data being - * posted is a form submission, the `Content-Type` header should be set - * accordingly (see example below). - * - * Examples: - * - * ```c - * nc1 = mg_connect_http(mgr, ev_handler_1, "http://www.google.com", NULL, - * NULL); - * nc2 = mg_connect_http(mgr, ev_handler_1, "https://github.com", NULL, NULL); - * nc3 = mg_connect_http( - * mgr, ev_handler_1, "my_server:8000/form_submit/", - * "Content-Type: application/x-www-form-urlencoded\r\n", - * "var_1=value_1&var_2=value_2"); - * ``` - */ -struct mg_connection *mg_connect_http( - struct mg_mgr *mgr, - MG_CB(mg_event_handler_t event_handler, void *user_data), const char *url, - const char *extra_headers, const char *post_data); - -/* - * Helper function that creates an outbound HTTP connection. - * - * Mostly identical to mg_connect_http, but allows you to provide extra - *parameters - * (for example, SSL parameters) - */ -struct mg_connection *mg_connect_http_opt( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - struct mg_connect_opts opts, const char *url, const char *extra_headers, - const char *post_data); - -/* Creates digest authentication header for a client request. */ -int mg_http_create_digest_auth_header(char *buf, size_t buf_len, - const char *method, const char *uri, - const char *auth_domain, const char *user, - const char *passwd, const char *nonce); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* CS_MONGOOSE_SRC_HTTP_CLIENT_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_mqtt.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - * This software is dual-licensed: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. For the terms of this - * license, see . - * - * You are free to use this software under the terms of the GNU General - * Public License, but WITHOUT ANY WARRANTY; without even the implied - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * Alternatively, you can license this software under a commercial - * license, as set out in . - */ - -/* - * === MQTT API reference - */ - -#ifndef CS_MONGOOSE_SRC_MQTT_H_ -#define CS_MONGOOSE_SRC_MQTT_H_ - -/* Amalgamated: #include "mg_net.h" */ - -struct mg_mqtt_message { - int cmd; - int qos; - int len; /* message length in the IO buffer */ - struct mg_str topic; - struct mg_str payload; - - uint8_t connack_ret_code; /* connack */ - uint16_t message_id; /* puback */ - - /* connect */ - uint8_t protocol_version; - uint8_t connect_flags; - uint16_t keep_alive_timer; - struct mg_str protocol_name; - struct mg_str client_id; - struct mg_str will_topic; - struct mg_str will_message; - struct mg_str user_name; - struct mg_str password; -}; - -struct mg_mqtt_topic_expression { - const char *topic; - uint8_t qos; -}; - -struct mg_send_mqtt_handshake_opts { - unsigned char flags; /* connection flags */ - uint16_t keep_alive; - const char *will_topic; - const char *will_message; - const char *user_name; - const char *password; -}; - -/* mg_mqtt_proto_data should be in header to allow external access to it */ -struct mg_mqtt_proto_data { - uint16_t keep_alive; - double last_control_time; -}; - -/* Message types */ -#define MG_MQTT_CMD_CONNECT 1 -#define MG_MQTT_CMD_CONNACK 2 -#define MG_MQTT_CMD_PUBLISH 3 -#define MG_MQTT_CMD_PUBACK 4 -#define MG_MQTT_CMD_PUBREC 5 -#define MG_MQTT_CMD_PUBREL 6 -#define MG_MQTT_CMD_PUBCOMP 7 -#define MG_MQTT_CMD_SUBSCRIBE 8 -#define MG_MQTT_CMD_SUBACK 9 -#define MG_MQTT_CMD_UNSUBSCRIBE 10 -#define MG_MQTT_CMD_UNSUBACK 11 -#define MG_MQTT_CMD_PINGREQ 12 -#define MG_MQTT_CMD_PINGRESP 13 -#define MG_MQTT_CMD_DISCONNECT 14 - -/* MQTT event types */ -#define MG_MQTT_EVENT_BASE 200 -#define MG_EV_MQTT_CONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNECT) -#define MG_EV_MQTT_CONNACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNACK) -#define MG_EV_MQTT_PUBLISH (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBLISH) -#define MG_EV_MQTT_PUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBACK) -#define MG_EV_MQTT_PUBREC (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREC) -#define MG_EV_MQTT_PUBREL (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREL) -#define MG_EV_MQTT_PUBCOMP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBCOMP) -#define MG_EV_MQTT_SUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBSCRIBE) -#define MG_EV_MQTT_SUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBACK) -#define MG_EV_MQTT_UNSUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBSCRIBE) -#define MG_EV_MQTT_UNSUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBACK) -#define MG_EV_MQTT_PINGREQ (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGREQ) -#define MG_EV_MQTT_PINGRESP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGRESP) -#define MG_EV_MQTT_DISCONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_DISCONNECT) - -/* Message flags */ -#define MG_MQTT_RETAIN 0x1 -#define MG_MQTT_DUP 0x4 -#define MG_MQTT_QOS(qos) ((qos) << 1) -#define MG_MQTT_GET_QOS(flags) (((flags) &0x6) >> 1) -#define MG_MQTT_SET_QOS(flags, qos) (flags) = ((flags) & ~0x6) | ((qos) << 1) - -/* Connection flags */ -#define MG_MQTT_CLEAN_SESSION 0x02 -#define MG_MQTT_HAS_WILL 0x04 -#define MG_MQTT_WILL_RETAIN 0x20 -#define MG_MQTT_HAS_PASSWORD 0x40 -#define MG_MQTT_HAS_USER_NAME 0x80 -#define MG_MQTT_GET_WILL_QOS(flags) (((flags) &0x18) >> 3) -#define MG_MQTT_SET_WILL_QOS(flags, qos) \ - (flags) = ((flags) & ~0x18) | ((qos) << 3) - -/* CONNACK return codes */ -#define MG_EV_MQTT_CONNACK_ACCEPTED 0 -#define MG_EV_MQTT_CONNACK_UNACCEPTABLE_VERSION 1 -#define MG_EV_MQTT_CONNACK_IDENTIFIER_REJECTED 2 -#define MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE 3 -#define MG_EV_MQTT_CONNACK_BAD_AUTH 4 -#define MG_EV_MQTT_CONNACK_NOT_AUTHORIZED 5 - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* - * Attaches a built-in MQTT event handler to the given connection. - * - * The user-defined event handler will receive following extra events: - * - * - MG_EV_MQTT_CONNACK - * - MG_EV_MQTT_PUBLISH - * - MG_EV_MQTT_PUBACK - * - MG_EV_MQTT_PUBREC - * - MG_EV_MQTT_PUBREL - * - MG_EV_MQTT_PUBCOMP - * - MG_EV_MQTT_SUBACK - */ -void mg_set_protocol_mqtt(struct mg_connection *nc); - -/* Sends an MQTT handshake. */ -void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id); - -/* Sends an MQTT handshake with optional parameters. */ -void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id, - struct mg_send_mqtt_handshake_opts); - -/* Publishes a message to a given topic. */ -void mg_mqtt_publish(struct mg_connection *nc, const char *topic, - uint16_t message_id, int flags, const void *data, - size_t len); - -/* Subscribes to a bunch of topics. */ -void mg_mqtt_subscribe(struct mg_connection *nc, - const struct mg_mqtt_topic_expression *topics, - size_t topics_len, uint16_t message_id); - -/* Unsubscribes from a bunch of topics. */ -void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics, - size_t topics_len, uint16_t message_id); - -/* Sends a DISCONNECT command. */ -void mg_mqtt_disconnect(struct mg_connection *nc); - -/* Sends a CONNACK command with a given `return_code`. */ -void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code); - -/* Sends a PUBACK command with a given `message_id`. */ -void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id); - -/* Sends a PUBREC command with a given `message_id`. */ -void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id); - -/* Sends a PUBREL command with a given `message_id`. */ -void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id); - -/* Sends a PUBCOMP command with a given `message_id`. */ -void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id); - -/* - * Sends a SUBACK command with a given `message_id` - * and a sequence of granted QoSs. - */ -void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len, - uint16_t message_id); - -/* Sends a UNSUBACK command with a given `message_id`. */ -void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id); - -/* Sends a PINGREQ command. */ -void mg_mqtt_ping(struct mg_connection *nc); - -/* Sends a PINGRESP command. */ -void mg_mqtt_pong(struct mg_connection *nc); - -/* - * Extracts the next topic expression from a SUBSCRIBE command payload. - * - * The topic expression name will point to a string in the payload buffer. - * Returns the pos of the next topic expression or -1 when the list - * of topics is exhausted. - */ -int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg, - struct mg_str *topic, uint8_t *qos, int pos); - -/* - * Matches a topic against a topic expression - * - * Returns 1 if it matches; 0 otherwise. - */ -int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic); - -/* - * Same as `mg_mqtt_match_topic_expression()`, but takes `exp` as a - * NULL-terminated string. - */ -int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_MONGOOSE_SRC_MQTT_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_mqtt_server.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - * This software is dual-licensed: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. For the terms of this - * license, see . - * - * You are free to use this software under the terms of the GNU General - * Public License, but WITHOUT ANY WARRANTY; without even the implied - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * Alternatively, you can license this software under a commercial - * license, as set out in . - */ - -/* - * === MQTT Server API reference - */ - -#ifndef CS_MONGOOSE_SRC_MQTT_BROKER_H_ -#define CS_MONGOOSE_SRC_MQTT_BROKER_H_ - -#if MG_ENABLE_MQTT_BROKER - -/* Amalgamated: #include "common/queue.h" */ -/* Amalgamated: #include "mg_mqtt.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifndef MG_MQTT_MAX_SESSION_SUBSCRIPTIONS -#define MG_MQTT_MAX_SESSION_SUBSCRIPTIONS 512 -#endif - -struct mg_mqtt_broker; - -/* MQTT session (Broker side). */ -struct mg_mqtt_session { - struct mg_mqtt_broker *brk; /* Broker */ - LIST_ENTRY(mg_mqtt_session) link; /* mg_mqtt_broker::sessions linkage */ - struct mg_connection *nc; /* Connection with the client */ - size_t num_subscriptions; /* Size of `subscriptions` array */ - void *user_data; /* User data */ - struct mg_mqtt_topic_expression *subscriptions; -}; - -/* MQTT broker. */ -struct mg_mqtt_broker { - LIST_HEAD(_mg_sesshead, mg_mqtt_session) sessions; /* Session list */ - void *user_data; /* User data */ -}; - -/* Initialises a MQTT broker. */ -void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data); - -/* - * Processes a MQTT broker message. - * - * The listening connection expects a pointer to an initialised - * `mg_mqtt_broker` structure in the `user_data` field. - * - * Basic usage: - * - * ```c - * mg_mqtt_broker_init(&brk, NULL); - * - * if ((nc = mg_bind(&mgr, address, mg_mqtt_broker)) == NULL) { - * // fail; - * } - * nc->user_data = &brk; - * ``` - * - * New incoming connections will receive a `mg_mqtt_session` structure - * in the connection `user_data`. The original `user_data` will be stored - * in the `user_data` field of the session structure. This allows the user - * handler to store user data before `mg_mqtt_broker` creates the session. - * - * Since only the MG_EV_ACCEPT message is processed by the listening socket, - * for most events the `user_data` will thus point to a `mg_mqtt_session`. - */ -void mg_mqtt_broker(struct mg_connection *brk, int ev, void *data); - -/* - * Iterates over all MQTT session connections. Example: - * - * ```c - * struct mg_mqtt_session *s; - * for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) { - * // Do something - * } - * ``` - */ -struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk, - struct mg_mqtt_session *s); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* MG_ENABLE_MQTT_BROKER */ -#endif /* CS_MONGOOSE_SRC_MQTT_BROKER_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_dns.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* - * === DNS API reference - */ - -#ifndef CS_MONGOOSE_SRC_DNS_H_ -#define CS_MONGOOSE_SRC_DNS_H_ - -/* Amalgamated: #include "mg_net.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#define MG_DNS_A_RECORD 0x01 /* Lookup IP address */ -#define MG_DNS_CNAME_RECORD 0x05 /* Lookup CNAME */ -#define MG_DNS_PTR_RECORD 0x0c /* Lookup PTR */ -#define MG_DNS_TXT_RECORD 0x10 /* Lookup TXT */ -#define MG_DNS_AAAA_RECORD 0x1c /* Lookup IPv6 address */ -#define MG_DNS_SRV_RECORD 0x21 /* Lookup SRV */ -#define MG_DNS_MX_RECORD 0x0f /* Lookup mail server for domain */ -#define MG_DNS_ANY_RECORD 0xff -#define MG_DNS_NSEC_RECORD 0x2f - -#define MG_MAX_DNS_QUESTIONS 32 -#define MG_MAX_DNS_ANSWERS 32 - -#define MG_DNS_MESSAGE 100 /* High-level DNS message event */ - -enum mg_dns_resource_record_kind { - MG_DNS_INVALID_RECORD = 0, - MG_DNS_QUESTION, - MG_DNS_ANSWER -}; - -/* DNS resource record. */ -struct mg_dns_resource_record { - struct mg_str name; /* buffer with compressed name */ - int rtype; - int rclass; - int ttl; - enum mg_dns_resource_record_kind kind; - struct mg_str rdata; /* protocol data (can be a compressed name) */ -}; - -/* DNS message (request and response). */ -struct mg_dns_message { - struct mg_str pkt; /* packet body */ - uint16_t flags; - uint16_t transaction_id; - int num_questions; - int num_answers; - struct mg_dns_resource_record questions[MG_MAX_DNS_QUESTIONS]; - struct mg_dns_resource_record answers[MG_MAX_DNS_ANSWERS]; -}; - -struct mg_dns_resource_record *mg_dns_next_record( - struct mg_dns_message *msg, int query, struct mg_dns_resource_record *prev); - -/* - * Parses the record data from a DNS resource record. - * - * - A: struct in_addr *ina - * - AAAA: struct in6_addr *ina - * - CNAME: char buffer - * - * Returns -1 on error. - * - * TODO(mkm): MX - */ -int mg_dns_parse_record_data(struct mg_dns_message *msg, - struct mg_dns_resource_record *rr, void *data, - size_t data_len); - -/* - * Sends a DNS query to the remote end. - */ -void mg_send_dns_query(struct mg_connection *nc, const char *name, - int query_type); - -/* - * Inserts a DNS header to an IO buffer. - * - * Returns the number of bytes inserted. - */ -int mg_dns_insert_header(struct mbuf *io, size_t pos, - struct mg_dns_message *msg); - -/* - * Appends already encoded questions from an existing message. - * - * This is useful when generating a DNS reply message which includes - * all question records. - * - * Returns the number of appended bytes. - */ -int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg); - -/* - * Encodes and appends a DNS resource record to an IO buffer. - * - * The record metadata is taken from the `rr` parameter, while the name and data - * are taken from the parameters, encoded in the appropriate format depending on - * record type and stored in the IO buffer. The encoded values might contain - * offsets within the IO buffer. It's thus important that the IO buffer doesn't - * get trimmed while a sequence of records are encoded while preparing a DNS - * reply. - * - * This function doesn't update the `name` and `rdata` pointers in the `rr` - * struct because they might be invalidated as soon as the IO buffer grows - * again. - * - * Returns the number of bytes appended or -1 in case of error. - */ -int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr, - const char *name, size_t nlen, const void *rdata, - size_t rlen); - -/* - * Encodes a DNS name. - */ -int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len); - -/* Low-level: parses a DNS response. */ -int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg); - -/* - * Uncompresses a DNS compressed name. - * - * The containing DNS message is required because of the compressed encoding - * and reference suffixes present elsewhere in the packet. - * - * If the name is less than `dst_len` characters long, the remainder - * of `dst` is terminated with `\0` characters. Otherwise, `dst` is not - * terminated. - * - * If `dst_len` is 0 `dst` can be NULL. - * Returns the uncompressed name length. - */ -size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name, - char *dst, int dst_len); - -/* - * Attaches a built-in DNS event handler to the given listening connection. - * - * The DNS event handler parses the incoming UDP packets, treating them as DNS - * requests. If an incoming packet gets successfully parsed by the DNS event - * handler, a user event handler will receive an `MG_DNS_REQUEST` event, with - * `ev_data` pointing to the parsed `struct mg_dns_message`. - * - * See - * [captive_dns_server](https://github.com/cesanta/mongoose/tree/master/examples/captive_dns_server) - * example on how to handle DNS request and send DNS reply. - */ -void mg_set_protocol_dns(struct mg_connection *nc); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* CS_MONGOOSE_SRC_DNS_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_dns_server.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* - * === DNS server API reference - * - * Disabled by default; enable with `-DMG_ENABLE_DNS_SERVER`. - */ - -#ifndef CS_MONGOOSE_SRC_DNS_SERVER_H_ -#define CS_MONGOOSE_SRC_DNS_SERVER_H_ - -#if MG_ENABLE_DNS_SERVER - -/* Amalgamated: #include "mg_dns.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#define MG_DNS_SERVER_DEFAULT_TTL 3600 - -struct mg_dns_reply { - struct mg_dns_message *msg; - struct mbuf *io; - size_t start; -}; - -/* - * Creates a DNS reply. - * - * The reply will be based on an existing query message `msg`. - * The query body will be appended to the output buffer. - * "reply + recursion allowed" will be added to the message flags and the - * message's num_answers will be set to 0. - * - * Answer records can be appended with `mg_dns_send_reply` or by lower - * level function defined in the DNS API. - * - * In order to send a reply use `mg_dns_send_reply`. - * It's possible to use a connection's send buffer as reply buffer, - * and it will work for both UDP and TCP connections. - * - * Example: - * - * ```c - * reply = mg_dns_create_reply(&nc->send_mbuf, msg); - * for (i = 0; i < msg->num_questions; i++) { - * rr = &msg->questions[i]; - * if (rr->rtype == MG_DNS_A_RECORD) { - * mg_dns_reply_record(&reply, rr, 3600, &dummy_ip_addr, 4); - * } - * } - * mg_dns_send_reply(nc, &reply); - * ``` - */ -struct mg_dns_reply mg_dns_create_reply(struct mbuf *io, - struct mg_dns_message *msg); - -/* - * Appends a DNS reply record to the IO buffer and to the DNS message. - * - * The message's num_answers field will be incremented. It's the caller's duty - * to ensure num_answers is properly initialised. - * - * Returns -1 on error. - */ -int mg_dns_reply_record(struct mg_dns_reply *reply, - struct mg_dns_resource_record *question, - const char *name, int rtype, int ttl, const void *rdata, - size_t rdata_len); - -/* - * Sends a DNS reply through a connection. - * - * The DNS data is stored in an IO buffer pointed by reply structure in `r`. - * This function mutates the content of that buffer in order to ensure that - * the DNS header reflects the size and flags of the message, that might have - * been updated either with `mg_dns_reply_record` or by direct manipulation of - * `r->message`. - * - * Once sent, the IO buffer will be trimmed unless the reply IO buffer - * is the connection's send buffer and the connection is not in UDP mode. - */ -void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* MG_ENABLE_DNS_SERVER */ -#endif /* CS_MONGOOSE_SRC_DNS_SERVER_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_resolv.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* - * === API reference - */ - -#ifndef CS_MONGOOSE_SRC_RESOLV_H_ -#define CS_MONGOOSE_SRC_RESOLV_H_ - -/* Amalgamated: #include "mg_dns.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -enum mg_resolve_err { - MG_RESOLVE_OK = 0, - MG_RESOLVE_NO_ANSWERS = 1, - MG_RESOLVE_EXCEEDED_RETRY_COUNT = 2, - MG_RESOLVE_TIMEOUT = 3 -}; - -typedef void (*mg_resolve_callback_t)(struct mg_dns_message *dns_message, - void *user_data, enum mg_resolve_err); - -/* Options for `mg_resolve_async_opt`. */ -struct mg_resolve_async_opts { - const char *nameserver; - int max_retries; /* defaults to 2 if zero */ - int timeout; /* in seconds; defaults to 5 if zero */ - int accept_literal; /* pseudo-resolve literal ipv4 and ipv6 addrs */ - int only_literal; /* only resolves literal addrs; sync cb invocation */ - struct mg_connection **dns_conn; /* return DNS connection */ -}; - -/* See `mg_resolve_async_opt()` */ -int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query, - mg_resolve_callback_t cb, void *data); - -/* Set default DNS server */ -void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver); - -/* - * Resolved a DNS name asynchronously. - * - * Upon successful resolution, the user callback will be invoked - * with the full DNS response message and a pointer to the user's - * context `data`. - * - * In case of timeout while performing the resolution the callback - * will receive a NULL `msg`. - * - * The DNS answers can be extracted with `mg_next_record` and - * `mg_dns_parse_record_data`: - * - * [source,c] - * ---- - * struct in_addr ina; - * struct mg_dns_resource_record *rr = mg_next_record(msg, MG_DNS_A_RECORD, - * NULL); - * mg_dns_parse_record_data(msg, rr, &ina, sizeof(ina)); - * ---- - */ -int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query, - mg_resolve_callback_t cb, void *data, - struct mg_resolve_async_opts opts); - -/* - * Resolve a name from `/etc/hosts`. - * - * Returns 0 on success, -1 on failure. - */ -int mg_resolve_from_hosts_file(const char *host, union socket_address *usa); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* CS_MONGOOSE_SRC_RESOLV_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_coap.h" -#endif -/* - * Copyright (c) 2015 Cesanta Software Limited - * All rights reserved - * This software is dual-licensed: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. For the terms of this - * license, see . - * - * You are free to use this software under the terms of the GNU General - * Public License, but WITHOUT ANY WARRANTY; without even the implied - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * Alternatively, you can license this software under a commercial - * license, as set out in . - */ - -/* - * === CoAP API reference - * - * CoAP message format: - * - * ``` - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - * |Ver| T | TKL | Code | Message ID | Token (if any, TKL bytes) ... - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - * | Options (if any) ... |1 1 1 1 1 1 1 1| Payload (if any) ... - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - * ``` - */ - -#ifndef CS_MONGOOSE_SRC_COAP_H_ -#define CS_MONGOOSE_SRC_COAP_H_ - -#if MG_ENABLE_COAP - -#define MG_COAP_MSG_TYPE_FIELD 0x2 -#define MG_COAP_CODE_CLASS_FIELD 0x4 -#define MG_COAP_CODE_DETAIL_FIELD 0x8 -#define MG_COAP_MSG_ID_FIELD 0x10 -#define MG_COAP_TOKEN_FIELD 0x20 -#define MG_COAP_OPTIOMG_FIELD 0x40 -#define MG_COAP_PAYLOAD_FIELD 0x80 - -#define MG_COAP_ERROR 0x10000 -#define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000) -#define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000) -#define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000) -#define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000) - -#define MG_COAP_MSG_CON 0 -#define MG_COAP_MSG_NOC 1 -#define MG_COAP_MSG_ACK 2 -#define MG_COAP_MSG_RST 3 -#define MG_COAP_MSG_MAX 3 - -#define MG_COAP_CODECLASS_REQUEST 0 -#define MG_COAP_CODECLASS_RESP_OK 2 -#define MG_COAP_CODECLASS_CLIENT_ERR 4 -#define MG_COAP_CODECLASS_SRV_ERR 5 - -#define MG_COAP_EVENT_BASE 300 -#define MG_EV_COAP_CON (MG_COAP_EVENT_BASE + MG_COAP_MSG_CON) -#define MG_EV_COAP_NOC (MG_COAP_EVENT_BASE + MG_COAP_MSG_NOC) -#define MG_EV_COAP_ACK (MG_COAP_EVENT_BASE + MG_COAP_MSG_ACK) -#define MG_EV_COAP_RST (MG_COAP_EVENT_BASE + MG_COAP_MSG_RST) - -/* - * CoAP options. - * Use mg_coap_add_option and mg_coap_free_options - * for creation and destruction. - */ -struct mg_coap_option { - struct mg_coap_option *next; - uint32_t number; - struct mg_str value; -}; - -/* CoAP message. See RFC 7252 for details. */ -struct mg_coap_message { - uint32_t flags; - uint8_t msg_type; - uint8_t code_class; - uint8_t code_detail; - uint16_t msg_id; - struct mg_str token; - struct mg_coap_option *options; - struct mg_str payload; - struct mg_coap_option *optiomg_tail; -}; - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* Sets CoAP protocol handler - triggers CoAP specific events. */ -int mg_set_protocol_coap(struct mg_connection *nc); - -/* - * Adds a new option to mg_coap_message structure. - * Returns pointer to the newly created option. - * Note: options must be freed by using mg_coap_free_options - */ -struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm, - uint32_t number, char *value, - size_t len); - -/* - * Frees the memory allocated for options. - * If the cm parameter doesn't contain any option it does nothing. - */ -void mg_coap_free_options(struct mg_coap_message *cm); - -/* - * Composes a CoAP message from `mg_coap_message` - * and sends it into `nc` connection. - * Returns 0 on success. On error, it is a bitmask: - * - * - `#define MG_COAP_ERROR 0x10000` - * - `#define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000)` - * - `#define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000)` - * - `#define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000)` - * - `#define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000)` - */ -uint32_t mg_coap_send_message(struct mg_connection *nc, - struct mg_coap_message *cm); - -/* - * Composes CoAP acknowledgement from `mg_coap_message` - * and sends it into `nc` connection. - * Return value: see `mg_coap_send_message()` - */ -uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id); - -/* - * Parses CoAP message and fills mg_coap_message and returns cm->flags. - * This is a helper function. - * - * NOTE: usually CoAP works over UDP, so lack of data means format error. - * But, in theory, it is possible to use CoAP over TCP (according to RFC) - * - * The caller has to check results and treat COAP_NOT_ENOUGH_DATA according to - * underlying protocol: - * - * - in case of UDP COAP_NOT_ENOUGH_DATA means COAP_FORMAT_ERROR, - * - in case of TCP client can try to receive more data - * - * Return value: see `mg_coap_send_message()` - */ -uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm); - -/* - * Composes CoAP message from mg_coap_message structure. - * This is a helper function. - * Return value: see `mg_coap_send_message()` - */ -uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* MG_ENABLE_COAP */ - -#endif /* CS_MONGOOSE_SRC_COAP_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_sntp.h" -#endif -/* - * Copyright (c) 2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_MONGOOSE_SRC_SNTP_H_ -#define CS_MONGOOSE_SRC_SNTP_H_ - -#if MG_ENABLE_SNTP - -#define MG_SNTP_EVENT_BASE 500 - -/* - * Received reply from time server. Event handler parameter contains - * pointer to mg_sntp_message structure - */ -#define MG_SNTP_REPLY (MG_SNTP_EVENT_BASE + 1) - -/* Received malformed SNTP packet */ -#define MG_SNTP_MALFORMED_REPLY (MG_SNTP_EVENT_BASE + 2) - -/* Failed to get time from server (timeout etc) */ -#define MG_SNTP_FAILED (MG_SNTP_EVENT_BASE + 3) - -struct mg_sntp_message { - /* if server sends this flags, user should not send requests to it */ - int kiss_of_death; - /* usual mg_time */ - double time; -}; - -/* Establishes connection to given sntp server */ -struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, - MG_CB(mg_event_handler_t event_handler, - void *user_data), - const char *sntp_server_name); - -/* Sends time request to given connection */ -void mg_sntp_send_request(struct mg_connection *c); - -/* - * Helper function - * Establishes connection to time server, tries to send request - * repeats sending SNTP_ATTEMPTS times every SNTP_TIMEOUT sec - * (if needed) - * See sntp_client example - */ -struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr, - mg_event_handler_t event_handler, - const char *sntp_server_name); - -#endif - -#endif /* CS_MONGOOSE_SRC_SNTP_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_socks.h" -#endif -/* - * Copyright (c) 2017 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_MONGOOSE_SRC_SOCKS_H_ -#define CS_MONGOOSE_SRC_SOCKS_H_ - -#if MG_ENABLE_SOCKS - -#define MG_SOCKS_VERSION 5 - -#define MG_SOCKS_HANDSHAKE_DONE MG_F_USER_1 -#define MG_SOCKS_CONNECT_DONE MG_F_USER_2 - -/* SOCKS5 handshake methods */ -enum mg_socks_handshake_method { - MG_SOCKS_HANDSHAKE_NOAUTH = 0, /* Handshake method - no authentication */ - MG_SOCKS_HANDSHAKE_GSSAPI = 1, /* Handshake method - GSSAPI auth */ - MG_SOCKS_HANDSHAKE_USERPASS = 2, /* Handshake method - user/password auth */ - MG_SOCKS_HANDSHAKE_FAILURE = 0xff, /* Handshake method - failure */ -}; - -/* SOCKS5 commands */ -enum mg_socks_command { - MG_SOCKS_CMD_CONNECT = 1, /* Command: CONNECT */ - MG_SOCKS_CMD_BIND = 2, /* Command: BIND */ - MG_SOCKS_CMD_UDP_ASSOCIATE = 3, /* Command: UDP ASSOCIATE */ -}; - -/* SOCKS5 address types */ -enum mg_socks_address_type { - MG_SOCKS_ADDR_IPV4 = 1, /* Address type: IPv4 */ - MG_SOCKS_ADDR_DOMAIN = 3, /* Address type: Domain name */ - MG_SOCKS_ADDR_IPV6 = 4, /* Address type: IPv6 */ -}; - -/* SOCKS5 response codes */ -enum mg_socks_response { - MG_SOCKS_SUCCESS = 0, /* Response: success */ - MG_SOCKS_FAILURE = 1, /* Response: failure */ - MG_SOCKS_NOT_ALLOWED = 2, /* Response: connection not allowed */ - MG_SOCKS_NET_UNREACHABLE = 3, /* Response: network unreachable */ - MG_SOCKS_HOST_UNREACHABLE = 4, /* Response: network unreachable */ - MG_SOCKS_CONN_REFUSED = 5, /* Response: network unreachable */ - MG_SOCKS_TTL_EXPIRED = 6, /* Response: network unreachable */ - MG_SOCKS_CMD_NOT_SUPPORTED = 7, /* Response: network unreachable */ - MG_SOCKS_ADDR_NOT_SUPPORTED = 8, /* Response: network unreachable */ -}; - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* Turn the connection into the SOCKS server */ -void mg_set_protocol_socks(struct mg_connection *c); - -/* Create socks tunnel for the client connection */ -struct mg_iface *mg_socks_mk_iface(struct mg_mgr *, const char *proxy_addr); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif -#endif diff --git a/util/websocket.c b/util/websocket.c deleted file mode 100644 index 4e74075..0000000 --- a/util/websocket.c +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#include "mongoose.h" - -static sig_atomic_t s_signal_received = 0; -static const char *s_http_port = "8000"; -static struct mg_serve_http_opts s_http_server_opts; -static char server_pwd[100]; -static struct mg_connection *supernode_client = NULL; - -static void signal_handler(int sig_num) { - signal(sig_num, signal_handler); // Reinstantiate signal handler - s_signal_received = sig_num; -} - -//Display Message in console/terminal -static void display(struct mg_connection *nc, char type[25]){ - char addr[32]; - mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); - printf("%s\t%s\n", addr, type); -} - -//Broadcast incoming message (from nc to all) -static void broadcast(struct mg_connection *nc, const struct mg_str msg) { - char addr[32]; - mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); - printf("%s\tBroadcast\t[%d]\n", addr, (int)msg.len); - struct mg_connection *c; - for (c = mg_next(nc->mgr, NULL); c != NULL; c = mg_next(nc->mgr, c)) { - if (c == nc) continue; /* Don't send to the sender. */ - mg_send_websocket_frame(c, WEBSOCKET_OP_TEXT, msg.p, msg.len); - } -} - -//Unicast message (to nc) -static void unicast(struct mg_connection *nc, const struct mg_str msg) { - char addr[32]; - mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); - printf("%s\tUnicast\t[%d]\n", addr, (int)msg.len); - if(nc != NULL) - mg_send_websocket_frame(nc, WEBSOCKET_OP_TEXT, msg.p, msg.len); -} - -//Forward message (from nc to supernode) -static void unicast_forward(struct mg_connection *nc, const struct mg_str msg) { - char addr[32]; - mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); - printf("%s\tForward\t[%d]\n", addr, (int)msg.len); - if(supernode_client != NULL) - mg_send_websocket_frame(supernode_client, WEBSOCKET_OP_TEXT, msg.p, msg.len); - else - printf("SuperNode client is offline!\n"); -} - -//Request message (from nc to supernode) -static void unicast_request(struct mg_connection *nc, const struct mg_str msg) { - if(supernode_client == NULL){ - printf("SuperNode client is offline!\n"); - return; - } - char addr[32], buf[500]; - mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); - printf("%s\tRequest\t[%d]\n", addr, (int)msg.len-1); - snprintf(buf, sizeof(buf), "?%s %.*s", addr, (int) msg.len-1, msg.p+1); - mg_send_websocket_frame(supernode_client, WEBSOCKET_OP_TEXT, buf, strlen(buf)); -} - -//Reply message (from supernode) -static void unicast_reply(const struct mg_str msg) { - if(supernode_client == NULL){ - printf("SuperNode client is offline!\n"); - return; - } - //Get receiver address from msg - char receiverAddr[32]; - int index = (int)(strchr(msg.p, ' ') - msg.p) + 1; - snprintf(receiverAddr, sizeof(receiverAddr), "%.*s", index - 1, msg.p); - printf("%s\tReply\t[%d]\n", receiverAddr, (int)msg.len - index); - //send msg to receiver - struct mg_connection *c; - for (c = mg_next(supernode_client->mgr, NULL); c != NULL; c = mg_next(supernode_client->mgr, c)) { - char addr[32]; - mg_sock_addr_to_str(&c->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); - if (!strcmp(receiverAddr,addr)) - mg_send_websocket_frame(c, WEBSOCKET_OP_TEXT, msg.p + index, msg.len - index); - } -} - -static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { - switch (ev) { - case MG_EV_WEBSOCKET_HANDSHAKE_DONE: { - /*New websocket connection*/ - display(nc, "+Connected+"); - break; - } - case MG_EV_WEBSOCKET_FRAME: { - struct websocket_message *wm = (struct websocket_message *) ev_data; - /* New websocket message*/ - struct mg_str d = {(char *) wm->data, wm->size}; - if (d.p[0] == '$'){ - char pass[100]; - snprintf(pass, sizeof(pass), "%.*s",(int)d.len-1, &d.p[1]); - if(!strcmp(pass,server_pwd)){ - if(supernode_client!=NULL) - unicast(supernode_client,mg_mk_str("$Another login is encountered! Please close/refresh this window")); - supernode_client = nc; - unicast(supernode_client,mg_mk_str("$Access Granted!")); - display(nc, "*Became SuperNode*"); - }else - unicast(nc,mg_mk_str("$Access Denied!")); - } - else if (d.p[0] == '?') - unicast_request(nc,d); - else if (nc == supernode_client) - unicast_reply(d); - else - unicast_forward(nc,d); - break; - } - case MG_EV_HTTP_REQUEST: { - mg_serve_http(nc, (struct http_message *) ev_data, s_http_server_opts); - break; - } - case MG_EV_CLOSE: { - /* Disconnect websocket*/ - if(nc == supernode_client){ - supernode_client = NULL; - display(nc,"!SuperNode Disconnected!"); - }else - display(nc, "-Disconnected-"); - break; - } - } -} - -int main(int argc, char** argv) { - - if(argc<=1){ - printf("Enter server password : "); - scanf("%s",server_pwd); - } - else - strcpy(server_pwd,argv[1]); - - struct mg_mgr mgr; - struct mg_connection *nc; - - signal(SIGTERM, signal_handler); - signal(SIGINT, signal_handler); - setvbuf(stdout, NULL, _IOLBF, 0); - setvbuf(stderr, NULL, _IOLBF, 0); - - mg_mgr_init(&mgr, NULL); - - nc = mg_bind(&mgr, s_http_port, ev_handler); - mg_set_protocol_http_websocket(nc); - s_http_server_opts.document_root = "."; // Serve current directory - s_http_server_opts.enable_directory_listing = "no"; - - printf("Started on port %s\n", s_http_port); - while (s_signal_received == 0) { - mg_mgr_poll(&mgr, 200); - } - mg_mgr_free(&mgr); - - return 0; -} From 9da3168f45720f4616d1eb08e23ce7ec905374d5 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 6 Oct 2019 02:52:34 +0530 Subject: [PATCH 011/289] Improved Read Data from blockchain via API Replaced floBlockchainAPI's readSentData, readDataPattern, readSentDataPattern, readDataContains, readSentDataContains with a improved version 'readData' readData is Promisfied function that reads and resolves floData from blockchain using API Arguments : addr - address from which the floData should be read options - (optional object, default = {}) Options : limit - maximum number of filtered data (default = 1000, negative = no limit) ignoreOld - ignore old txs (default = 0) sentOnly - filters only sent data pattern - filters data that starts with a pattern contains - filters data that contains a string filter - custom filter funtion for floData (eg . filter: d => {return d[0] == '$'}) --- index.html | 110 ++++++++++++++++++----------------------------------- 1 file changed, 36 insertions(+), 74 deletions(-) diff --git a/index.html b/index.html index a78a65d..9786771 100644 --- a/index.html +++ b/index.html @@ -5114,81 +5114,43 @@ }); }, - //Read Data Sent from Address (if limit is specified, only return newest sent data) - readSentData: function (addr, limit = 0) { - return new Promise((resolve, reject) => { - this.readAllTxs(addr).then(items => { - var filteredItems = []; - if (limit <= 0) limit = items.length; - for (i = 0; i < items.length && filteredItems.length < limit; i++) - if (items[i].vin[0].addr === addr) - filteredItems.push(items[i].floData); - console.log(filteredItems); - resolve(filteredItems); + /*Read flo Data from txs of given Address + options can be used to filter data + limit : maximum number of filtered data (default = 1000, negative = no limit) + ignoreOld : ignore old txs (default = 0) + sentOnly : filters only sent data + pattern : filters data that starts with a pattern + contains : filters data that contains a string + filter : custom filter funtion for floData (eg . filter: d => {return d[0] == '$'}) + */ + readData: function(addr,options = {}){ + options.limit = options.limit | 1000 + options.ignoreOld = options.ignoreOld | 0 + return new Promise((resolve, reject) => { + this.promisedAJAX("GET", `api/addrs/${addr}/txs?from=0&to=1`).then(response => { + var newItems = JSON.parse(response).totalItems - options.ignoreOld; + this.promisedAJAX("GET", `api/addrs/${addr}/txs?from=0&to=${newItems*2}`).then(response => { + response = JSON.parse(response) + if (options.limit <= 0) + options.limit = response.items.length; + var filteredData = []; + for (i = 0; i < (response.totalItems - options.ignoreOld) && filteredData.length < options.limit; i++){ + if(options.sentOnly && response.items[i].vin[0].addr !== addr) + continue; + if(options.pattern && !response.items[i].floData.startsWith(options.pattern, 0) && !response.items[i].floData.startsWith(options.pattern, 2)) + continue; + if(options.contains && !response.items[i].floData.includes(options.contains)) + continue; + if(options.filter && !options.filter(response.items[i].floData)) + continue; + filteredData.push(response.items[i].floData); + } + resolve(filteredData); + }).catch(error => { + reject(error); + }); }).catch(error => { - reject(error) - }); - }); - }, - - //Read newest 'limit' Data matching 'pattern' - readDataPattern: function (addr, pattern, jsonType = false, limit = 1000) { - return new Promise((resolve, reject) => { - this.readAllTxs(addr).then(items => { - var filteredItems = []; - var pos = (jsonType ? 2 : 0); - for (i = 0; i < items.length && filteredItems.length < limit; i++) - if (items[i].floData.startsWith(pattern, pos)) - filteredItems.push(items[i].floData); - resolve(filteredItems); - }).catch(error => { - reject(error) - }); - }); - }, - - //Read newest 'limit' Data Sent from Address and matching 'pattern' - readSentDataPattern: function (addr, pattern, jsonType = false, limit = 1000) { - return new Promise((resolve, reject) => { - this.readAllTxs(addr).then(items => { - var filteredItems = []; - var pos = (jsonType ? 2 : 0); - for (i = 0; i < items.length && filteredItems.length < limit; i++) - if (items[i].vin[0].addr === addr && items[i].floData.startsWith(pattern, pos)) - filteredItems.push(items[i].floData); - resolve(filteredItems); - }).catch(error => { - reject(error) - }); - }); - }, - - //Read newest 'limit' Data containing 'keyword' - readDataContains: function (addr, keyword, limit = 1000) { - return new Promise((resolve, reject) => { - this.readAllTxs(addr).then(items => { - var filteredItems = []; - for (i = 0; i < items.length && filteredItems.length < limit; i++) - if (items[i].floData.includes(keyword)) - filteredItems.push(items[i].floData); - resolve(filteredItems); - }).catch(error => { - reject(error) - }); - }); - }, - - //Read newest 'limit' Data Sent from Address and containing 'keyword' - readSentDataContains: function (addr, keyword, limit = 1000) { - return new Promise((resolve, reject) => { - this.readAllTxs(addr).then(items => { - var filteredItems = []; - for (i = 0; i < items.length && filteredItems.length < limit; i++) - if (items[i].vin[0].addr === addr && items[i].floData.includes(keyword)) - filteredItems.push(items[i].floData); - resolve(filteredItems); - }).catch(error => { - reject(error) + reject(error); }); }); } From 68472cad568f22186a65d4e97b3ee99ed143d849 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 6 Oct 2019 03:15:18 +0530 Subject: [PATCH 012/289] floBlockchainAPI.readData will now return a object with totalTxs and data --- index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 9786771..a9abfd4 100644 --- a/index.html +++ b/index.html @@ -5117,7 +5117,7 @@ /*Read flo Data from txs of given Address options can be used to filter data limit : maximum number of filtered data (default = 1000, negative = no limit) - ignoreOld : ignore old txs (default = 0) + ignoreOld : ignore old txs (default = 0) sentOnly : filters only sent data pattern : filters data that starts with a pattern contains : filters data that contains a string @@ -5145,7 +5145,7 @@ continue; filteredData.push(response.items[i].floData); } - resolve(filteredData); + resolve({totalTxs:response.totalItems , data:filteredData}); }).catch(error => { reject(error); }); From ed59eeeb65a55315a7393d6c617f031b7a4c81fa Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 6 Oct 2019 03:51:13 +0530 Subject: [PATCH 013/289] Added removeData in compactIDB --- index.html | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/index.html b/index.html index a9abfd4..84c76e6 100644 --- a/index.html +++ b/index.html @@ -5363,6 +5363,19 @@ }); }, + removeData: function (obsName, key, dbName = this.dbName) { + return new Promise((resolve, reject) => { + this.openDB(dbName).then(db => { + var obs = db.transaction(obsName, "readwrite").objectStore(obsName); + let delReq = obs.delete(key); + delReq.onsuccess = (evt) => resolve(`Removed Data ${key}`); + delReq.onerror = (evt) => reject( + `Remove data unsuccessful [${evt.target.error.name}] ${evt.target.error.message}`); + db.close(); + }).catch(error => reject(error)); + }); + }, + readData: function (obsName, key, dbName = this.dbName) { return new Promise((resolve, reject) => { this.openDB(dbName).then(db => { From b1c6d8c153e1cba2fede3aeeca4d61940fb72ef2 Mon Sep 17 00:00:00 2001 From: Sai Raj <39055732+sairajzero@users.noreply.github.com> Date: Sun, 13 Oct 2019 03:04:28 +0530 Subject: [PATCH 014/289] fixing broadcastTx not been asynchronized call --- index.html | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/index.html b/index.html index 84c76e6..251d501 100644 --- a/index.html +++ b/index.html @@ -5070,8 +5070,7 @@ reject("Empty Signature"); else { var params = `{"rawtx":"${signedTxHash}"}`; - var result; - request.open('POST', url, false); + request.open('POST', url, true); //Send the proper header information along with the request request.setRequestHeader('Content-type', 'application/json'); request.onload = function () { @@ -5082,7 +5081,6 @@ reject(request.responseText); } request.send(params); - return result; } }) }, @@ -5837,4 +5835,4 @@ } - \ No newline at end of file + From 049cd5823c448631d11f8efac4db65b506b5838d Mon Sep 17 00:00:00 2001 From: Sai Raj <39055732+sairajzero@users.noreply.github.com> Date: Thu, 17 Oct 2019 15:55:24 +0530 Subject: [PATCH 015/289] changing ws:// to wss:// in supernode module --- index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 251d501..6a1d084 100644 --- a/index.html +++ b/index.html @@ -5237,7 +5237,7 @@ sendData: function (data, floID) { return new Promise((resolve, reject) => { this.kBucket.determineClosestSupernode(floID).then(result => { - var websocket = new WebSocket("ws://" + floGlobals.supernodes[result[0].floID].uri + "/ws"); + var websocket = new WebSocket("wss://" + floGlobals.supernodes[result[0].floID].uri + "/ws"); websocket.onopen = (evt) => { websocket.send(data); resolve(`Data sent to ${floID}'s supernode`); @@ -5256,7 +5256,7 @@ requestData: function (request, floID) { return new Promise((resolve, reject) => { this.kBucket.determineClosestSupernode(floID).then(result => { - var websocket = new WebSocket("ws://" + floGlobals.supernodes[result[0].floID].uri + "/ws"); + var websocket = new WebSocket("wss://" + floGlobals.supernodes[result[0].floID].uri + "/ws"); websocket.onopen = (evt) => { websocket.send(`?${request}`); }; From 57d16248d91d53e36b5a94bd9fc5ad5f2eec45b3 Mon Sep 17 00:00:00 2001 From: Sai Raj <39055732+sairajzero@users.noreply.github.com> Date: Thu, 17 Oct 2019 17:21:07 +0530 Subject: [PATCH 016/289] fixing bug in initDB --- index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 6a1d084..2f93325 100644 --- a/index.html +++ b/index.html @@ -5309,8 +5309,8 @@ } idb.onsuccess = (event) => { var db = event.target.result; - if (JSON.stringify(Object.values(db.objectStoreNames)) === JSON.stringify(Object.keys( - objectStores))) + if (JSON.stringify(Object.values(db.objectStoreNames).sort()) === JSON.stringify(Object.keys( + objectStores).sort())) resolve("Initiated IndexedDB"); else reject("IndexedDB already exist with different ObjectStores!"); From 41eb1dc4524bff40320b826d1135812ae87df96b Mon Sep 17 00:00:00 2001 From: sairaj mote Date: Sun, 20 Oct 2019 01:07:28 +0530 Subject: [PATCH 017/289] added description for floBlockchainAPI and compact IDB operations --- README.md | 112 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) diff --git a/README.md b/README.md index 0115093..fd7a439 100644 --- a/README.md +++ b/README.md @@ -78,3 +78,115 @@ This template contains standard operations that can be used for the following: 1. data - data of the given signature 2. signature - signature of the data 3. publicKey - public key of the signer + +## FLO Blockchain API Operations +`floBlockchainAPI` object method can be used to send/recieve data to/from blockchain.These functions are asynchronous and return a promise. Contains the following functions. + +#### promisedAJAX + floBlockchainAPI.promisedAJAX(method, uri) +`promisedAJAX` resolves a responce from server on success or rejects the responce on failure. +1. method - GET/POST + a. GET - Requests data from a specified resource. + b. POST - Submits data to be processed to a specified resource. +2. uri(Uniform Resource Identifier) - identifier for AJAX resource. It is used to create URL(Uniform Resource Locator) for further operations. + +#### getBalalnce + floBlockchainAPI.getBalance(addr) +`getBalance` resolves balance for specified FLO address. +1. addr - FLO address for which balance has to be retrieved. + +#### writeData + floBlockchainAPI.writeData(senderAddr, Data, PrivKey, receiverAddr = floGlobals.adminID) +`writeData` writes data into blockchain. +1. senderAddr - FLO address from which the data and amount has to be sent. +2. Data - Actual FLO data that will be sent as string of 1040 characters. +3. receiverAddr - FLO address to which has to be sent. Default is specified in floGlobals.adminID. +4. PrivKey - Private key of sender to verify sender. + +#### sendTx + floBlockchainAPI.sendTx(senderAddr, receiverAddr, sendAmt, PrivKey, floData = '') +`sendTx` sends a transaction to blockchain, resolves transaction id if the transacation was succsessful. +1. senderAddr - FLO address from which the data and amount has to be sent. +2. receiverAddr - FLO address to which has to be sent. +3. sendAmt - Amount of FLO coins to be sent to receiver. +4. PrivKey - Private key of sender to verify sender. +5. floData - Actual FLO data that will be sent as string of 1040 characters. + +#### readTxs + floBlockchainAPI.readTxs(addr, from, to) +`readTxs` reads transactions of specified address between from and to. +1. addr - FLO address for which the transactions has to be read. +2. from - Reading transactions starts from 'from'. +3. to - Reading transactions ends on 'to'. + +#### readAllTxs + floBlockchainAPI.readTxs(addr) +`readAllTxs` reads all transactions of specified address(newest first). +1. addr - FLO address for which the transactions has to be read. + +#### readData + floBlockchainAPI.readData(addr, options = {}) +`readData` reads FLO data from transactions of specified address +1. addr - FLO address for which the transactions data has to be read. +2. options - Contains options for filter data from transactions. + a. limit : maximum number of filtered data (default = 1000, negative = no limit) + b. ignoreOld : ignore old transactions (default = 0) + c. sentOnly : filters only sent data + d. pattern : filters data that starts with a pattern + e. contains : filters data that contains a string + f. filter : custom filter funtion for floData (eg . filter: d => {return d[0] == '$'}) + +## Compact IndexedDB operations +`compactIDB` operations can be used to perform basic IndexedDB operations such as add, read/write, modify and remove.Contains following operations. + +#### setDefaultDB + compactIDB.setDefaultDB(dbName) +`setDefaultDB` sets the database on which further operations will be performed. +1. dbName - This is the name of default database to be used. + +#### initDB + compactIDB.initDB(dbName, objectStores = {}) +`initDB` initializes new IndexedDB. +1. dbName - Specifies database to be initialized. +2. objectStores - This is an object containing various objectStores to be initiazed when creating an IDB. + +#### openDB + compactIDB.openDB(dbName) +`openDB` returns a promise that resolves to a default database object. + +#### deleteDB + compactIDB.deleteDB(dbName) +`deleteDB` deletes the specified database. + +#### writeData + compactIDB.writeData(obsName, data) +`writeData` writes specified data into the database if data doesn't exists or replaces it when data is already present. +1. obsName - object store name in which the data is to be written. +2. data - data that has to be written in specified object store. + +#### addData + compactIDB.addData(obsName, data) +`addData` writes new data into object store. If data already exists, it will return an error. +1. obsName - Object store name in which has to be stored. +2. data - The data which has to be added to obeject store. + +#### removeData + compactDB.removeData(obsName, key) +`removeData` deletes data from specified object store using primary key. +1. obsName - Name of object store from which the data has to be removed. +2. key - Primary key of the specified object store. + +#### readData + compactDB.readData(obsName, key) +`readData` reads the data from object store associated with specified key. +1. obsName - Name of object store from which the data has to be retrieved. +2. key - 2.key - Primary key of the specified object store. + +#### readAllData + compactDB.readAllData(obsName) +`readAllData` reads all the data from specified object store using IndexedDB openCursor method. +1. obsName - Name of object store from which the data has to be retrieved. +`signData` signs the data using the private key +1. data - data to sign +2. privateKey - private key of the signer + From 10a539337388417032702584730565fdbc6eb009 Mon Sep 17 00:00:00 2001 From: sairaj mote Date: Sun, 20 Oct 2019 01:15:39 +0530 Subject: [PATCH 018/289] Update README.md --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index fd7a439..17fb054 100644 --- a/README.md +++ b/README.md @@ -86,8 +86,8 @@ This template contains standard operations that can be used for the following: floBlockchainAPI.promisedAJAX(method, uri) `promisedAJAX` resolves a responce from server on success or rejects the responce on failure. 1. method - GET/POST - a. GET - Requests data from a specified resource. - b. POST - Submits data to be processed to a specified resource. + - GET - Requests data from a specified resource. + - POST - Submits data to be processed to a specified resource. 2. uri(Uniform Resource Identifier) - identifier for AJAX resource. It is used to create URL(Uniform Resource Locator) for further operations. #### getBalalnce @@ -129,12 +129,12 @@ This template contains standard operations that can be used for the following: `readData` reads FLO data from transactions of specified address 1. addr - FLO address for which the transactions data has to be read. 2. options - Contains options for filter data from transactions. - a. limit : maximum number of filtered data (default = 1000, negative = no limit) - b. ignoreOld : ignore old transactions (default = 0) - c. sentOnly : filters only sent data - d. pattern : filters data that starts with a pattern - e. contains : filters data that contains a string - f. filter : custom filter funtion for floData (eg . filter: d => {return d[0] == '$'}) + - limit : maximum number of filtered data (default = 1000, negative = no limit) + - ignoreOld : ignore old transactions (default = 0) + - sentOnly : filters only sent data + - pattern : filters data that starts with a pattern + - contains : filters data that contains a string + - filter : custom filter funtion for floData (eg . filter: d => {return d[0] == '$'}) ## Compact IndexedDB operations `compactIDB` operations can be used to perform basic IndexedDB operations such as add, read/write, modify and remove.Contains following operations. From d79d54b400b3853732cddfa2b829d47aeb578f02 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 19 Nov 2019 20:09:15 +0530 Subject: [PATCH 019/289] Updating to match the backup node feature of SN --- index.html | 124 +++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 102 insertions(+), 22 deletions(-) diff --git a/index.html b/index.html index 2f93325..6b155e3 100644 --- a/index.html +++ b/index.html @@ -5218,6 +5218,50 @@ } }); }, + getPrevSupernode: function(flo_addr, n = 1, KB = this.supernodeKBucket){ + return new Promise((resolve, reject) => { + try { + let isFloIdUint8 = flo_addr instanceof Uint8Array; + if (!isFloIdUint8) + flo_addr = this.floIdToKbucketId(flo_addr); + const KA = KB.toArray(); + let pos = KB._indexOf(KB.root,flo_addr) + var prevSupernode = [] + for(var i = 1; i <= n; i++){ + if(pos - i < 0) + var prev = pos - i + KA.length + else + var prev = pos - i + prevSupernode.push(KA[prev]) + } + resolve(prevSupernode); + } catch (error) { + reject(error); + } + }); + }, + getNextSupernode: function(flo_addr, n = 1, KB = this.supernodeKBucket){ + return new Promise((resolve, reject) => { + try { + let isFloIdUint8 = flo_addr instanceof Uint8Array; + if (!isFloIdUint8) + flo_addr = this.floIdToKbucketId(flo_addr); + const KA = KB.toArray(); + let pos = KB._indexOf(KB.root,flo_addr) + var nextSupernode = [] + for(var i = 1; i <= n; i++){ + if(pos + i >= KA.length) + var next = pos + i - KA.length + else + var next = pos + i + nextSupernode.push(KA[next]) + } + resolve(nextSupernode); + } catch (error) { + reject(error); + } + }); + }, determineClosestSupernode: function (flo_addr, n = 1, KB = this.supernodeKBucket) { return new Promise((resolve, reject) => { try { @@ -5233,42 +5277,78 @@ } }, + sendDataToSN(data, snfloID){ + return new Promise((resolve, reject) => { + console.log(snfloID) + var websocket = new WebSocket("wss://" + floGlobals.supernodes[snfloID].uri + "/ws"); + websocket.onmessage = (evt => { + if(evt.data == '$+'){ + websocket.send(data); + resolve(`Data sent to supernode : ${snfloID}`); + }else if(evt.data == '$-'){ + this.kBucket.getNextSupernode(snfloID) + .then(nextnode => this.sendDataToSN(data, nextnode[0].floID)) + .catch(error => reject(error)) + }else{ + console.log(evt.data) + reject(evt.data) + } + websocket.close(); + }) + websocket.onerror = (evt) => { + this.kBucket.getNextSupernode(snfloID) + .then(nextnode => this.sendDataToSN(data, nextnode[0].floID)) + .catch(error => reject(error)) + }; + }) + }, + //Sends data to the supernode sendData: function (data, floID) { return new Promise((resolve, reject) => { this.kBucket.determineClosestSupernode(floID).then(result => { - var websocket = new WebSocket("wss://" + floGlobals.supernodes[result[0].floID].uri + "/ws"); - websocket.onopen = (evt) => { - websocket.send(data); - resolve(`Data sent to ${floID}'s supernode`); - websocket.close(); - }; - websocket.onerror = (evt) => { - reject(evt); - }; + this.sendDataToSN(data, result[0].floID) + .then(result => resolve(result)) + .catch(error => reject(error)) }).catch(error => { - reject(error); + reject(error); }); }); }, + requestDataFromSN(request, snfloID){ + return new Promise((resolve, reject) => { + var websocket = new WebSocket("wss://" + floGlobals.supernodes[snfloID].uri + "/ws"); + websocket.onmessage = (evt => { + if(evt.data == '$+'){ + websocket.send(`?${request}`); + }else if(evt.data == '$-'){ + this.kBucket.getNextSupernode(snfloID) + .then(nextnode => this.requestDataFromSN(request, nextnode[0].floID)) + .catch(error => reject(error)) + websocket.close() + }else{ + resolve(evt.data); + websocket.close(); + } + }) + websocket.onerror = (evt) => { + this.kBucket.getNextSupernode(snfloID) + .then(nextnode => this.requestDataFromSN(request, nextnode[0].floID)) + .catch(error => reject(error)) + }; + }) + }, + //Request data from supernode requestData: function (request, floID) { return new Promise((resolve, reject) => { this.kBucket.determineClosestSupernode(floID).then(result => { - var websocket = new WebSocket("wss://" + floGlobals.supernodes[result[0].floID].uri + "/ws"); - websocket.onopen = (evt) => { - websocket.send(`?${request}`); - }; - websocket.onmessage = (evt) => { - resolve(evt.data); - websocket.close(); - }; - websocket.onerror = (evt) => { - reject(evt); - }; + this.requestDataFromSN(request, result[0].floID) + .then(result => resolve(result)) + .catch(error => reject(error)) }).catch(error => { - reject(error); + reject(error); }); }); } From 289089d972836056b65b3e58eb3965f4f7c88591 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 19 Nov 2019 20:11:32 +0530 Subject: [PATCH 020/289] Adding floCloudAPI floCloudAPI has methods to send application data, request application data, reset or update object data. --- index.html | 407 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 407 insertions(+) diff --git a/index.html b/index.html index 6b155e3..8fa934a 100644 --- a/index.html +++ b/index.html @@ -5914,5 +5914,412 @@ } } + + From ce28df68344c626b94b871410ab774b40d732256 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Wed, 20 Nov 2019 02:07:35 +0530 Subject: [PATCH 021/289] adding automatic fetch for flosight API --- index.html | 133 ++++++++++++++++++++++++++++++----------------------- 1 file changed, 75 insertions(+), 58 deletions(-) diff --git a/index.html b/index.html index 8fa934a..7a809f9 100644 --- a/index.html +++ b/index.html @@ -10,12 +10,12 @@ const floGlobals = { //Required for all - blockchain: "FLO_TEST", + blockchain: "FLO", //Required for blockchain API operators apiURL: { - FLO: 'https://flosight.duckdns.org', - FLO_TEST: 'https://testnet-flosight.duckdns.org' + FLO: ['https://explorer.mediciland.com/', 'https://livenet.flocha.in/', 'https://flosight.duckdns.org/', 'http://livenet-explorer.floexperiments.com', 'http://ec2-13-233-133-128.ap-south-1.compute.amazonaws.com/', 'http://ec2-13-233-131-136.ap-south-1.compute.amazonaws.com/', 'http://ec2-13-233-194-1.ap-south-1.compute.amazonaws.com/'], + FLO_TEST: ['https://testnet-flosight.duckdns.org', 'https://testnet.flocha.in/'] }, adminID: "oTZw3ydCRKDhcYC5Bp6mRJMGTTVv9JHtg8", sendAmt: 0.001, @@ -4692,7 +4692,6 @@ }; - From 5ae3214a67b72e00dca58199444f893ec77f9785 Mon Sep 17 00:00:00 2001 From: Sai Raj <39055732+sairajzero@users.noreply.github.com> Date: Wed, 20 Nov 2019 18:15:34 +0530 Subject: [PATCH 022/289] Rename index.html to standard_Operations.html --- index.html => standard_Operations.html | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename index.html => standard_Operations.html (100%) diff --git a/index.html b/standard_Operations.html similarity index 100% rename from index.html rename to standard_Operations.html From 577bee4d371cfd0a17629724b256d202fa2aba65 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Wed, 20 Nov 2019 20:20:39 +0530 Subject: [PATCH 023/289] Adding requestApplicationData requestApplicationData : request any message from the supernode cloud Fixed minor bugs --- standard_Operations.html | 51 ++++++++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 12 deletions(-) diff --git a/standard_Operations.html b/standard_Operations.html index 7a809f9..e9683ae 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -22,7 +22,14 @@ fee: 0.0005, //Required for Supernode operations - supernodes: {} //each supnernode must be stored as floID : {uri:,pubKey:} + SNStorageID: "FEzk75EGMPEQMrCuPosGiwuK162hcEu49E", + supernodes: {}, //each supnernode must be stored as floID : {uri:,pubKey:} + + //for cloud apps + subAdmins: [], + application: "Test_RIBC", + vectorClock: {}, + appObjects: {} } @@ -6240,6 +6247,26 @@ }) }, + //request any data from supernode cloud + requestApplicationData: function(options = {}){ + return new Promise((resolve,reject) => { + var request = { + receiverID: options.receiverID || floGlobals.adminID, + senderIDs: options.senderIDs || undefined, + application: options.application || floGlobals.application, + type: options.type || undefined, + comment: options.comment || undefined, + lowerVectorClock: options.lowerVectorClock || undefined, + upperVectorClock: options.upperVectorClock || undefined, + atVectorClock: options.atVectorClock || undefined, + mostRecent: options.mostRecent || undefined, + } + floSupernode.requestData(JSON.stringify(request), request.receiverID) + .then(response => resolve(response)) + .catch(error => reject(error)) + }) + }, + //request an object data from supernode cloud requestObjectData: function(objectName, options = {}){ var request = { @@ -6265,10 +6292,10 @@ var message = { division: options.division || floGlobals.division, object: objectName, - vectorClock: floGlobals.vectorClock[object], + vectorClock: floGlobals.vectorClock[objectName], reset: newObject } - this.sendApplicationData(message, `${object}@Reset`, options) + this.sendApplicationData(message, `${objectName}@Reset`, options) .then(result => reactor.dispatchEvent('logHandle',result)) .catch(error => reactor.dispatchEvent('errorHandle',error)) }, @@ -6278,10 +6305,10 @@ var message = { division: options.division || floGlobals.division, object: objectName, - vectorClock: floGlobals.vectorClock[object], + vectorClock: floGlobals.vectorClock[objectName], diff: detailedDiff(oldObject, newObject) } - this.sendApplicationData(message, `${object}@Update`, options) + this.sendApplicationData(message, `${objectName}@Update`, options) .then(result => reactor.dispatchEvent('logHandle',result)) .catch(error => reactor.dispatchEvent('errorHandle',error)) } @@ -6293,15 +6320,15 @@ dataSet = JSON.parse(dataSet); console.log(dataSet) for(vc in dataSet){ - if(floGlobals.subAdmins.includes(dataSet[v].senderID)){ - var message = dataSet[v].message; + //if(floGlobals.subAdmins.includes(dataSet[vc].senderID)){ + var message = dataSet[vc].message; if(message.reset){ floGlobals.appObjects[message.object] = message.reset floGlobals.vectorClock[message.object] = vc //compactIDB.writeData("appObjects", floGlobals.appObjects[message.object], message.object) //compactIDB.writeData("vectorClocks", vc, message.object) } - } + //} } }catch(error){ console.log(error) @@ -6314,13 +6341,13 @@ dataSet = JSON.parse(dataSet); console.log(dataSet) for(vc in dataSet){ - if(floGlobals.subAdmins.includes(dataSet[v].senderID)){ - var message = dataSet[v].message; + //if(floGlobals.subAdmins.includes(dataSet[vc].senderID)){ + var message = dataSet[vc].message; if(message.diff){ floGlobals.appObjects[message.object] = mergeAllDiff(floGlobals.appObjects[message.object], message.diff) - //compactIDB.writeData("objects",floGlobals.appObjects[message.object], message.object) + //compactIDB.writeData("appObjects",floGlobals.appObjects[message.object], message.object) } - } + //} floGlobals.vectorClock[message.object] = vc //compactIDB.writeData("vectorClocks", vc, message.object) } From e7a74c785edcb31a0640d1e20404431946370a7e Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 1 Dec 2019 11:45:00 +0530 Subject: [PATCH 024/289] Adding Shamir's Shared Secret to floCrypto Adding Shamir's Shared Secret to floCrypto module createShamirsSecretShares: create the shamirs secret shares retrieveShamirSecret: retrives the secret from shares verifyShamirsSecret: verify the shares with secret Also adding randInt and randString to floCrypto module --- standard_Operations.html | 638 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 627 insertions(+), 11 deletions(-) diff --git a/standard_Operations.html b/standard_Operations.html index e9683ae..b4e076f 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -36,7 +36,9 @@ use console - use console - + + use console - - - - - - - + - - From 5a2b6250ca6163df90e1c783ed729e55bb2d985b Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 19 Dec 2019 22:03:53 +0530 Subject: [PATCH 032/289] adding floDapps std_Op This std_op contains functions for FLO Dapp startup and other useful functions for FLO Dapps --- standard_Operations.html | 268 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 267 insertions(+), 1 deletion(-) diff --git a/standard_Operations.html b/standard_Operations.html index 8d75b81..54294c9 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -36,7 +36,7 @@ - + use console + From 5e9926b87b7a92f9797b898e2aa9dd721518f978 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 19 Dec 2019 22:28:43 +0530 Subject: [PATCH 033/289] bug fix: floDapps --- standard_Operations.html | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/standard_Operations.html b/standard_Operations.html index 54294c9..a1e55bc 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -2,7 +2,7 @@ - FLO Operators + FLO Standard Operators From c473d200c03193eeb2abfe61fa27b49877a4e639 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 5 Jan 2020 19:42:34 +0530 Subject: [PATCH 034/289] Improving floSupernode.kBucket module Adding getInnerNodes and getOuterNodes getPrevSupernode, getNextSupernode and determineClosestSupernode now return an array of floIDs --- standard_Operations.html | 91 ++++++++++++++++++++++++++-------------- 1 file changed, 60 insertions(+), 31 deletions(-) diff --git a/standard_Operations.html b/standard_Operations.html index a1e55bc..7e9cf66 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -6129,31 +6129,60 @@ this.addContact(decodedId, address, KB); }, isNodePresent: function (flo_id, KB = this.supernodeKBucket) { + let kArray = KB.toArray(); + let kArrayFloIds = kArray.map(k => k.floID); + if (kArrayFloIds.includes(flo_id)) + return true; + else + return false; + }, + + getInnerNodes: function(flo_addr1, flo_addr2, KB = this.supernodeKBucket){ return new Promise((resolve, reject) => { - let kArray = KB.toArray(); - let kArrayFloIds = kArray.map(k => k.data.id); - if (kArrayFloIds.includes(flo_id)) { - resolve(true); - } else { - reject(false); - } + let kArrayFloIds = KB.toArray().map(k => k.floID); + var innerNodes = [] + if(kArrayFloIds.includes(flo_addr1) && kArrayFloIds.includes(flo_addr2)){ + for(var i = kArrayFloIds.indexOf(flo_addr1); i!= flo_addr2; i++){ + if(i >= kArrayFloIds.length) + i = -1 + else + innerNodes.push(kArrayFloIds[i]) + } + resolve(innerNodes) + }else + reject('Given nodes are not in KBucket') }); }, + + getOuterNodes: function(flo_addr1, flo_addr2, KB = this.supernodeKBucket){ + return new Promise((resolve, reject) => { + let kArrayFloIds = KB.toArray().map(k => k.floID); + var outterNodes = [] + if(kArrayFloIds.includes(flo_addr1) && kArrayFloIds.includes(flo_addr2)){ + for(var i = kArrayFloIds.indexOf(flo_addr2); i!= flo_addr1; i++){ + if(i >= kArrayFloIds.length) + i = -1 + else + outterNodes.push(kArrayFloIds[i]) + } + resolve(outterNodes) + }else + reject('Given nodes are not in KBucket') + }); + }, + getPrevSupernode: function(flo_addr, n = 1, KB = this.supernodeKBucket){ return new Promise((resolve, reject) => { try { - let isFloIdUint8 = flo_addr instanceof Uint8Array; - if (!isFloIdUint8) - flo_addr = this.floIdToKbucketId(flo_addr); - const KA = KB.toArray(); - let pos = KB._indexOf(KB.root,flo_addr) + let kArrayFloIds = KB.toArray().map(k => k.floID); + let pos = kArrayFloIds.indexOf(flo_addr) var prevSupernode = [] for(var i = 1; i <= n; i++){ if(pos - i < 0) - var prev = pos - i + KA.length + var prev = pos - i + kArrayFloIds.length else var prev = pos - i - prevSupernode.push(KA[prev]) + prevSupernode.push(kArrayFloIds[prev]) } resolve(prevSupernode); } catch (error) { @@ -6161,21 +6190,19 @@ } }); }, + getNextSupernode: function(flo_addr, n = 1, KB = this.supernodeKBucket){ return new Promise((resolve, reject) => { try { - let isFloIdUint8 = flo_addr instanceof Uint8Array; - if (!isFloIdUint8) - flo_addr = this.floIdToKbucketId(flo_addr); - const KA = KB.toArray(); - let pos = KB._indexOf(KB.root,flo_addr) + let kArrayFloIds = KB.toArray().map(k => k.floID); + let pos = kArrayFloIds.indexOf(flo_addr) var nextSupernode = [] for(var i = 1; i <= n; i++){ - if(pos + i >= KA.length) - var next = pos + i - KA.length + if(pos + i >= kArrayFloIds.length) + var next = pos + i - kArrayFloIds.length else var next = pos + i - nextSupernode.push(KA[next]) + nextSupernode.push(kArrayFloIds[next]) } resolve(nextSupernode); } catch (error) { @@ -6183,13 +6210,15 @@ } }); }, + determineClosestSupernode: function (flo_addr, n = 1, KB = this.supernodeKBucket) { return new Promise((resolve, reject) => { try { let isFloIdUint8 = flo_addr instanceof Uint8Array; if (!isFloIdUint8) flo_addr = this.floIdToKbucketId(flo_addr); - const closestSupernode = KB.closest(flo_addr, n); + var closestSupernode = KB.closest(flo_addr, n); + closestSupernode = closestSupernode.map(k => k.floID); resolve(closestSupernode); } catch (error) { reject(error); @@ -6208,7 +6237,7 @@ resolve(`Data sent to supernode : ${snfloID}`); }else if(evt.data == '$-'){ this.kBucket.getNextSupernode(snfloID) - .then(nextnode => this.sendDataToSN(data, nextnode[0].floID)) + .then(nextNode => this.sendDataToSN(data, nextNode[0])) .catch(error => reject(error)) }else{ console.log(evt.data) @@ -6218,7 +6247,7 @@ }) websocket.onerror = (evt) => { this.kBucket.getNextSupernode(snfloID) - .then(nextnode => this.sendDataToSN(data, nextnode[0].floID)) + .then(nextNode => this.sendDataToSN(data, nextNode[0])) .catch(error => reject(error)) }; }) @@ -6227,8 +6256,8 @@ //Sends data to the supernode sendData: function (data, floID) { return new Promise((resolve, reject) => { - this.kBucket.determineClosestSupernode(floID).then(result => { - this.sendDataToSN(data, result[0].floID) + this.kBucket.determineClosestSupernode(floID).then(closestNode => { + this.sendDataToSN(data, closestNode[0]) .then(result => resolve(result)) .catch(error => reject(error)) }).catch(error => { @@ -6245,7 +6274,7 @@ websocket.send(`?${request}`); }else if(evt.data == '$-'){ this.kBucket.getNextSupernode(snfloID) - .then(nextnode => this.requestDataFromSN(request, nextnode[0].floID)) + .then(nextNode => this.requestDataFromSN(request, nextNode[0])) .catch(error => reject(error)) websocket.close() }else{ @@ -6255,7 +6284,7 @@ }) websocket.onerror = (evt) => { this.kBucket.getNextSupernode(snfloID) - .then(nextnode => this.requestDataFromSN(request, nextnode[0].floID)) + .then(nextNode => this.requestDataFromSN(request, nextNode[0])) .catch(error => reject(error)) }; }) @@ -6264,8 +6293,8 @@ //Request data from supernode requestData: function (request, floID) { return new Promise((resolve, reject) => { - this.kBucket.determineClosestSupernode(floID).then(result => { - this.requestDataFromSN(request, result[0].floID) + this.kBucket.determineClosestSupernode(floID).then(closestNode => { + this.requestDataFromSN(request, closestNode[0]) .then(result => resolve(result)) .catch(error => reject(error)) }).catch(error => { From e40771eb2336c0b690c3bf73e3cac8b057ed0fa6 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 5 Jan 2020 19:43:09 +0530 Subject: [PATCH 035/289] bug fix: some missing libraries --- standard_Operations.html | 10401 +++++++++++++++++++++---------------- 1 file changed, 5905 insertions(+), 4496 deletions(-) diff --git a/standard_Operations.html b/standard_Operations.html index 7e9cf66..64ab216 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -88,4667 +88,6076 @@ reactor.dispatchEvent('',); */ - /*! - * Crypto-JS v2.5.4 Crypto.js - * http://code.google.com/p/crypto-js/ - * Copyright (c) 2009-2013, Jeff Mott. All rights reserved. - * http://code.google.com/p/crypto-js/wiki/License - */ - if (typeof Crypto == "undefined" || !Crypto.util) { + +/*! +* Crypto-JS v2.5.4 Crypto.js +* http://code.google.com/p/crypto-js/ +* Copyright (c) 2009-2013, Jeff Mott. All rights reserved. +* http://code.google.com/p/crypto-js/wiki/License +*/ +if (typeof Crypto == "undefined" || !Crypto.util) { + (function () { + + var base64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + // Global Crypto object + var Crypto = window.Crypto = {}; + + // Crypto utilities + var util = Crypto.util = { + + // Bit-wise rotate left + rotl: function (n, b) { + return (n << b) | (n >>> (32 - b)); + }, + + // Bit-wise rotate right + rotr: function (n, b) { + return (n << (32 - b)) | (n >>> b); + }, + + // Swap big-endian to little-endian and vice versa + endian: function (n) { + + // If number given, swap endian + if (n.constructor == Number) { + return util.rotl(n, 8) & 0x00FF00FF | + util.rotl(n, 24) & 0xFF00FF00; + } + + // Else, assume array and swap all items + for (var i = 0; i < n.length; i++) + n[i] = util.endian(n[i]); + return n; + + }, + + // Generate an array of any length of random bytes + randomBytes: function (n) { + for (var bytes = []; n > 0; n--) + bytes.push(Math.floor(Math.random() * 256)); + return bytes; + }, + + // Convert a byte array to big-endian 32-bit words + bytesToWords: function (bytes) { + for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) + words[b >>> 5] |= (bytes[i] & 0xFF) << (24 - b % 32); + return words; + }, + + // Convert big-endian 32-bit words to a byte array + wordsToBytes: function (words) { + for (var bytes = [], b = 0; b < words.length * 32; b += 8) + bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); + return bytes; + }, + + // Convert a byte array to a hex string + bytesToHex: function (bytes) { + for (var hex = [], i = 0; i < bytes.length; i++) { + hex.push((bytes[i] >>> 4).toString(16)); + hex.push((bytes[i] & 0xF).toString(16)); + } + return hex.join(""); + }, + + // Convert a hex string to a byte array + hexToBytes: function (hex) { + for (var bytes = [], c = 0; c < hex.length; c += 2) + bytes.push(parseInt(hex.substr(c, 2), 16)); + return bytes; + }, + + // Convert a byte array to a base-64 string + bytesToBase64: function (bytes) { + for (var base64 = [], i = 0; i < bytes.length; i += 3) { + var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; + for (var j = 0; j < 4; j++) { + if (i * 8 + j * 6 <= bytes.length * 8) + base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F)); + else base64.push("="); + } + } + + return base64.join(""); + }, + + // Convert a base-64 string to a byte array + base64ToBytes: function (base64) { + // Remove non-base-64 characters + base64 = base64.replace(/[^A-Z0-9+\/]/ig, ""); + + for (var bytes = [], i = 0, imod4 = 0; i < base64.length; imod4 = ++i % 4) { + if (imod4 == 0) continue; + bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) | + (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); + } + + return bytes; + } + + }; + + // Crypto character encodings + var charenc = Crypto.charenc = {}; + + // UTF-8 encoding + var UTF8 = charenc.UTF8 = { + + // Convert a string to a byte array + stringToBytes: function (str) { + return Binary.stringToBytes(unescape(encodeURIComponent(str))); + }, + + // Convert a byte array to a string + bytesToString: function (bytes) { + return decodeURIComponent(escape(Binary.bytesToString(bytes))); + } + + }; + + // Binary encoding + var Binary = charenc.Binary = { + + // Convert a string to a byte array + stringToBytes: function (str) { + for (var bytes = [], i = 0; i < str.length; i++) + bytes.push(str.charCodeAt(i) & 0xFF); + return bytes; + }, + + // Convert a byte array to a string + bytesToString: function (bytes) { + for (var str = [], i = 0; i < bytes.length; i++) + str.push(String.fromCharCode(bytes[i])); + return str.join(""); + } + + }; + + })(); +} + + + + //Adding SHA1 to fix basic PKBDF2 + /* + * Crypto-JS v2.5.4 + * http://code.google.com/p/crypto-js/ + * (c) 2009-2012 by Jeff Mott. All rights reserved. + * http://code.google.com/p/crypto-js/wiki/License + */ (function () { - - var base64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - // Global Crypto object - var Crypto = window.Crypto = {}; - - // Crypto utilities - var util = Crypto.util = { - - // Bit-wise rotate left - rotl: function (n, b) { - return (n << b) | (n >>> (32 - b)); - }, - - // Bit-wise rotate right - rotr: function (n, b) { - return (n << (32 - b)) | (n >>> b); - }, - - // Swap big-endian to little-endian and vice versa - endian: function (n) { - - // If number given, swap endian - if (n.constructor == Number) { - return util.rotl(n, 8) & 0x00FF00FF | - util.rotl(n, 24) & 0xFF00FF00; - } - - // Else, assume array and swap all items - for (var i = 0; i < n.length; i++) - n[i] = util.endian(n[i]); - return n; - - }, - - // Generate an array of any length of random bytes - randomBytes: function (n) { - for (var bytes = []; n > 0; n--) - bytes.push(Math.floor(Math.random() * 256)); - return bytes; - }, - - // Convert a byte array to big-endian 32-bit words - bytesToWords: function (bytes) { - for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) - words[b >>> 5] |= (bytes[i] & 0xFF) << (24 - b % 32); - return words; - }, - - // Convert big-endian 32-bit words to a byte array - wordsToBytes: function (words) { - for (var bytes = [], b = 0; b < words.length * 32; b += 8) - bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); - return bytes; - }, - - // Convert a byte array to a hex string - bytesToHex: function (bytes) { - for (var hex = [], i = 0; i < bytes.length; i++) { - hex.push((bytes[i] >>> 4).toString(16)); - hex.push((bytes[i] & 0xF).toString(16)); - } - return hex.join(""); - }, - - // Convert a hex string to a byte array - hexToBytes: function (hex) { - for (var bytes = [], c = 0; c < hex.length; c += 2) - bytes.push(parseInt(hex.substr(c, 2), 16)); - return bytes; - }, - - // Convert a byte array to a base-64 string - bytesToBase64: function (bytes) { - for (var base64 = [], i = 0; i < bytes.length; i += 3) { - var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; - for (var j = 0; j < 4; j++) { - if (i * 8 + j * 6 <= bytes.length * 8) - base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F)); - else base64.push("="); + + // Shortcuts + var C = Crypto, + util = C.util, + charenc = C.charenc, + UTF8 = charenc.UTF8, + Binary = charenc.Binary; + + // Public API + var SHA1 = C.SHA1 = function (message, options) { + var digestbytes = util.wordsToBytes(SHA1._sha1(message)); + return options && options.asBytes ? digestbytes : + options && options.asString ? Binary.bytesToString(digestbytes) : + util.bytesToHex(digestbytes); + }; + + // The core + SHA1._sha1 = function (message) { + + // Convert to byte array + if (message.constructor == String) message = UTF8.stringToBytes(message); + /* else, assume byte array already */ + + var m = util.bytesToWords(message), + l = message.length * 8, + w = [], + H0 = 1732584193, + H1 = -271733879, + H2 = -1732584194, + H3 = 271733878, + H4 = -1009589776; + + // Padding + m[l >> 5] |= 0x80 << (24 - l % 32); + m[((l + 64 >>> 9) << 4) + 15] = l; + + for (var i = 0; i < m.length; i += 16) { + + var a = H0, + b = H1, + c = H2, + d = H3, + e = H4; + + for (var j = 0; j < 80; j++) { + + if (j < 16) w[j] = m[i + j]; + else { + var n = w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16]; + w[j] = (n << 1) | (n >>> 31); } + + var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + ( + j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 : + j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 : + j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 : + (H1 ^ H2 ^ H3) - 899497514); + + H4 = H3; + H3 = H2; + H2 = (H1 << 30) | (H1 >>> 2); + H1 = H0; + H0 = t; + } - - return base64.join(""); - }, - - // Convert a base-64 string to a byte array - base64ToBytes: function (base64) { - // Remove non-base-64 characters - base64 = base64.replace(/[^A-Z0-9+\/]/ig, ""); - - for (var bytes = [], i = 0, imod4 = 0; i < base64.length; imod4 = ++i % 4) { - if (imod4 == 0) continue; - bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) | - (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); - } - - return bytes; + + H0 += a; + H1 += b; + H2 += c; + H3 += d; + H4 += e; + } - + + return [H0, H1, H2, H3, H4]; + }; - - // Crypto character encodings - var charenc = Crypto.charenc = {}; - - // UTF-8 encoding - var UTF8 = charenc.UTF8 = { - - // Convert a string to a byte array - stringToBytes: function (str) { - return Binary.stringToBytes(unescape(encodeURIComponent(str))); - }, - - // Convert a byte array to a string - bytesToString: function (bytes) { - return decodeURIComponent(escape(Binary.bytesToString(bytes))); - } - - }; - - // Binary encoding - var Binary = charenc.Binary = { - - // Convert a string to a byte array - stringToBytes: function (str) { - for (var bytes = [], i = 0; i < str.length; i++) - bytes.push(str.charCodeAt(i) & 0xFF); - return bytes; - }, - - // Convert a byte array to a string - bytesToString: function (bytes) { - for (var str = [], i = 0; i < bytes.length; i++) - str.push(String.fromCharCode(bytes[i])); - return str.join(""); - } - - }; - + + // Package private blocksize + SHA1._blocksize = 16; + + SHA1._digestsize = 20; + })(); - } - - - - //Adding SHA1 to fix basic PKBDF2 - /* - * Crypto-JS v2.5.4 - * http://code.google.com/p/crypto-js/ - * (c) 2009-2012 by Jeff Mott. All rights reserved. - * http://code.google.com/p/crypto-js/wiki/License - */ - (function () { - - // Shortcuts - var C = Crypto, - util = C.util, - charenc = C.charenc, - UTF8 = charenc.UTF8, - Binary = charenc.Binary; - - // Public API - var SHA1 = C.SHA1 = function (message, options) { - var digestbytes = util.wordsToBytes(SHA1._sha1(message)); - return options && options.asBytes ? digestbytes : - options && options.asString ? Binary.bytesToString(digestbytes) : - util.bytesToHex(digestbytes); - }; - - // The core - SHA1._sha1 = function (message) { - - // Convert to byte array - if (message.constructor == String) message = UTF8.stringToBytes(message); - /* else, assume byte array already */ - - var m = util.bytesToWords(message), - l = message.length * 8, - w = [], - H0 = 1732584193, - H1 = -271733879, - H2 = -1732584194, - H3 = 271733878, - H4 = -1009589776; - - // Padding - m[l >> 5] |= 0x80 << (24 - l % 32); - m[((l + 64 >>> 9) << 4) + 15] = l; - - for (var i = 0; i < m.length; i += 16) { - - var a = H0, - b = H1, - c = H2, - d = H3, - e = H4; - - for (var j = 0; j < 80; j++) { - - if (j < 16) w[j] = m[i + j]; - else { - var n = w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16]; - w[j] = (n << 1) | (n >>> 31); - } - - var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + ( - j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 : - j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 : - j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 : - (H1 ^ H2 ^ H3) - 899497514); - - H4 = H3; - H3 = H2; - H2 = (H1 << 30) | (H1 >>> 2); - H1 = H0; - H0 = t; - - } - - H0 += a; - H1 += b; - H2 += c; - H3 += d; - H4 += e; - - } - - return [H0, H1, H2, H3, H4]; - - }; - - // Package private blocksize - SHA1._blocksize = 16; - - SHA1._digestsize = 20; - - })(); - - //Added to make PKBDF2 work - /* - * Crypto-JS v2.5.4 - * http://code.google.com/p/crypto-js/ - * (c) 2009-2012 by Jeff Mott. All rights reserved. - * http://code.google.com/p/crypto-js/wiki/License - */ - (function () { - - // Shortcuts - var C = Crypto, - util = C.util, - charenc = C.charenc, - UTF8 = charenc.UTF8, - Binary = charenc.Binary; - - C.HMAC = function (hasher, message, key, options) { - - // Convert to byte arrays - if (message.constructor == String) message = UTF8.stringToBytes(message); - if (key.constructor == String) key = UTF8.stringToBytes(key); - /* else, assume byte arrays already */ - - // Allow arbitrary length keys - if (key.length > hasher._blocksize * 4) - key = hasher(key, { - asBytes: true - }); - - // XOR keys with pad constants - var okey = key.slice(0), - ikey = key.slice(0); - for (var i = 0; i < hasher._blocksize * 4; i++) { - okey[i] ^= 0x5C; - ikey[i] ^= 0x36; - } - - var hmacbytes = hasher(okey.concat(hasher(ikey.concat(message), { - asBytes: true - })), { + + //Added to make PKBDF2 work + /* + * Crypto-JS v2.5.4 + * http://code.google.com/p/crypto-js/ + * (c) 2009-2012 by Jeff Mott. All rights reserved. + * http://code.google.com/p/crypto-js/wiki/License + */ + (function () { + + // Shortcuts + var C = Crypto, + util = C.util, + charenc = C.charenc, + UTF8 = charenc.UTF8, + Binary = charenc.Binary; + + C.HMAC = function (hasher, message, key, options) { + + // Convert to byte arrays + if (message.constructor == String) message = UTF8.stringToBytes(message); + if (key.constructor == String) key = UTF8.stringToBytes(key); + /* else, assume byte arrays already */ + + // Allow arbitrary length keys + if (key.length > hasher._blocksize * 4) + key = hasher(key, { asBytes: true }); - - return options && options.asBytes ? hmacbytes : - options && options.asString ? Binary.bytesToString(hmacbytes) : - util.bytesToHex(hmacbytes); - - }; - - })(); - - - //crypto-sha256-hmac.js - /* - * Crypto-JS v2.5.4 - * http://code.google.com/p/crypto-js/ - * (c) 2009-2012 by Jeff Mott. All rights reserved. - * http://code.google.com/p/crypto-js/wiki/License - */ - - function ascii_to_hexa(str) { - var arr1 = []; - for (var n = 0, l = str.length; n < l; n++) { - var hex = Number(str.charCodeAt(n)).toString(16); - arr1.push(hex); + + // XOR keys with pad constants + var okey = key.slice(0), + ikey = key.slice(0); + for (var i = 0; i < hasher._blocksize * 4; i++) { + okey[i] ^= 0x5C; + ikey[i] ^= 0x36; } - return arr1.join(''); + + var hmacbytes = hasher(okey.concat(hasher(ikey.concat(message), { + asBytes: true + })), { + asBytes: true + }); + + return options && options.asBytes ? hmacbytes : + options && options.asString ? Binary.bytesToString(hmacbytes) : + util.bytesToHex(hmacbytes); + + }; + + })(); + + + //crypto-sha256-hmac.js + /* + * Crypto-JS v2.5.4 + * http://code.google.com/p/crypto-js/ + * (c) 2009-2012 by Jeff Mott. All rights reserved. + * http://code.google.com/p/crypto-js/wiki/License + */ + + function ascii_to_hexa(str) { + var arr1 = []; + for (var n = 0, l = str.length; n < l; n++) { + var hex = Number(str.charCodeAt(n)).toString(16); + arr1.push(hex); } - - - (typeof Crypto == "undefined" || !Crypto.util) && function () { - var d = window.Crypto = {}, - k = d.util = { - rotl: function (b, a) { - return b << a | b >>> 32 - a - }, - rotr: function (b, a) { - return b << 32 - a | b >>> a - }, - endian: function (b) { - if (b.constructor == Number) return k.rotl(b, 8) & 16711935 | k.rotl(b, 24) & 4278255360; - for (var a = 0; a < b.length; a++) b[a] = k.endian(b[a]); - return b - }, - randomBytes: function (b) { - for (var a = []; b > 0; b--) a.push(Math.floor(Math.random() * 256)); - return a - }, - bytesToWords: function (b) { - for (var a = [], c = 0, e = 0; c < b.length; c++, e += 8) a[e >>> 5] |= (b[c] & 255) << - 24 - e % 32; - return a - }, - wordsToBytes: function (b) { - for (var a = [], c = 0; c < b.length * 32; c += 8) a.push(b[c >>> 5] >>> 24 - c % 32 & 255); - return a - }, - bytesToHex: function (b) { - for (var a = [], c = 0; c < b.length; c++) a.push((b[c] >>> 4).toString(16)), a.push((b[c] & - 15).toString(16)); - return a.join("") - }, - hexToBytes: function (b) { - for (var a = [], c = 0; c < b.length; c += 2) a.push(parseInt(b.substr(c, 2), 16)); - return a - }, - bytesToBase64: function (b) { - for (var a = [], c = 0; c < b.length; c += 3) - for (var e = b[c] << 16 | b[c + 1] << 8 | b[c + 2], p = 0; p < 4; p++) c * 8 + p * 6 <= - b.length * 8 ? a.push( - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e >>> - 6 * (3 - p) & 63)) : a.push("="); - return a.join("") - }, - base64ToBytes: function (b) { - for (var b = b.replace(/[^A-Z0-9+\/]/ig, ""), a = [], c = 0, e = 0; c < b.length; e = ++c % - 4) e != 0 && a.push(("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" - .indexOf(b.charAt(c - 1)) & Math.pow(2, -2 * e + 8) - 1) << e * 2 | - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(b.charAt( - c)) >>> 6 - e * 2); - return a - } + return arr1.join(''); + } + + + (typeof Crypto == "undefined" || !Crypto.util) && function () { + var d = window.Crypto = {}, + k = d.util = { + rotl: function (b, a) { + return b << a | b >>> 32 - a }, - d = d.charenc = {}; - d.UTF8 = { - stringToBytes: function (b) { - return g.stringToBytes(unescape(encodeURIComponent(b))) + rotr: function (b, a) { + return b << 32 - a | b >>> a }, - bytesToString: function (b) { - return decodeURIComponent(escape(g.bytesToString(b))) - } - }; - var g = d.Binary = { - stringToBytes: function (b) { - for (var a = [], c = 0; c < b.length; c++) a.push(b.charCodeAt(c) & 255); + endian: function (b) { + if (b.constructor == Number) return k.rotl(b, 8) & 16711935 | k.rotl(b, 24) & 4278255360; + for (var a = 0; a < b.length; a++) b[a] = k.endian(b[a]); + return b + }, + randomBytes: function (b) { + for (var a = []; b > 0; b--) a.push(Math.floor(Math.random() * 256)); return a }, - bytesToString: function (b) { - for (var a = [], c = 0; c < b.length; c++) a.push(String.fromCharCode(b[c])); + bytesToWords: function (b) { + for (var a = [], c = 0, e = 0; c < b.length; c++, e += 8) a[e >>> 5] |= (b[c] & 255) << + 24 - e % 32; + return a + }, + wordsToBytes: function (b) { + for (var a = [], c = 0; c < b.length * 32; c += 8) a.push(b[c >>> 5] >>> 24 - c % 32 & 255); + return a + }, + bytesToHex: function (b) { + for (var a = [], c = 0; c < b.length; c++) a.push((b[c] >>> 4).toString(16)), a.push((b[c] & + 15).toString(16)); return a.join("") + }, + hexToBytes: function (b) { + for (var a = [], c = 0; c < b.length; c += 2) a.push(parseInt(b.substr(c, 2), 16)); + return a + }, + bytesToBase64: function (b) { + for (var a = [], c = 0; c < b.length; c += 3) + for (var e = b[c] << 16 | b[c + 1] << 8 | b[c + 2], p = 0; p < 4; p++) c * 8 + p * 6 <= + b.length * 8 ? a.push( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e >>> + 6 * (3 - p) & 63)) : a.push("="); + return a.join("") + }, + base64ToBytes: function (b) { + for (var b = b.replace(/[^A-Z0-9+\/]/ig, ""), a = [], c = 0, e = 0; c < b.length; e = ++c % + 4) e != 0 && a.push(("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + .indexOf(b.charAt(c - 1)) & Math.pow(2, -2 * e + 8) - 1) << e * 2 | + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(b.charAt( + c)) >>> 6 - e * 2); + return a } + }, + d = d.charenc = {}; + d.UTF8 = { + stringToBytes: function (b) { + return g.stringToBytes(unescape(encodeURIComponent(b))) + }, + bytesToString: function (b) { + return decodeURIComponent(escape(g.bytesToString(b))) } - }(); - (function () { - var d = Crypto, - k = d.util, - g = d.charenc, - b = g.UTF8, - a = g.Binary, - c = [1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, - 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, - 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, - 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, - 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, - 2730485921, - 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, - 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, - 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 - ], - e = d.SHA256 = function (b, c) { - var f = k.wordsToBytes(e._sha256(b)); - return c && c.asBytes ? f : c && c.asString ? a.bytesToString(f) : k.bytesToHex(f) - }; - e._sha256 = function (a) { - a.constructor == String && (a = b.stringToBytes(a)); - var e = k.bytesToWords(a), - f = a.length * 8, - a = [1779033703, 3144134277, - 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225 - ], - d = [], - g, m, r, i, n, o, s, t, h, l, j; - e[f >> 5] |= 128 << 24 - f % 32; - e[(f + 64 >> 9 << 4) + 15] = f; - for (t = 0; t < e.length; t += 16) { - f = a[0]; - g = a[1]; - m = a[2]; - r = a[3]; - i = a[4]; - n = a[5]; - o = a[6]; - s = a[7]; - for (h = 0; h < 64; h++) { - h < 16 ? d[h] = e[h + t] : (l = d[h - 15], j = d[h - 2], d[h] = ((l << 25 | l >>> 7) ^ - (l << 14 | l >>> 18) ^ l >>> 3) + (d[h - 7] >>> 0) + ((j << 15 | j >>> 17) ^ - (j << 13 | j >>> 19) ^ j >>> 10) + (d[h - 16] >>> 0)); - j = f & g ^ f & m ^ g & m; - var u = (f << 30 | f >>> 2) ^ (f << 19 | f >>> 13) ^ (f << 10 | f >>> 22); - l = (s >>> 0) + ((i << 26 | i >>> 6) ^ (i << 21 | i >>> 11) ^ (i << 7 | i >>> 25)) + - (i & n ^ ~i & o) + c[h] + (d[h] >>> 0); - j = u + j; - s = o; - o = n; - n = i; - i = r + l >>> 0; - r = m; - m = g; - g = f; - f = l + j >>> 0 - } - a[0] += f; - a[1] += g; - a[2] += m; - a[3] += r; - a[4] += i; - a[5] += n; - a[6] += o; - a[7] += s - } + }; + var g = d.Binary = { + stringToBytes: function (b) { + for (var a = [], c = 0; c < b.length; c++) a.push(b.charCodeAt(c) & 255); return a + }, + bytesToString: function (b) { + for (var a = [], c = 0; c < b.length; c++) a.push(String.fromCharCode(b[c])); + return a.join("") + } + } + }(); + (function () { + var d = Crypto, + k = d.util, + g = d.charenc, + b = g.UTF8, + a = g.Binary, + c = [1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, + 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, + 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, + 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, + 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, + 2730485921, + 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, + 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, + 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 + ], + e = d.SHA256 = function (b, c) { + var f = k.wordsToBytes(e._sha256(b)); + return c && c.asBytes ? f : c && c.asString ? a.bytesToString(f) : k.bytesToHex(f) }; - e._blocksize = 16; - e._digestsize = 32 - })(); - (function () { - var d = Crypto, - k = d.util, - g = d.charenc, - b = g.UTF8, - a = g.Binary; - d.HMAC = function (c, e, d, g) { - e.constructor == String && (e = b.stringToBytes(e)); - d.constructor == String && (d = b.stringToBytes(d)); - d.length > c._blocksize * 4 && (d = c(d, { - asBytes: !0 - })); - for (var f = d.slice(0), d = d.slice(0), q = 0; q < c._blocksize * 4; q++) f[q] ^= 92, d[q] ^= - 54; - c = c(f.concat(c(d.concat(e), { - asBytes: !0 - })), { - asBytes: !0 - }); - return g && g.asBytes ? c : g && g.asString ? a.bytesToString(c) : k.bytesToHex(c) - } - })(); - - - /*! - * Random number generator with ArcFour PRNG - * - * NOTE: For best results, put code like - * - * in your main HTML document. - * - * Copyright Tom Wu, bitaddress.org BSD License. - * http://www-cs-students.stanford.edu/~tjw/jsbn/LICENSE - */ - (function () { - - // Constructor function of Global SecureRandom object - var sr = window.SecureRandom = function () { }; - - // Properties - sr.state; - sr.pool; - sr.pptr; - sr.poolCopyOnInit; - - // Pool size must be a multiple of 4 and greater than 32. - // An array of bytes the size of the pool will be passed to init() - sr.poolSize = 256; - - // --- object methods --- - - // public method - // ba: byte array - sr.prototype.nextBytes = function (ba) { - var i; - if (window.crypto && window.crypto.getRandomValues && window.Uint8Array) { - try { - var rvBytes = new Uint8Array(ba.length); - window.crypto.getRandomValues(rvBytes); - for (i = 0; i < ba.length; ++i) - ba[i] = sr.getByte() ^ rvBytes[i]; - return; - } catch (e) { - alert(e); + e._sha256 = function (a) { + a.constructor == String && (a = b.stringToBytes(a)); + var e = k.bytesToWords(a), + f = a.length * 8, + a = [1779033703, 3144134277, + 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225 + ], + d = [], + g, m, r, i, n, o, s, t, h, l, j; + e[f >> 5] |= 128 << 24 - f % 32; + e[(f + 64 >> 9 << 4) + 15] = f; + for (t = 0; t < e.length; t += 16) { + f = a[0]; + g = a[1]; + m = a[2]; + r = a[3]; + i = a[4]; + n = a[5]; + o = a[6]; + s = a[7]; + for (h = 0; h < 64; h++) { + h < 16 ? d[h] = e[h + t] : (l = d[h - 15], j = d[h - 2], d[h] = ((l << 25 | l >>> 7) ^ + (l << 14 | l >>> 18) ^ l >>> 3) + (d[h - 7] >>> 0) + ((j << 15 | j >>> 17) ^ + (j << 13 | j >>> 19) ^ j >>> 10) + (d[h - 16] >>> 0)); + j = f & g ^ f & m ^ g & m; + var u = (f << 30 | f >>> 2) ^ (f << 19 | f >>> 13) ^ (f << 10 | f >>> 22); + l = (s >>> 0) + ((i << 26 | i >>> 6) ^ (i << 21 | i >>> 11) ^ (i << 7 | i >>> 25)) + + (i & n ^ ~i & o) + c[h] + (d[h] >>> 0); + j = u + j; + s = o; + o = n; + n = i; + i = r + l >>> 0; + r = m; + m = g; + g = f; + f = l + j >>> 0 + } + a[0] += f; + a[1] += g; + a[2] += m; + a[3] += r; + a[4] += i; + a[5] += n; + a[6] += o; + a[7] += s } + return a + }; + e._blocksize = 16; + e._digestsize = 32 + })(); + (function () { + var d = Crypto, + k = d.util, + g = d.charenc, + b = g.UTF8, + a = g.Binary; + d.HMAC = function (c, e, d, g) { + e.constructor == String && (e = b.stringToBytes(e)); + d.constructor == String && (d = b.stringToBytes(d)); + d.length > c._blocksize * 4 && (d = c(d, { + asBytes: !0 + })); + for (var f = d.slice(0), d = d.slice(0), q = 0; q < c._blocksize * 4; q++) f[q] ^= 92, d[q] ^= + 54; + c = c(f.concat(c(d.concat(e), { + asBytes: !0 + })), { + asBytes: !0 + }); + return g && g.asBytes ? c : g && g.asString ? a.bytesToString(c) : k.bytesToHex(c) + } + })(); + + +/*! +* Random number generator with ArcFour PRNG +* +* NOTE: For best results, put code like +* +* in your main HTML document. +* +* Copyright Tom Wu, bitaddress.org BSD License. +* http://www-cs-students.stanford.edu/~tjw/jsbn/LICENSE +*/ +(function () { + + // Constructor function of Global SecureRandom object + var sr = window.SecureRandom = function () { }; + + // Properties + sr.state; + sr.pool; + sr.pptr; + sr.poolCopyOnInit; + + // Pool size must be a multiple of 4 and greater than 32. + // An array of bytes the size of the pool will be passed to init() + sr.poolSize = 256; + + // --- object methods --- + + // public method + // ba: byte array + sr.prototype.nextBytes = function (ba) { + var i; + if (window.crypto && window.crypto.getRandomValues && window.Uint8Array) { + try { + var rvBytes = new Uint8Array(ba.length); + window.crypto.getRandomValues(rvBytes); + for (i = 0; i < ba.length; ++i) + ba[i] = sr.getByte() ^ rvBytes[i]; + return; + } catch (e) { + alert(e); } - for (i = 0; i < ba.length; ++i) ba[i] = sr.getByte(); - }; - - - // --- static methods --- - - // Mix in the current time (w/milliseconds) into the pool - // NOTE: this method should be called from body click/keypress event handlers to increase entropy - sr.seedTime = function () { - sr.seedInt(new Date().getTime()); } - - sr.getByte = function () { - if (sr.state == null) { - sr.seedTime(); - sr.state = sr.ArcFour(); // Plug in your RNG constructor here - sr.state.init(sr.pool); - sr.poolCopyOnInit = []; - for (sr.pptr = 0; sr.pptr < sr.pool.length; ++sr.pptr) - sr.poolCopyOnInit[sr.pptr] = sr.pool[sr.pptr]; - sr.pptr = 0; - } - // TODO: allow reseeding after first request - return sr.state.next(); - } - - // Mix in a 32-bit integer into the pool - sr.seedInt = function (x) { - sr.seedInt8(x); - sr.seedInt8((x >> 8)); - sr.seedInt8((x >> 16)); - sr.seedInt8((x >> 24)); - } - - // Mix in a 16-bit integer into the pool - sr.seedInt16 = function (x) { - sr.seedInt8(x); - sr.seedInt8((x >> 8)); - } - - // Mix in a 8-bit integer into the pool - sr.seedInt8 = function (x) { - sr.pool[sr.pptr++] ^= x & 255; - if (sr.pptr >= sr.poolSize) sr.pptr -= sr.poolSize; - } - - // Arcfour is a PRNG - sr.ArcFour = function () { - function Arcfour() { - this.i = 0; - this.j = 0; - this.S = new Array(); - } - - // Initialize arcfour context from key, an array of ints, each from [0..255] - function ARC4init(key) { - var i, j, t; - for (i = 0; i < 256; ++i) - this.S[i] = i; - j = 0; - for (i = 0; i < 256; ++i) { - j = (j + this.S[i] + key[i % key.length]) & 255; - t = this.S[i]; - this.S[i] = this.S[j]; - this.S[j] = t; - } - this.i = 0; - this.j = 0; - } - - function ARC4next() { - var t; - this.i = (this.i + 1) & 255; - this.j = (this.j + this.S[this.i]) & 255; - t = this.S[this.i]; - this.S[this.i] = this.S[this.j]; - this.S[this.j] = t; - return this.S[(t + this.S[this.i]) & 255]; - } - - Arcfour.prototype.init = ARC4init; - Arcfour.prototype.next = ARC4next; - - return new Arcfour(); - }; - - - // Initialize the pool with junk if needed. - if (sr.pool == null) { - sr.pool = new Array(); - sr.pptr = 0; - var t; - if (window.crypto && window.crypto.getRandomValues && window.Uint8Array) { - try { - // Use webcrypto if available - var ua = new Uint8Array(sr.poolSize); - window.crypto.getRandomValues(ua); - for (t = 0; t < sr.poolSize; ++t) - sr.pool[sr.pptr++] = ua[t]; - } catch (e) { alert(e); } - } - while (sr.pptr < sr.poolSize) { // extract some randomness from Math.random() - t = Math.floor(65536 * Math.random()); - sr.pool[sr.pptr++] = t >>> 8; - sr.pool[sr.pptr++] = t & 255; - } - sr.pptr = Math.floor(sr.poolSize * Math.random()); + for (i = 0; i < ba.length; ++i) ba[i] = sr.getByte(); + }; + + + // --- static methods --- + + // Mix in the current time (w/milliseconds) into the pool + // NOTE: this method should be called from body click/keypress event handlers to increase entropy + sr.seedTime = function () { + sr.seedInt(new Date().getTime()); + } + + sr.getByte = function () { + if (sr.state == null) { sr.seedTime(); - // entropy - var entropyStr = ""; - // screen size and color depth: ~4.8 to ~5.4 bits - entropyStr += (window.screen.height * window.screen.width * window.screen.colorDepth); - entropyStr += (window.screen.availHeight * window.screen.availWidth * window.screen.pixelDepth); - // time zone offset: ~4 bits - var dateObj = new Date(); - var timeZoneOffset = dateObj.getTimezoneOffset(); - entropyStr += timeZoneOffset; - // user agent: ~8.3 to ~11.6 bits - entropyStr += navigator.userAgent; - // browser plugin details: ~16.2 to ~21.8 bits - var pluginsStr = ""; - for (var i = 0; i < navigator.plugins.length; i++) { - pluginsStr += navigator.plugins[i].name + " " + navigator.plugins[i].filename + " " + navigator.plugins[i].description + " " + navigator.plugins[i].version + ", "; - } - var mimeTypesStr = ""; - for (var i = 0; i < navigator.mimeTypes.length; i++) { - mimeTypesStr += navigator.mimeTypes[i].description + " " + navigator.mimeTypes[i].type + " " + navigator.mimeTypes[i].suffixes + ", "; - } - entropyStr += pluginsStr + mimeTypesStr; - // cookies and storage: 1 bit - entropyStr += navigator.cookieEnabled + typeof (sessionStorage) + typeof (localStorage); - // language: ~7 bit - entropyStr += navigator.language; - // history: ~2 bit - entropyStr += window.history.length; - // location - entropyStr += window.location; - - var entropyBytes = Crypto.SHA256(entropyStr, { asBytes: true }); - for (var i = 0 ; i < entropyBytes.length ; i++) { - sr.seedInt8(entropyBytes[i]); - } + sr.state = sr.ArcFour(); // Plug in your RNG constructor here + sr.state.init(sr.pool); + sr.poolCopyOnInit = []; + for (sr.pptr = 0; sr.pptr < sr.pool.length; ++sr.pptr) + sr.poolCopyOnInit[sr.pptr] = sr.pool[sr.pptr]; + sr.pptr = 0; } - })(); - - - //ripemd160.js - /* - CryptoJS v3.1.2 - code.google.com/p/crypto-js - (c) 2009-2013 by Jeff Mott. All rights reserved. - code.google.com/p/crypto-js/wiki/License - */ - /** @preserve - (c) 2012 by Cédric Mesnil. All rights reserved. - Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - // Constants table - var zl = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 - ]; - var zr = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 - ]; - var sl = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 - ]; - var sr = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 - ]; - - var hl = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]; - var hr = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]; - - var bytesToWords = function (bytes) { - var words = []; - for (var i = 0, b = 0; i < bytes.length; i++, b += 8) { - words[b >>> 5] |= bytes[i] << (24 - b % 32); - } - return words; - }; - - var wordsToBytes = function (words) { - var bytes = []; - for (var b = 0; b < words.length * 32; b += 8) { - bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); - } - return bytes; - }; - - var processBlock = function (H, M, offset) { - - // Swap endian - for (var i = 0; i < 16; i++) { - var offset_i = offset + i; - var M_offset_i = M[offset_i]; - - // Swap - M[offset_i] = ( - (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | - (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) - ); - } - - // Working variables - var al, bl, cl, dl, el; - var ar, br, cr, dr, er; - - ar = al = H[0]; - br = bl = H[1]; - cr = cl = H[2]; - dr = dl = H[3]; - er = el = H[4]; - // Computation - var t; - for (var i = 0; i < 80; i += 1) { - t = (al + M[offset + zl[i]]) | 0; - if (i < 16) { - t += f1(bl, cl, dl) + hl[0]; - } else if (i < 32) { - t += f2(bl, cl, dl) + hl[1]; - } else if (i < 48) { - t += f3(bl, cl, dl) + hl[2]; - } else if (i < 64) { - t += f4(bl, cl, dl) + hl[3]; - } else { // if (i<80) { - t += f5(bl, cl, dl) + hl[4]; - } - t = t | 0; - t = rotl(t, sl[i]); - t = (t + el) | 0; - al = el; - el = dl; - dl = rotl(cl, 10); - cl = bl; - bl = t; - - t = (ar + M[offset + zr[i]]) | 0; - if (i < 16) { - t += f5(br, cr, dr) + hr[0]; - } else if (i < 32) { - t += f4(br, cr, dr) + hr[1]; - } else if (i < 48) { - t += f3(br, cr, dr) + hr[2]; - } else if (i < 64) { - t += f2(br, cr, dr) + hr[3]; - } else { // if (i<80) { - t += f1(br, cr, dr) + hr[4]; - } - t = t | 0; - t = rotl(t, sr[i]); - t = (t + er) | 0; - ar = er; - er = dr; - dr = rotl(cr, 10); - cr = br; - br = t; - } - // Intermediate hash value - t = (H[1] + cl + dr) | 0; - H[1] = (H[2] + dl + er) | 0; - H[2] = (H[3] + el + ar) | 0; - H[3] = (H[4] + al + br) | 0; - H[4] = (H[0] + bl + cr) | 0; - H[0] = t; - }; - - function f1(x, y, z) { - return ((x) ^ (y) ^ (z)); + // TODO: allow reseeding after first request + return sr.state.next(); + } + + // Mix in a 32-bit integer into the pool + sr.seedInt = function (x) { + sr.seedInt8(x); + sr.seedInt8((x >> 8)); + sr.seedInt8((x >> 16)); + sr.seedInt8((x >> 24)); + } + + // Mix in a 16-bit integer into the pool + sr.seedInt16 = function (x) { + sr.seedInt8(x); + sr.seedInt8((x >> 8)); + } + + // Mix in a 8-bit integer into the pool + sr.seedInt8 = function (x) { + sr.pool[sr.pptr++] ^= x & 255; + if (sr.pptr >= sr.poolSize) sr.pptr -= sr.poolSize; + } + + // Arcfour is a PRNG + sr.ArcFour = function () { + function Arcfour() { + this.i = 0; + this.j = 0; + this.S = new Array(); + } + + // Initialize arcfour context from key, an array of ints, each from [0..255] + function ARC4init(key) { + var i, j, t; + for (i = 0; i < 256; ++i) + this.S[i] = i; + j = 0; + for (i = 0; i < 256; ++i) { + j = (j + this.S[i] + key[i % key.length]) & 255; + t = this.S[i]; + this.S[i] = this.S[j]; + this.S[j] = t; } - - function f2(x, y, z) { - return (((x) & (y)) | ((~x) & (z))); + this.i = 0; + this.j = 0; + } + + function ARC4next() { + var t; + this.i = (this.i + 1) & 255; + this.j = (this.j + this.S[this.i]) & 255; + t = this.S[this.i]; + this.S[this.i] = this.S[this.j]; + this.S[this.j] = t; + return this.S[(t + this.S[this.i]) & 255]; + } + + Arcfour.prototype.init = ARC4init; + Arcfour.prototype.next = ARC4next; + + return new Arcfour(); + }; + + + // Initialize the pool with junk if needed. + if (sr.pool == null) { + sr.pool = new Array(); + sr.pptr = 0; + var t; + if (window.crypto && window.crypto.getRandomValues && window.Uint8Array) { + try { + // Use webcrypto if available + var ua = new Uint8Array(sr.poolSize); + window.crypto.getRandomValues(ua); + for (t = 0; t < sr.poolSize; ++t) + sr.pool[sr.pptr++] = ua[t]; + } catch (e) { alert(e); } + } + while (sr.pptr < sr.poolSize) { // extract some randomness from Math.random() + t = Math.floor(65536 * Math.random()); + sr.pool[sr.pptr++] = t >>> 8; + sr.pool[sr.pptr++] = t & 255; + } + sr.pptr = Math.floor(sr.poolSize * Math.random()); + sr.seedTime(); + // entropy + var entropyStr = ""; + // screen size and color depth: ~4.8 to ~5.4 bits + entropyStr += (window.screen.height * window.screen.width * window.screen.colorDepth); + entropyStr += (window.screen.availHeight * window.screen.availWidth * window.screen.pixelDepth); + // time zone offset: ~4 bits + var dateObj = new Date(); + var timeZoneOffset = dateObj.getTimezoneOffset(); + entropyStr += timeZoneOffset; + // user agent: ~8.3 to ~11.6 bits + entropyStr += navigator.userAgent; + // browser plugin details: ~16.2 to ~21.8 bits + var pluginsStr = ""; + for (var i = 0; i < navigator.plugins.length; i++) { + pluginsStr += navigator.plugins[i].name + " " + navigator.plugins[i].filename + " " + navigator.plugins[i].description + " " + navigator.plugins[i].version + ", "; + } + var mimeTypesStr = ""; + for (var i = 0; i < navigator.mimeTypes.length; i++) { + mimeTypesStr += navigator.mimeTypes[i].description + " " + navigator.mimeTypes[i].type + " " + navigator.mimeTypes[i].suffixes + ", "; + } + entropyStr += pluginsStr + mimeTypesStr; + // cookies and storage: 1 bit + entropyStr += navigator.cookieEnabled + typeof (sessionStorage) + typeof (localStorage); + // language: ~7 bit + entropyStr += navigator.language; + // history: ~2 bit + entropyStr += window.history.length; + // location + entropyStr += window.location; + + var entropyBytes = Crypto.SHA256(entropyStr, { asBytes: true }); + for (var i = 0 ; i < entropyBytes.length ; i++) { + sr.seedInt8(entropyBytes[i]); + } + } +})(); + + + //ripemd160.js + /* + CryptoJS v3.1.2 + code.google.com/p/crypto-js + (c) 2009-2013 by Jeff Mott. All rights reserved. + code.google.com/p/crypto-js/wiki/License + */ + /** @preserve + (c) 2012 by Cédric Mesnil. All rights reserved. + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + // Constants table + var zl = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 + ]; + var zr = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 + ]; + var sl = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 + ]; + var sr = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 + ]; + + var hl = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]; + var hr = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]; + + var bytesToWords = function (bytes) { + var words = []; + for (var i = 0, b = 0; i < bytes.length; i++, b += 8) { + words[b >>> 5] |= bytes[i] << (24 - b % 32); } - - function f3(x, y, z) { - return (((x) | (~(y))) ^ (z)); + return words; + }; + + var wordsToBytes = function (words) { + var bytes = []; + for (var b = 0; b < words.length * 32; b += 8) { + bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); } - - function f4(x, y, z) { - return (((x) & (z)) | ((y) & (~(z)))); - } - - function f5(x, y, z) { - return ((x) ^ ((y) | (~(z)))); - } - - function rotl(x, n) { - return (x << n) | (x >>> (32 - n)); - } - - function ripemd160(message) { - var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]; - - var m = bytesToWords(message); - - var nBitsLeft = message.length * 8; - var nBitsTotal = message.length * 8; - - // Add padding - m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( - (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | - (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) + return bytes; + }; + + var processBlock = function (H, M, offset) { + + // Swap endian + for (var i = 0; i < 16; i++) { + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + // Swap + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); - - for (var i = 0; i < m.length; i += 16) { - processBlock(H, m, i); - } - - // Swap endian - for (var i = 0; i < 5; i++) { - // Shortcut - var H_i = H[i]; - - // Swap - H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | - (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); - } - - var digestbytes = wordsToBytes(H); - return digestbytes; } - - - - - - - // Upstream 'BigInteger' here: - // Original Author: http://www-cs-students.stanford.edu/~tjw/jsbn/ - // Follows 'jsbn' on Github: https://github.com/jasondavies/jsbn - // Review and Testing: https://github.com/cryptocoinjs/bigi/ - /*! - * Basic JavaScript BN library - subset useful for RSA encryption. v1.4 - * - * Copyright (c) 2005 Tom Wu - * All Rights Reserved. - * BSD License - * http://www-cs-students.stanford.edu/~tjw/jsbn/LICENSE - * - * Copyright Stephan Thomas - * Copyright pointbiz - */ - - (function () { - - // (public) Constructor function of Global BigInteger object - var BigInteger = window.BigInteger = function BigInteger(a, b, c) { - if (!(this instanceof BigInteger)) - return new BigInteger(a, b, c); - - if (a != null) - if ("number" == typeof a) this.fromNumber(a, b, c); - else if (b == null && "string" != typeof a) this.fromString(a, 256); - else this.fromString(a, b); - }; - - // Bits per digit - var dbits; - - // JavaScript engine analysis - var canary = 0xdeadbeefcafe; - var j_lm = ((canary & 0xffffff) == 0xefcafe); - - // return new, unset BigInteger - function nbi() { - return new BigInteger(null); + + // Working variables + var al, bl, cl, dl, el; + var ar, br, cr, dr, er; + + ar = al = H[0]; + br = bl = H[1]; + cr = cl = H[2]; + dr = dl = H[3]; + er = el = H[4]; + // Computation + var t; + for (var i = 0; i < 80; i += 1) { + t = (al + M[offset + zl[i]]) | 0; + if (i < 16) { + t += f1(bl, cl, dl) + hl[0]; + } else if (i < 32) { + t += f2(bl, cl, dl) + hl[1]; + } else if (i < 48) { + t += f3(bl, cl, dl) + hl[2]; + } else if (i < 64) { + t += f4(bl, cl, dl) + hl[3]; + } else { // if (i<80) { + t += f5(bl, cl, dl) + hl[4]; } - - // am: Compute w_j += (x*this_i), propagate carries, - // c is initial carry, returns final carry. - // c < 3*dvalue, x < 2*dvalue, this_i < dvalue - // We need to select the fastest one that works in this environment. - - // am1: use a single mult and divide to get the high bits, - // max digit bits should be 26 because - // max internal value = 2*dvalue^2-2*dvalue (< 2^53) - function am1(i, x, w, j, c, n) { - while (--n >= 0) { - var v = x * this[i++] + w[j] + c; - c = Math.floor(v / 0x4000000); - w[j++] = v & 0x3ffffff; - } - return c; + t = t | 0; + t = rotl(t, sl[i]); + t = (t + el) | 0; + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = t; + + t = (ar + M[offset + zr[i]]) | 0; + if (i < 16) { + t += f5(br, cr, dr) + hr[0]; + } else if (i < 32) { + t += f4(br, cr, dr) + hr[1]; + } else if (i < 48) { + t += f3(br, cr, dr) + hr[2]; + } else if (i < 64) { + t += f2(br, cr, dr) + hr[3]; + } else { // if (i<80) { + t += f1(br, cr, dr) + hr[4]; } - // am2 avoids a big mult-and-extract completely. - // Max digit bits should be <= 30 because we do bitwise ops - // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) - function am2(i, x, w, j, c, n) { - var xl = x & 0x7fff, - xh = x >> 15; - while (--n >= 0) { - var l = this[i] & 0x7fff; - var h = this[i++] >> 15; - var m = xh * l + h * xl; - l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); - c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); - w[j++] = l & 0x3fffffff; - } - return c; + t = t | 0; + t = rotl(t, sr[i]); + t = (t + er) | 0; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = t; + } + // Intermediate hash value + t = (H[1] + cl + dr) | 0; + H[1] = (H[2] + dl + er) | 0; + H[2] = (H[3] + el + ar) | 0; + H[3] = (H[4] + al + br) | 0; + H[4] = (H[0] + bl + cr) | 0; + H[0] = t; + }; + + function f1(x, y, z) { + return ((x) ^ (y) ^ (z)); + } + + function f2(x, y, z) { + return (((x) & (y)) | ((~x) & (z))); + } + + function f3(x, y, z) { + return (((x) | (~(y))) ^ (z)); + } + + function f4(x, y, z) { + return (((x) & (z)) | ((y) & (~(z)))); + } + + function f5(x, y, z) { + return ((x) ^ ((y) | (~(z)))); + } + + function rotl(x, n) { + return (x << n) | (x >>> (32 - n)); + } + + function ripemd160(message) { + var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]; + + var m = bytesToWords(message); + + var nBitsLeft = message.length * 8; + var nBitsTotal = message.length * 8; + + // Add padding + m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | + (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) + ); + + for (var i = 0; i < m.length; i += 16) { + processBlock(H, m, i); + } + + // Swap endian + for (var i = 0; i < 5; i++) { + // Shortcut + var H_i = H[i]; + + // Swap + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + var digestbytes = wordsToBytes(H); + return digestbytes; + } + + + + + + + // Upstream 'BigInteger' here: + // Original Author: http://www-cs-students.stanford.edu/~tjw/jsbn/ + // Follows 'jsbn' on Github: https://github.com/jasondavies/jsbn + // Review and Testing: https://github.com/cryptocoinjs/bigi/ + /*! + * Basic JavaScript BN library - subset useful for RSA encryption. v1.4 + * + * Copyright (c) 2005 Tom Wu + * All Rights Reserved. + * BSD License + * http://www-cs-students.stanford.edu/~tjw/jsbn/LICENSE + * + * Copyright Stephan Thomas + * Copyright pointbiz + */ + + (function () { + + // (public) Constructor function of Global BigInteger object + var BigInteger = window.BigInteger = function BigInteger(a, b, c) { + if (!(this instanceof BigInteger)) + return new BigInteger(a, b, c); + + if (a != null) + if ("number" == typeof a) this.fromNumber(a, b, c); + else if (b == null && "string" != typeof a) this.fromString(a, 256); + else this.fromString(a, b); + }; + + // Bits per digit + var dbits; + + // JavaScript engine analysis + var canary = 0xdeadbeefcafe; + var j_lm = ((canary & 0xffffff) == 0xefcafe); + + // return new, unset BigInteger + function nbi() { + return new BigInteger(null); + } + + // am: Compute w_j += (x*this_i), propagate carries, + // c is initial carry, returns final carry. + // c < 3*dvalue, x < 2*dvalue, this_i < dvalue + // We need to select the fastest one that works in this environment. + + // am1: use a single mult and divide to get the high bits, + // max digit bits should be 26 because + // max internal value = 2*dvalue^2-2*dvalue (< 2^53) + function am1(i, x, w, j, c, n) { + while (--n >= 0) { + var v = x * this[i++] + w[j] + c; + c = Math.floor(v / 0x4000000); + w[j++] = v & 0x3ffffff; } - // Alternately, set max digit bits to 28 since some - // browsers slow down when dealing with 32-bit numbers. - function am3(i, x, w, j, c, n) { - var xl = x & 0x3fff, - xh = x >> 14; - while (--n >= 0) { - var l = this[i] & 0x3fff; - var h = this[i++] >> 14; - var m = xh * l + h * xl; - l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; - c = (l >> 28) + (m >> 14) + xh * h; - w[j++] = l & 0xfffffff; - } - return c; + return c; + } + // am2 avoids a big mult-and-extract completely. + // Max digit bits should be <= 30 because we do bitwise ops + // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) + function am2(i, x, w, j, c, n) { + var xl = x & 0x7fff, + xh = x >> 15; + while (--n >= 0) { + var l = this[i] & 0x7fff; + var h = this[i++] >> 15; + var m = xh * l + h * xl; + l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); + c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); + w[j++] = l & 0x3fffffff; } - if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) { - BigInteger.prototype.am = am2; - dbits = 30; - } else if (j_lm && (navigator.appName != "Netscape")) { - BigInteger.prototype.am = am1; - dbits = 26; - } else { // Mozilla/Netscape seems to prefer am3 - BigInteger.prototype.am = am3; - dbits = 28; + return c; + } + // Alternately, set max digit bits to 28 since some + // browsers slow down when dealing with 32-bit numbers. + function am3(i, x, w, j, c, n) { + var xl = x & 0x3fff, + xh = x >> 14; + while (--n >= 0) { + var l = this[i] & 0x3fff; + var h = this[i++] >> 14; + var m = xh * l + h * xl; + l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; + c = (l >> 28) + (m >> 14) + xh * h; + w[j++] = l & 0xfffffff; } - - BigInteger.prototype.DB = dbits; - BigInteger.prototype.DM = ((1 << dbits) - 1); - BigInteger.prototype.DV = (1 << dbits); - - var BI_FP = 52; - BigInteger.prototype.FV = Math.pow(2, BI_FP); - BigInteger.prototype.F1 = BI_FP - dbits; - BigInteger.prototype.F2 = 2 * dbits - BI_FP; - - // Digit conversions - var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; - var BI_RC = new Array(); - var rr, vv; - rr = "0".charCodeAt(0); - for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; - rr = "a".charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - rr = "A".charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - - function int2char(n) { - return BI_RM.charAt(n); + return c; + } + if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) { + BigInteger.prototype.am = am2; + dbits = 30; + } else if (j_lm && (navigator.appName != "Netscape")) { + BigInteger.prototype.am = am1; + dbits = 26; + } else { // Mozilla/Netscape seems to prefer am3 + BigInteger.prototype.am = am3; + dbits = 28; + } + + BigInteger.prototype.DB = dbits; + BigInteger.prototype.DM = ((1 << dbits) - 1); + BigInteger.prototype.DV = (1 << dbits); + + var BI_FP = 52; + BigInteger.prototype.FV = Math.pow(2, BI_FP); + BigInteger.prototype.F1 = BI_FP - dbits; + BigInteger.prototype.F2 = 2 * dbits - BI_FP; + + // Digit conversions + var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; + var BI_RC = new Array(); + var rr, vv; + rr = "0".charCodeAt(0); + for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; + rr = "a".charCodeAt(0); + for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + rr = "A".charCodeAt(0); + for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + + function int2char(n) { + return BI_RM.charAt(n); + } + + function intAt(s, i) { + var c = BI_RC[s.charCodeAt(i)]; + return (c == null) ? -1 : c; + } + + + + // return bigint initialized to value + function nbv(i) { + var r = nbi(); + r.fromInt(i); + return r; + } + + + // returns bit length of the integer x + function nbits(x) { + var r = 1, + t; + if ((t = x >>> 16) != 0) { + x = t; + r += 16; } - - function intAt(s, i) { - var c = BI_RC[s.charCodeAt(i)]; - return (c == null) ? -1 : c; + if ((t = x >> 8) != 0) { + x = t; + r += 8; } - - - - // return bigint initialized to value - function nbv(i) { - var r = nbi(); - r.fromInt(i); - return r; + if ((t = x >> 4) != 0) { + x = t; + r += 4; } - - - // returns bit length of the integer x - function nbits(x) { - var r = 1, - t; - if ((t = x >>> 16) != 0) { - x = t; - r += 16; - } - if ((t = x >> 8) != 0) { - x = t; - r += 8; - } - if ((t = x >> 4) != 0) { - x = t; - r += 4; - } - if ((t = x >> 2) != 0) { - x = t; - r += 2; - } - if ((t = x >> 1) != 0) { - x = t; - r += 1; - } - return r; + if ((t = x >> 2) != 0) { + x = t; + r += 2; } - - - - - - - - // (protected) copy this to r - BigInteger.prototype.copyTo = function (r) { - for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; - r.t = this.t; - r.s = this.s; - }; - - - // (protected) set from integer value x, -DV <= x < DV - BigInteger.prototype.fromInt = function (x) { - this.t = 1; - this.s = (x < 0) ? -1 : 0; - if (x > 0) this[0] = x; - else if (x < -1) this[0] = x + this.DV; - else this.t = 0; - }; - - // (protected) set from string and radix - BigInteger.prototype.fromString = function (s, b) { - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 256) k = 8; // byte array - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else { - this.fromRadix(s, b); - return; + if ((t = x >> 1) != 0) { + x = t; + r += 1; + } + return r; + } + + + + + + + + // (protected) copy this to r + BigInteger.prototype.copyTo = function (r) { + for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; + r.t = this.t; + r.s = this.s; + }; + + + // (protected) set from integer value x, -DV <= x < DV + BigInteger.prototype.fromInt = function (x) { + this.t = 1; + this.s = (x < 0) ? -1 : 0; + if (x > 0) this[0] = x; + else if (x < -1) this[0] = x + this.DV; + else this.t = 0; + }; + + // (protected) set from string and radix + BigInteger.prototype.fromString = function (s, b) { + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 256) k = 8; // byte array + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 4) k = 2; + else { + this.fromRadix(s, b); + return; + } + this.t = 0; + this.s = 0; + var i = s.length, + mi = false, + sh = 0; + while (--i >= 0) { + var x = (k == 8) ? s[i] & 0xff : intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-") mi = true; + continue; } - this.t = 0; - this.s = 0; - var i = s.length, - mi = false, - sh = 0; - while (--i >= 0) { - var x = (k == 8) ? s[i] & 0xff : intAt(s, i); - if (x < 0) { - if (s.charAt(i) == "-") mi = true; - continue; - } - mi = false; - if (sh == 0) - this[this.t++] = x; - else if (sh + k > this.DB) { - this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; - this[this.t++] = (x >> (this.DB - sh)); - } else - this[this.t - 1] |= x << sh; - sh += k; - if (sh >= this.DB) sh -= this.DB; - } - if (k == 8 && (s[0] & 0x80) != 0) { - this.s = -1; - if (sh > 0) this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; - } - this.clamp(); - if (mi) BigInteger.ZERO.subTo(this, this); - }; - - - // (protected) clamp off excess high words - BigInteger.prototype.clamp = function () { - var c = this.s & this.DM; - while (this.t > 0 && this[this.t - 1] == c) --this.t; - }; - - // (protected) r = this << n*DB - BigInteger.prototype.dlShiftTo = function (n, r) { - var i; - for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; - for (i = n - 1; i >= 0; --i) r[i] = 0; - r.t = this.t + n; - r.s = this.s; - }; - - // (protected) r = this >> n*DB - BigInteger.prototype.drShiftTo = function (n, r) { - for (var i = n; i < this.t; ++i) r[i - n] = this[i]; - r.t = Math.max(this.t - n, 0); - r.s = this.s; - }; - - - // (protected) r = this << n - BigInteger.prototype.lShiftTo = function (n, r) { - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << cbs) - 1; - var ds = Math.floor(n / this.DB), - c = (this.s << bs) & this.DM, - i; - for (i = this.t - 1; i >= 0; --i) { - r[i + ds + 1] = (this[i] >> cbs) | c; - c = (this[i] & bm) << bs; - } - for (i = ds - 1; i >= 0; --i) r[i] = 0; - r[ds] = c; - r.t = this.t + ds + 1; - r.s = this.s; - r.clamp(); - }; - - - // (protected) r = this >> n - BigInteger.prototype.rShiftTo = function (n, r) { - r.s = this.s; - var ds = Math.floor(n / this.DB); - if (ds >= this.t) { - r.t = 0; - return; - } - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << bs) - 1; - r[0] = this[ds] >> bs; - for (var i = ds + 1; i < this.t; ++i) { - r[i - ds - 1] |= (this[i] & bm) << cbs; - r[i - ds] = this[i] >> bs; - } - if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; - r.t = this.t - ds; - r.clamp(); - }; - - - // (protected) r = this - a - BigInteger.prototype.subTo = function (a, r) { - var i = 0, - c = 0, - m = Math.min(a.t, this.t); - while (i < m) { - c += this[i] - a[i]; + mi = false; + if (sh == 0) + this[this.t++] = x; + else if (sh + k > this.DB) { + this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; + this[this.t++] = (x >> (this.DB - sh)); + } else + this[this.t - 1] |= x << sh; + sh += k; + if (sh >= this.DB) sh -= this.DB; + } + if (k == 8 && (s[0] & 0x80) != 0) { + this.s = -1; + if (sh > 0) this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; + } + this.clamp(); + if (mi) BigInteger.ZERO.subTo(this, this); + }; + + + // (protected) clamp off excess high words + BigInteger.prototype.clamp = function () { + var c = this.s & this.DM; + while (this.t > 0 && this[this.t - 1] == c) --this.t; + }; + + // (protected) r = this << n*DB + BigInteger.prototype.dlShiftTo = function (n, r) { + var i; + for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; + for (i = n - 1; i >= 0; --i) r[i] = 0; + r.t = this.t + n; + r.s = this.s; + }; + + // (protected) r = this >> n*DB + BigInteger.prototype.drShiftTo = function (n, r) { + for (var i = n; i < this.t; ++i) r[i - n] = this[i]; + r.t = Math.max(this.t - n, 0); + r.s = this.s; + }; + + + // (protected) r = this << n + BigInteger.prototype.lShiftTo = function (n, r) { + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << cbs) - 1; + var ds = Math.floor(n / this.DB), + c = (this.s << bs) & this.DM, + i; + for (i = this.t - 1; i >= 0; --i) { + r[i + ds + 1] = (this[i] >> cbs) | c; + c = (this[i] & bm) << bs; + } + for (i = ds - 1; i >= 0; --i) r[i] = 0; + r[ds] = c; + r.t = this.t + ds + 1; + r.s = this.s; + r.clamp(); + }; + + + // (protected) r = this >> n + BigInteger.prototype.rShiftTo = function (n, r) { + r.s = this.s; + var ds = Math.floor(n / this.DB); + if (ds >= this.t) { + r.t = 0; + return; + } + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << bs) - 1; + r[0] = this[ds] >> bs; + for (var i = ds + 1; i < this.t; ++i) { + r[i - ds - 1] |= (this[i] & bm) << cbs; + r[i - ds] = this[i] >> bs; + } + if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; + r.t = this.t - ds; + r.clamp(); + }; + + + // (protected) r = this - a + BigInteger.prototype.subTo = function (a, r) { + var i = 0, + c = 0, + m = Math.min(a.t, this.t); + while (i < m) { + c += this[i] - a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c -= a.s; + while (i < this.t) { + c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } - if (a.t < this.t) { - c -= a.s; - while (i < this.t) { - c += this[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c -= a[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c -= a.s; + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c -= a[i]; + r[i++] = c & this.DM; + c >>= this.DB; } - r.s = (c < 0) ? -1 : 0; - if (c < -1) r[i++] = this.DV + c; - else if (c > 0) r[i++] = c; - r.t = i; - r.clamp(); - }; - - - // (protected) r = this * a, r != this,a (HAC 14.12) - // "this" should be the larger one if appropriate. - BigInteger.prototype.multiplyTo = function (a, r) { - var x = this.abs(), - y = a.abs(); - var i = x.t; - r.t = i + y.t; - while (--i >= 0) r[i] = 0; - for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); - r.s = 0; - r.clamp(); - if (this.s != a.s) BigInteger.ZERO.subTo(r, r); - }; - - - // (protected) r = this^2, r != this (HAC 14.16) - BigInteger.prototype.squareTo = function (r) { - var x = this.abs(); - var i = r.t = 2 * x.t; - while (--i >= 0) r[i] = 0; - for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x[i], r, 2 * i, 0, 1); - if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { - r[i + x.t] -= x.DV; - r[i + x.t + 1] = 1; - } + c -= a.s; + } + r.s = (c < 0) ? -1 : 0; + if (c < -1) r[i++] = this.DV + c; + else if (c > 0) r[i++] = c; + r.t = i; + r.clamp(); + }; + + + // (protected) r = this * a, r != this,a (HAC 14.12) + // "this" should be the larger one if appropriate. + BigInteger.prototype.multiplyTo = function (a, r) { + var x = this.abs(), + y = a.abs(); + var i = x.t; + r.t = i + y.t; + while (--i >= 0) r[i] = 0; + for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); + r.s = 0; + r.clamp(); + if (this.s != a.s) BigInteger.ZERO.subTo(r, r); + }; + + + // (protected) r = this^2, r != this (HAC 14.16) + BigInteger.prototype.squareTo = function (r) { + var x = this.abs(); + var i = r.t = 2 * x.t; + while (--i >= 0) r[i] = 0; + for (i = 0; i < x.t - 1; ++i) { + var c = x.am(i, x[i], r, 2 * i, 0, 1); + if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { + r[i + x.t] -= x.DV; + r[i + x.t + 1] = 1; } - if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); - r.s = 0; - r.clamp(); - }; - - - - // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) - // r != q, this != m. q or r may be null. - BigInteger.prototype.divRemTo = function (m, q, r) { - var pm = m.abs(); - if (pm.t <= 0) return; - var pt = this.abs(); - if (pt.t < pm.t) { - if (q != null) q.fromInt(0); - if (r != null) this.copyTo(r); - return; - } - if (r == null) r = nbi(); - var y = nbi(), - ts = this.s, - ms = m.s; - var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus - if (nsh > 0) { - pm.lShiftTo(nsh, y); - pt.lShiftTo(nsh, r); - } else { - pm.copyTo(y); - pt.copyTo(r); - } - var ys = y.t; - var y0 = y[ys - 1]; - if (y0 == 0) return; - var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); - var d1 = this.FV / yt, - d2 = (1 << this.F1) / yt, - e = 1 << this.F2; - var i = r.t, - j = i - ys, - t = (q == null) ? nbi() : q; - y.dlShiftTo(j, t); - if (r.compareTo(t) >= 0) { - r[r.t++] = 1; + } + if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); + r.s = 0; + r.clamp(); + }; + + + + // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) + // r != q, this != m. q or r may be null. + BigInteger.prototype.divRemTo = function (m, q, r) { + var pm = m.abs(); + if (pm.t <= 0) return; + var pt = this.abs(); + if (pt.t < pm.t) { + if (q != null) q.fromInt(0); + if (r != null) this.copyTo(r); + return; + } + if (r == null) r = nbi(); + var y = nbi(), + ts = this.s, + ms = m.s; + var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus + if (nsh > 0) { + pm.lShiftTo(nsh, y); + pt.lShiftTo(nsh, r); + } else { + pm.copyTo(y); + pt.copyTo(r); + } + var ys = y.t; + var y0 = y[ys - 1]; + if (y0 == 0) return; + var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); + var d1 = this.FV / yt, + d2 = (1 << this.F1) / yt, + e = 1 << this.F2; + var i = r.t, + j = i - ys, + t = (q == null) ? nbi() : q; + y.dlShiftTo(j, t); + if (r.compareTo(t) >= 0) { + r[r.t++] = 1; + r.subTo(t, r); + } + BigInteger.ONE.dlShiftTo(ys, t); + t.subTo(y, y); // "negative" y so we can replace sub with am later + while (y.t < ys) y[y.t++] = 0; + while (--j >= 0) { + // Estimate quotient digit + var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); + if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out + y.dlShiftTo(j, t); r.subTo(t, r); + while (r[i] < --qd) r.subTo(t, r); } - BigInteger.ONE.dlShiftTo(ys, t); - t.subTo(y, y); // "negative" y so we can replace sub with am later - while (y.t < ys) y[y.t++] = 0; - while (--j >= 0) { - // Estimate quotient digit - var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); - if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out - y.dlShiftTo(j, t); - r.subTo(t, r); - while (r[i] < --qd) r.subTo(t, r); - } + } + if (q != null) { + r.drShiftTo(ys, q); + if (ts != ms) BigInteger.ZERO.subTo(q, q); + } + r.t = ys; + r.clamp(); + if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder + if (ts < 0) BigInteger.ZERO.subTo(r, r); + }; + + + // (protected) return "-1/this % 2^DB"; useful for Mont. reduction + // justification: + // xy == 1 (mod m) + // xy = 1+km + // xy(2-xy) = (1+km)(1-km) + // x[y(2-xy)] = 1-k^2m^2 + // x[y(2-xy)] == 1 (mod m^2) + // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 + // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. + // JS multiply "overflows" differently from C/C++, so care is needed here. + BigInteger.prototype.invDigit = function () { + if (this.t < 1) return 0; + var x = this[0]; + if ((x & 1) == 0) return 0; + var y = x & 3; // y == 1/x mod 2^2 + y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 + y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 + y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly; + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return (y > 0) ? this.DV - y : -y; + }; + + + // (protected) true iff this is even + BigInteger.prototype.isEven = function () { + return ((this.t > 0) ? (this[0] & 1) : this.s) == 0; + }; + + + // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) + BigInteger.prototype.exp = function (e, z) { + if (e > 0xffffffff || e < 1) return BigInteger.ONE; + var r = nbi(), + r2 = nbi(), + g = z.convert(this), + i = nbits(e) - 1; + g.copyTo(r); + while (--i >= 0) { + z.sqrTo(r, r2); + if ((e & (1 << i)) > 0) z.mulTo(r2, g, r); + else { + var t = r; + r = r2; + r2 = t; } - if (q != null) { - r.drShiftTo(ys, q); - if (ts != ms) BigInteger.ZERO.subTo(q, q); + } + return z.revert(r); + }; + + + // (public) return string representation in given radix + BigInteger.prototype.toString = function (b) { + if (this.s < 0) return "-" + this.negate().toString(b); + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 4) k = 2; + else return this.toRadix(b); + var km = (1 << k) - 1, + d, m = false, + r = "", + i = this.t; + var p = this.DB - (i * this.DB) % k; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) > 0) { + m = true; + r = int2char(d); } - r.t = ys; - r.clamp(); - if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder - if (ts < 0) BigInteger.ZERO.subTo(r, r); - }; - - - // (protected) return "-1/this % 2^DB"; useful for Mont. reduction - // justification: - // xy == 1 (mod m) - // xy = 1+km - // xy(2-xy) = (1+km)(1-km) - // x[y(2-xy)] = 1-k^2m^2 - // x[y(2-xy)] == 1 (mod m^2) - // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 - // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. - // JS multiply "overflows" differently from C/C++, so care is needed here. - BigInteger.prototype.invDigit = function () { - if (this.t < 1) return 0; - var x = this[0]; - if ((x & 1) == 0) return 0; - var y = x & 3; // y == 1/x mod 2^2 - y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 - y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 - y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly; - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return (y > 0) ? this.DV - y : -y; - }; - - - // (protected) true iff this is even - BigInteger.prototype.isEven = function () { - return ((this.t > 0) ? (this[0] & 1) : this.s) == 0; - }; - - - // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) - BigInteger.prototype.exp = function (e, z) { - if (e > 0xffffffff || e < 1) return BigInteger.ONE; - var r = nbi(), - r2 = nbi(), - g = z.convert(this), - i = nbits(e) - 1; - g.copyTo(r); - while (--i >= 0) { - z.sqrTo(r, r2); - if ((e & (1 << i)) > 0) z.mulTo(r2, g, r); - else { - var t = r; - r = r2; - r2 = t; - } - } - return z.revert(r); - }; - - - // (public) return string representation in given radix - BigInteger.prototype.toString = function (b) { - if (this.s < 0) return "-" + this.negate().toString(b); - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else return this.toRadix(b); - var km = (1 << k) - 1, - d, m = false, - r = "", - i = this.t; - var p = this.DB - (i * this.DB) % k; - if (i-- > 0) { - if (p < this.DB && (d = this[i] >> p) > 0) { - m = true; - r = int2char(d); - } - while (i >= 0) { - if (p < k) { - d = (this[i] & ((1 << p) - 1)) << (k - p); - d |= this[--i] >> (p += this.DB - k); - } else { - d = (this[i] >> (p -= k)) & km; - if (p <= 0) { - p += this.DB; - --i; - } + while (i >= 0) { + if (p < k) { + d = (this[i] & ((1 << p) - 1)) << (k - p); + d |= this[--i] >> (p += this.DB - k); + } else { + d = (this[i] >> (p -= k)) & km; + if (p <= 0) { + p += this.DB; + --i; } - if (d > 0) m = true; - if (m) r += int2char(d); } + if (d > 0) m = true; + if (m) r += int2char(d); } - return m ? r : "0"; - }; - - - // (public) -this - BigInteger.prototype.negate = function () { - var r = nbi(); - BigInteger.ZERO.subTo(this, r); - return r; - }; - - // (public) |this| - BigInteger.prototype.abs = function () { - return (this.s < 0) ? this.negate() : this; - }; - - // (public) return + if this > a, - if this < a, 0 if equal - BigInteger.prototype.compareTo = function (a) { - var r = this.s - a.s; - if (r != 0) return r; - var i = this.t; - r = i - a.t; - if (r != 0) return (this.s < 0) ? -r : r; - while (--i >= 0) - if ((r = this[i] - a[i]) != 0) return r; - return 0; } - - // (public) return the number of bits in "this" - BigInteger.prototype.bitLength = function () { - if (this.t <= 0) return 0; - return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); - }; - - // (public) this mod a - BigInteger.prototype.mod = function (a) { - var r = nbi(); - this.abs().divRemTo(a, null, r); - if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); - return r; + return m ? r : "0"; + }; + + + // (public) -this + BigInteger.prototype.negate = function () { + var r = nbi(); + BigInteger.ZERO.subTo(this, r); + return r; + }; + + // (public) |this| + BigInteger.prototype.abs = function () { + return (this.s < 0) ? this.negate() : this; + }; + + // (public) return + if this > a, - if this < a, 0 if equal + BigInteger.prototype.compareTo = function (a) { + var r = this.s - a.s; + if (r != 0) return r; + var i = this.t; + r = i - a.t; + if (r != 0) return (this.s < 0) ? -r : r; + while (--i >= 0) + if ((r = this[i] - a[i]) != 0) return r; + return 0; + } + + // (public) return the number of bits in "this" + BigInteger.prototype.bitLength = function () { + if (this.t <= 0) return 0; + return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); + }; + + // (public) this mod a + BigInteger.prototype.mod = function (a) { + var r = nbi(); + this.abs().divRemTo(a, null, r); + if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); + return r; + } + + // (public) this^e % m, 0 <= e < 2^32 + BigInteger.prototype.modPowInt = function (e, m) { + var z; + if (e < 256 || m.isEven()) z = new Classic(m); + else z = new Montgomery(m); + return this.exp(e, z); + }; + + // "constants" + BigInteger.ZERO = nbv(0); + BigInteger.ONE = nbv(1); + + + + + + + + // Copyright (c) 2005-2009 Tom Wu + // All Rights Reserved. + // See "LICENSE" for details. + // Extended JavaScript BN functions, required for RSA private ops. + // Version 1.1: new BigInteger("0", 10) returns "proper" zero + // Version 1.2: square() API, isProbablePrime fix + + + // return index of lowest 1-bit in x, x < 2^31 + function lbit(x) { + if (x == 0) return -1; + var r = 0; + if ((x & 0xffff) == 0) { + x >>= 16; + r += 16; } - - // (public) this^e % m, 0 <= e < 2^32 - BigInteger.prototype.modPowInt = function (e, m) { - var z; - if (e < 256 || m.isEven()) z = new Classic(m); - else z = new Montgomery(m); - return this.exp(e, z); - }; - - // "constants" - BigInteger.ZERO = nbv(0); - BigInteger.ONE = nbv(1); - - - - - - - - // Copyright (c) 2005-2009 Tom Wu - // All Rights Reserved. - // See "LICENSE" for details. - // Extended JavaScript BN functions, required for RSA private ops. - // Version 1.1: new BigInteger("0", 10) returns "proper" zero - // Version 1.2: square() API, isProbablePrime fix - - - // return index of lowest 1-bit in x, x < 2^31 - function lbit(x) { - if (x == 0) return -1; - var r = 0; - if ((x & 0xffff) == 0) { - x >>= 16; - r += 16; - } - if ((x & 0xff) == 0) { - x >>= 8; - r += 8; - } - if ((x & 0xf) == 0) { - x >>= 4; - r += 4; - } - if ((x & 3) == 0) { - x >>= 2; - r += 2; - } - if ((x & 1) == 0) ++r; - return r; + if ((x & 0xff) == 0) { + x >>= 8; + r += 8; } - - // return number of 1 bits in x - function cbit(x) { - var r = 0; - while (x != 0) { - x &= x - 1; - ++r; - } - return r; + if ((x & 0xf) == 0) { + x >>= 4; + r += 4; } - - var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, - 89, - 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, - 193, - 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, - 311, - 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, - 433, - 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, - 569, - 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, - 683, - 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, - 827, - 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, - 971, - 977, 983, 991, 997 - ]; - var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; - - - - // (protected) return x s.t. r^x < DV - BigInteger.prototype.chunkSize = function (r) { - return Math.floor(Math.LN2 * this.DB / Math.log(r)); - }; - - // (protected) convert to radix string - BigInteger.prototype.toRadix = function (b) { - if (b == null) b = 10; - if (this.signum() == 0 || b < 2 || b > 36) return "0"; - var cs = this.chunkSize(b); - var a = Math.pow(b, cs); - var d = nbv(a), - y = nbi(), - z = nbi(), - r = ""; - this.divRemTo(d, y, z); - while (y.signum() > 0) { - r = (a + z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d, y, z); + if ((x & 3) == 0) { + x >>= 2; + r += 2; + } + if ((x & 1) == 0) ++r; + return r; + } + + // return number of 1 bits in x + function cbit(x) { + var r = 0; + while (x != 0) { + x &= x - 1; + ++r; + } + return r; + } + + var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, + 89, + 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, + 193, + 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, + 311, + 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, + 433, + 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, + 569, + 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, + 683, + 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, + 827, + 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, + 971, + 977, 983, 991, 997 + ]; + var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; + + + + // (protected) return x s.t. r^x < DV + BigInteger.prototype.chunkSize = function (r) { + return Math.floor(Math.LN2 * this.DB / Math.log(r)); + }; + + // (protected) convert to radix string + BigInteger.prototype.toRadix = function (b) { + if (b == null) b = 10; + if (this.signum() == 0 || b < 2 || b > 36) return "0"; + var cs = this.chunkSize(b); + var a = Math.pow(b, cs); + var d = nbv(a), + y = nbi(), + z = nbi(), + r = ""; + this.divRemTo(d, y, z); + while (y.signum() > 0) { + r = (a + z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d, y, z); + } + return z.intValue().toString(b) + r; + }; + + // (protected) convert from radix string + BigInteger.prototype.fromRadix = function (s, b) { + this.fromInt(0); + if (b == null) b = 10; + var cs = this.chunkSize(b); + var d = Math.pow(b, cs), + mi = false, + j = 0, + w = 0; + for (var i = 0; i < s.length; ++i) { + var x = intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-" && this.signum() == 0) mi = true; + continue; } - return z.intValue().toString(b) + r; - }; - - // (protected) convert from radix string - BigInteger.prototype.fromRadix = function (s, b) { - this.fromInt(0); - if (b == null) b = 10; - var cs = this.chunkSize(b); - var d = Math.pow(b, cs), - mi = false, - j = 0, - w = 0; - for (var i = 0; i < s.length; ++i) { - var x = intAt(s, i); - if (x < 0) { - if (s.charAt(i) == "-" && this.signum() == 0) mi = true; - continue; - } - w = b * w + x; - if (++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w, 0); - j = 0; - w = 0; - } - } - if (j > 0) { - this.dMultiply(Math.pow(b, j)); + w = b * w + x; + if (++j >= cs) { + this.dMultiply(d); this.dAddOffset(w, 0); + j = 0; + w = 0; } - if (mi) BigInteger.ZERO.subTo(this, this); - }; - - // (protected) alternate constructor - BigInteger.prototype.fromNumber = function (a, b, c) { - if ("number" == typeof b) { - // new BigInteger(int,int,RNG) - if (a < 2) this.fromInt(1); - else { - this.fromNumber(a, c); - if (!this.testBit(a - 1)) // force MSB set - this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); - if (this.isEven()) this.dAddOffset(1, 0); // force odd - while (!this.isProbablePrime(b)) { - this.dAddOffset(2, 0); - if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); - } + } + if (j > 0) { + this.dMultiply(Math.pow(b, j)); + this.dAddOffset(w, 0); + } + if (mi) BigInteger.ZERO.subTo(this, this); + }; + + // (protected) alternate constructor + BigInteger.prototype.fromNumber = function (a, b, c) { + if ("number" == typeof b) { + // new BigInteger(int,int,RNG) + if (a < 2) this.fromInt(1); + else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) // force MSB set + this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + if (this.isEven()) this.dAddOffset(1, 0); // force odd + while (!this.isProbablePrime(b)) { + this.dAddOffset(2, 0); + if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); } - } else { - // new BigInteger(int,RNG) - var x = new Array(), - t = a & 7; - x.length = (a >> 3) + 1; - b.nextBytes(x); - if (t > 0) x[0] &= ((1 << t) - 1); - else x[0] = 0; - this.fromString(x, 256); } - }; - - // (protected) r = this op a (bitwise) - BigInteger.prototype.bitwiseTo = function (a, op, r) { - var i, f, m = Math.min(a.t, this.t); - for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); - if (a.t < this.t) { - f = a.s & this.DM; - for (i = m; i < this.t; ++i) r[i] = op(this[i], f); - r.t = this.t; - } else { - f = this.s & this.DM; - for (i = m; i < a.t; ++i) r[i] = op(f, a[i]); - r.t = a.t; - } - r.s = op(this.s, a.s); - r.clamp(); - }; - - // (protected) this op (1<> 3) + 1; + b.nextBytes(x); + if (t > 0) x[0] &= ((1 << t) - 1); + else x[0] = 0; + this.fromString(x, 256); + } + }; + + // (protected) r = this op a (bitwise) + BigInteger.prototype.bitwiseTo = function (a, op, r) { + var i, f, m = Math.min(a.t, this.t); + for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); + if (a.t < this.t) { + f = a.s & this.DM; + for (i = m; i < this.t; ++i) r[i] = op(this[i], f); + r.t = this.t; + } else { + f = this.s & this.DM; + for (i = m; i < a.t; ++i) r[i] = op(f, a[i]); + r.t = a.t; + } + r.s = op(this.s, a.s); + r.clamp(); + }; + + // (protected) this op (1<>= this.DB; + } + if (a.t < this.t) { + c += a.s; + while (i < this.t) { + c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } - if (a.t < this.t) { - c += a.s; - while (i < this.t) { - c += this[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c += a[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += a.s; + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c += a[i]; + r[i++] = c & this.DM; + c >>= this.DB; } - r.s = (c < 0) ? -1 : 0; - if (c > 0) r[i++] = c; - else if (c < -1) r[i++] = this.DV + c; - r.t = i; - r.clamp(); - }; - - // (protected) this *= n, this >= 0, 1 < n < DV - BigInteger.prototype.dMultiply = function (n) { - this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); - ++this.t; - this.clamp(); - }; - - // (protected) this += n << w words, this >= 0 - BigInteger.prototype.dAddOffset = function (n, w) { - if (n == 0) return; - while (this.t <= w) this[this.t++] = 0; - this[w] += n; - while (this[w] >= this.DV) { - this[w] -= this.DV; - if (++w >= this.t) this[this.t++] = 0; - ++this[w]; - } - }; - - // (protected) r = lower n words of "this * a", a.t <= n - // "this" should be the larger one if appropriate. - BigInteger.prototype.multiplyLowerTo = function (a, n, r) { - var i = Math.min(this.t + a.t, n); - r.s = 0; // assumes a,this >= 0 - r.t = i; - while (i > 0) r[--i] = 0; - var j; - for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); - for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i); - r.clamp(); - }; - - - // (protected) r = "this * a" without lower n words, n > 0 - // "this" should be the larger one if appropriate. - BigInteger.prototype.multiplyUpperTo = function (a, n, r) { - --n; - var i = r.t = this.t + a.t - n; - r.s = 0; // assumes a,this >= 0 - while (--i >= 0) r[i] = 0; - for (i = Math.max(n - this.t, 0); i < a.t; ++i) - r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); - r.clamp(); - r.drShiftTo(1, r); - }; - - // (protected) this % n, n < 2^26 - BigInteger.prototype.modInt = function (n) { - if (n <= 0) return 0; - var d = this.DV % n, - r = (this.s < 0) ? n - 1 : 0; - if (this.t > 0) - if (d == 0) r = this[0] % n; - else - for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n; - return r; - }; - - - // (protected) true if probably prime (HAC 4.24, Miller-Rabin) - BigInteger.prototype.millerRabin = function (t) { - var n1 = this.subtract(BigInteger.ONE); - var k = n1.getLowestSetBit(); - if (k <= 0) return false; - var r = n1.shiftRight(k); - t = (t + 1) >> 1; - if (t > lowprimes.length) t = lowprimes.length; - var a = nbi(); - for (var i = 0; i < t; ++i) { - //Pick bases at random, instead of starting at 2 - a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); - var y = a.modPow(r, this); - if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while (j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2, this); - if (y.compareTo(BigInteger.ONE) == 0) return false; - } - if (y.compareTo(n1) != 0) return false; - } - } - return true; - }; - - - - // (public) - BigInteger.prototype.clone = function () { - var r = nbi(); - this.copyTo(r); - return r; - }; - - // (public) return value as integer - BigInteger.prototype.intValue = function () { - if (this.s < 0) { - if (this.t == 1) return this[0] - this.DV; - else if (this.t == 0) return -1; - } else if (this.t == 1) return this[0]; - else if (this.t == 0) return 0; - // assumes 16 < DB < 32 - return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; - }; - - - // (public) return value as byte - BigInteger.prototype.byteValue = function () { - return (this.t == 0) ? this.s : (this[0] << 24) >> 24; - }; - - // (public) return value as short (assumes DB>=16) - BigInteger.prototype.shortValue = function () { - return (this.t == 0) ? this.s : (this[0] << 16) >> 16; - }; - - // (public) 0 if this == 0, 1 if this > 0 - BigInteger.prototype.signum = function () { - if (this.s < 0) return -1; - else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; - else return 1; - }; - - - // (public) convert to bigendian byte array - BigInteger.prototype.toByteArray = function () { - var i = this.t, - r = new Array(); - r[0] = this.s; - var p = this.DB - (i * this.DB) % 8, - d, k = 0; - if (i-- > 0) { - if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) - r[k++] = d | (this.s << (this.DB - p)); - while (i >= 0) { - if (p < 8) { - d = (this[i] & ((1 << p) - 1)) << (8 - p); - d |= this[--i] >> (p += this.DB - 8); - } else { - d = (this[i] >> (p -= 8)) & 0xff; - if (p <= 0) { - p += this.DB; - --i; - } - } - if ((d & 0x80) != 0) d |= -256; - if (k == 0 && (this.s & 0x80) != (d & 0x80)) ++k; - if (k > 0 || d != this.s) r[k++] = d; - } - } - return r; - }; - - BigInteger.prototype.equals = function (a) { - return (this.compareTo(a) == 0); - }; - BigInteger.prototype.min = function (a) { - return (this.compareTo(a) < 0) ? this : a; - }; - BigInteger.prototype.max = function (a) { - return (this.compareTo(a) > 0) ? this : a; - }; - - // (public) this & a - function op_and(x, y) { - return x & y; + c += a.s; } - BigInteger.prototype.and = function (a) { - var r = nbi(); - this.bitwiseTo(a, op_and, r); - return r; - }; - - // (public) this | a - function op_or(x, y) { - return x | y; + r.s = (c < 0) ? -1 : 0; + if (c > 0) r[i++] = c; + else if (c < -1) r[i++] = this.DV + c; + r.t = i; + r.clamp(); + }; + + // (protected) this *= n, this >= 0, 1 < n < DV + BigInteger.prototype.dMultiply = function (n) { + this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); + ++this.t; + this.clamp(); + }; + + // (protected) this += n << w words, this >= 0 + BigInteger.prototype.dAddOffset = function (n, w) { + if (n == 0) return; + while (this.t <= w) this[this.t++] = 0; + this[w] += n; + while (this[w] >= this.DV) { + this[w] -= this.DV; + if (++w >= this.t) this[this.t++] = 0; + ++this[w]; } - BigInteger.prototype.or = function (a) { - var r = nbi(); - this.bitwiseTo(a, op_or, r); - return r; - }; - - // (public) this ^ a - function op_xor(x, y) { - return x ^ y; - } - BigInteger.prototype.xor = function (a) { - var r = nbi(); - this.bitwiseTo(a, op_xor, r); - return r; - }; - - // (public) this & ~a - function op_andnot(x, y) { - return x & ~y; - } - BigInteger.prototype.andNot = function (a) { - var r = nbi(); - this.bitwiseTo(a, op_andnot, r); - return r; - }; - - // (public) ~this - BigInteger.prototype.not = function () { - var r = nbi(); - for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; - r.t = this.t; - r.s = ~this.s; - return r; - }; - - // (public) this << n - BigInteger.prototype.shiftLeft = function (n) { - var r = nbi(); - if (n < 0) this.rShiftTo(-n, r); - else this.lShiftTo(n, r); - return r; - }; - - // (public) this >> n - BigInteger.prototype.shiftRight = function (n) { - var r = nbi(); - if (n < 0) this.lShiftTo(-n, r); - else this.rShiftTo(n, r); - return r; - }; - - // (public) returns index of lowest 1-bit (or -1 if none) - BigInteger.prototype.getLowestSetBit = function () { - for (var i = 0; i < this.t; ++i) - if (this[i] != 0) return i * this.DB + lbit(this[i]); - if (this.s < 0) return this.t * this.DB; - return -1; - }; - - // (public) return number of set bits - BigInteger.prototype.bitCount = function () { - var r = 0, - x = this.s & this.DM; - for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); - return r; - }; - - // (public) true iff nth bit is set - BigInteger.prototype.testBit = function (n) { - var j = Math.floor(n / this.DB); - if (j >= this.t) return (this.s != 0); - return ((this[j] & (1 << (n % this.DB))) != 0); - }; - - // (public) this | (1<= 0 + r.t = i; + while (i > 0) r[--i] = 0; + var j; + for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); + for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i); + r.clamp(); + }; + + + // (protected) r = "this * a" without lower n words, n > 0 + // "this" should be the larger one if appropriate. + BigInteger.prototype.multiplyUpperTo = function (a, n, r) { + --n; + var i = r.t = this.t + a.t - n; + r.s = 0; // assumes a,this >= 0 + while (--i >= 0) r[i] = 0; + for (i = Math.max(n - this.t, 0); i < a.t; ++i) + r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); + r.clamp(); + r.drShiftTo(1, r); + }; + + // (protected) this % n, n < 2^26 + BigInteger.prototype.modInt = function (n) { + if (n <= 0) return 0; + var d = this.DV % n, + r = (this.s < 0) ? n - 1 : 0; + if (this.t > 0) + if (d == 0) r = this[0] % n; else - z = new Montgomery(m); - - // precomputation - var g = new Array(), - n = 3, - k1 = k - 1, - km = (1 << k) - 1; - g[1] = z.convert(this); - if (k > 1) { - var g2 = nbi(); - z.sqrTo(g[1], g2); - while (n <= km) { - g[n] = nbi(); - z.mulTo(g2, g[n - 2], g[n]); - n += 2; + for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n; + return r; + }; + + + // (protected) true if probably prime (HAC 4.24, Miller-Rabin) + BigInteger.prototype.millerRabin = function (t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if (k <= 0) return false; + var r = n1.shiftRight(k); + t = (t + 1) >> 1; + if (t > lowprimes.length) t = lowprimes.length; + var a = nbi(); + for (var i = 0; i < t; ++i) { + //Pick bases at random, instead of starting at 2 + a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); + var y = a.modPow(r, this); + if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while (j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2, this); + if (y.compareTo(BigInteger.ONE) == 0) return false; } + if (y.compareTo(n1) != 0) return false; } - - var j = e.t - 1, - w, is1 = true, - r2 = nbi(), - t; - i = nbits(e[j]) - 1; - while (j >= 0) { - if (i >= k1) w = (e[j] >> (i - k1)) & km; - else { - w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); - if (j > 0) w |= e[j - 1] >> (this.DB + i - k1); - } - - n = k; - while ((w & 1) == 0) { - w >>= 1; - --n; - } - if ((i -= n) < 0) { - i += this.DB; - --j; - } - if (is1) { // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r); - is1 = false; + } + return true; + }; + + + + // (public) + BigInteger.prototype.clone = function () { + var r = nbi(); + this.copyTo(r); + return r; + }; + + // (public) return value as integer + BigInteger.prototype.intValue = function () { + if (this.s < 0) { + if (this.t == 1) return this[0] - this.DV; + else if (this.t == 0) return -1; + } else if (this.t == 1) return this[0]; + else if (this.t == 0) return 0; + // assumes 16 < DB < 32 + return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; + }; + + + // (public) return value as byte + BigInteger.prototype.byteValue = function () { + return (this.t == 0) ? this.s : (this[0] << 24) >> 24; + }; + + // (public) return value as short (assumes DB>=16) + BigInteger.prototype.shortValue = function () { + return (this.t == 0) ? this.s : (this[0] << 16) >> 16; + }; + + // (public) 0 if this == 0, 1 if this > 0 + BigInteger.prototype.signum = function () { + if (this.s < 0) return -1; + else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; + else return 1; + }; + + + // (public) convert to bigendian byte array + BigInteger.prototype.toByteArray = function () { + var i = this.t, + r = new Array(); + r[0] = this.s; + var p = this.DB - (i * this.DB) % 8, + d, k = 0; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) + r[k++] = d | (this.s << (this.DB - p)); + while (i >= 0) { + if (p < 8) { + d = (this[i] & ((1 << p) - 1)) << (8 - p); + d |= this[--i] >> (p += this.DB - 8); } else { - while (n > 1) { - z.sqrTo(r, r2); - z.sqrTo(r2, r); - n -= 2; + d = (this[i] >> (p -= 8)) & 0xff; + if (p <= 0) { + p += this.DB; + --i; } - if (n > 0) z.sqrTo(r, r2); - else { - t = r; - r = r2; - r2 = t; - } - z.mulTo(r2, g[w], r); } - - while (j >= 0 && (e[j] & (1 << i)) == 0) { + if ((d & 0x80) != 0) d |= -256; + if (k == 0 && (this.s & 0x80) != (d & 0x80)) ++k; + if (k > 0 || d != this.s) r[k++] = d; + } + } + return r; + }; + + BigInteger.prototype.equals = function (a) { + return (this.compareTo(a) == 0); + }; + BigInteger.prototype.min = function (a) { + return (this.compareTo(a) < 0) ? this : a; + }; + BigInteger.prototype.max = function (a) { + return (this.compareTo(a) > 0) ? this : a; + }; + + // (public) this & a + function op_and(x, y) { + return x & y; + } + BigInteger.prototype.and = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_and, r); + return r; + }; + + // (public) this | a + function op_or(x, y) { + return x | y; + } + BigInteger.prototype.or = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_or, r); + return r; + }; + + // (public) this ^ a + function op_xor(x, y) { + return x ^ y; + } + BigInteger.prototype.xor = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_xor, r); + return r; + }; + + // (public) this & ~a + function op_andnot(x, y) { + return x & ~y; + } + BigInteger.prototype.andNot = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_andnot, r); + return r; + }; + + // (public) ~this + BigInteger.prototype.not = function () { + var r = nbi(); + for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; + r.t = this.t; + r.s = ~this.s; + return r; + }; + + // (public) this << n + BigInteger.prototype.shiftLeft = function (n) { + var r = nbi(); + if (n < 0) this.rShiftTo(-n, r); + else this.lShiftTo(n, r); + return r; + }; + + // (public) this >> n + BigInteger.prototype.shiftRight = function (n) { + var r = nbi(); + if (n < 0) this.lShiftTo(-n, r); + else this.rShiftTo(n, r); + return r; + }; + + // (public) returns index of lowest 1-bit (or -1 if none) + BigInteger.prototype.getLowestSetBit = function () { + for (var i = 0; i < this.t; ++i) + if (this[i] != 0) return i * this.DB + lbit(this[i]); + if (this.s < 0) return this.t * this.DB; + return -1; + }; + + // (public) return number of set bits + BigInteger.prototype.bitCount = function () { + var r = 0, + x = this.s & this.DM; + for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); + return r; + }; + + // (public) true iff nth bit is set + BigInteger.prototype.testBit = function (n) { + var j = Math.floor(n / this.DB); + if (j >= this.t) return (this.s != 0); + return ((this[j] & (1 << (n % this.DB))) != 0); + }; + + // (public) this | (1< 1) { + var g2 = nbi(); + z.sqrTo(g[1], g2); + while (n <= km) { + g[n] = nbi(); + z.mulTo(g2, g[n - 2], g[n]); + n += 2; + } + } + + var j = e.t - 1, + w, is1 = true, + r2 = nbi(), + t; + i = nbits(e[j]) - 1; + while (j >= 0) { + if (i >= k1) w = (e[j] >> (i - k1)) & km; + else { + w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); + if (j > 0) w |= e[j - 1] >> (this.DB + i - k1); + } + + n = k; + while ((w & 1) == 0) { + w >>= 1; + --n; + } + if ((i -= n) < 0) { + i += this.DB; + --j; + } + if (is1) { // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r); + is1 = false; + } else { + while (n > 1) { z.sqrTo(r, r2); + z.sqrTo(r2, r); + n -= 2; + } + if (n > 0) z.sqrTo(r, r2); + else { t = r; r = r2; r2 = t; - if (--i < 0) { - i = this.DB - 1; - --j; + } + z.mulTo(r2, g[w], r); + } + + while (j >= 0 && (e[j] & (1 << i)) == 0) { + z.sqrTo(r, r2); + t = r; + r = r2; + r2 = t; + if (--i < 0) { + i = this.DB - 1; + --j; + } + } + } + return z.revert(r); + }; + + // (public) 1/this % m (HAC 14.61) + BigInteger.prototype.modInverse = function (m) { + var ac = m.isEven(); + if (this.signum() === 0) throw new Error('division by zero'); + if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; + var u = m.clone(), + v = this.clone(); + var a = nbv(1), + b = nbv(0), + c = nbv(0), + d = nbv(1); + while (u.signum() != 0) { + while (u.isEven()) { + u.rShiftTo(1, u); + if (ac) { + if (!a.isEven() || !b.isEven()) { + a.addTo(this, a); + b.subTo(m, b); } - } + a.rShiftTo(1, a); + } else if (!b.isEven()) b.subTo(m, b); + b.rShiftTo(1, b); } - return z.revert(r); - }; - - // (public) 1/this % m (HAC 14.61) - BigInteger.prototype.modInverse = function (m) { - var ac = m.isEven(); - if (this.signum() === 0) throw new Error('division by zero'); - if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; - var u = m.clone(), - v = this.clone(); - var a = nbv(1), - b = nbv(0), - c = nbv(0), - d = nbv(1); - while (u.signum() != 0) { - while (u.isEven()) { - u.rShiftTo(1, u); - if (ac) { - if (!a.isEven() || !b.isEven()) { - a.addTo(this, a); - b.subTo(m, b); - } - a.rShiftTo(1, a); - } else if (!b.isEven()) b.subTo(m, b); - b.rShiftTo(1, b); - } - while (v.isEven()) { - v.rShiftTo(1, v); - if (ac) { - if (!c.isEven() || !d.isEven()) { - c.addTo(this, c); - d.subTo(m, d); - } - c.rShiftTo(1, c); - } else if (!d.isEven()) d.subTo(m, d); - d.rShiftTo(1, d); - } - if (u.compareTo(v) >= 0) { - u.subTo(v, u); - if (ac) a.subTo(c, a); - b.subTo(d, b); - } else { - v.subTo(u, v); - if (ac) c.subTo(a, c); - d.subTo(b, d); - } + while (v.isEven()) { + v.rShiftTo(1, v); + if (ac) { + if (!c.isEven() || !d.isEven()) { + c.addTo(this, c); + d.subTo(m, d); + } + c.rShiftTo(1, c); + } else if (!d.isEven()) d.subTo(m, d); + d.rShiftTo(1, d); } - if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; - while (d.compareTo(m) >= 0) d.subTo(m, d); - while (d.signum() < 0) d.addTo(m, d); - return d; - }; - - - // (public) this^e - BigInteger.prototype.pow = function (e) { - return this.exp(e, new NullExp()); - }; - - // (public) gcd(this,a) (HAC 14.54) - BigInteger.prototype.gcd = function (a) { - var x = (this.s < 0) ? this.negate() : this.clone(); - var y = (a.s < 0) ? a.negate() : a.clone(); - if (x.compareTo(y) < 0) { - var t = x; - x = y; - y = t; - } - var i = x.getLowestSetBit(), - g = y.getLowestSetBit(); - if (g < 0) return x; - if (i < g) g = i; - if (g > 0) { - x.rShiftTo(g, x); - y.rShiftTo(g, y); - } - while (x.signum() > 0) { - if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); - if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); - if (x.compareTo(y) >= 0) { - x.subTo(y, x); - x.rShiftTo(1, x); - } else { - y.subTo(x, y); - y.rShiftTo(1, y); - } - } - if (g > 0) y.lShiftTo(g, y); - return y; - }; - - // (public) test primality with certainty >= 1-.5^t - BigInteger.prototype.isProbablePrime = function (t) { - var i, x = this.abs(); - if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { - for (i = 0; i < lowprimes.length; ++i) - if (x[0] == lowprimes[i]) return true; - return false; - } - if (x.isEven()) return false; - i = 1; - while (i < lowprimes.length) { - var m = lowprimes[i], - j = i + 1; - while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; - m = x.modInt(m); - while (i < j) - if (m % lowprimes[i++] == 0) return false; - } - return x.millerRabin(t); - }; - - - // JSBN-specific extension - - // (public) this^2 - BigInteger.prototype.square = function () { - var r = nbi(); - this.squareTo(r); - return r; - }; - - - // NOTE: BigInteger interfaces not implemented in jsbn: - // BigInteger(int signum, byte[] magnitude) - // double doubleValue() - // float floatValue() - // int hashCode() - // long longValue() - // static BigInteger valueOf(long val) - - - - // Copyright Stephan Thomas (start) --- // - // https://raw.github.com/bitcoinjs/bitcoinjs-lib/07f9d55ccb6abd962efb6befdd37671f85ea4ff9/src/util.js - // BigInteger monkey patching - BigInteger.valueOf = nbv; - - /** - * Returns a byte array representation of the big integer. - * - * This returns the absolute of the contained value in big endian - * form. A value of zero results in an empty array. - */ - BigInteger.prototype.toByteArrayUnsigned = function () { - var ba = this.abs().toByteArray(); - if (ba.length) { - if (ba[0] == 0) { - ba = ba.slice(1); - } - return ba.map(function (v) { - return (v < 0) ? v + 256 : v; - }); + if (u.compareTo(v) >= 0) { + u.subTo(v, u); + if (ac) a.subTo(c, a); + b.subTo(d, b); } else { - // Empty array, nothing to do - return ba; + v.subTo(u, v); + if (ac) c.subTo(a, c); + d.subTo(b, d); } - }; - - /** - * Turns a byte array into a big integer. - * - * This function will interpret a byte array as a big integer in big - * endian notation and ignore leading zeros. - */ - BigInteger.fromByteArrayUnsigned = function (ba) { - if (!ba.length) { - return ba.valueOf(0); - } else if (ba[0] & 0x80) { - // Prepend a zero so the BigInteger class doesn't mistake this - // for a negative integer. - return new BigInteger([0].concat(ba)); + } + if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; + while (d.compareTo(m) >= 0) d.subTo(m, d); + while (d.signum() < 0) d.addTo(m, d); + return d; + }; + + + // (public) this^e + BigInteger.prototype.pow = function (e) { + return this.exp(e, new NullExp()); + }; + + // (public) gcd(this,a) (HAC 14.54) + BigInteger.prototype.gcd = function (a) { + var x = (this.s < 0) ? this.negate() : this.clone(); + var y = (a.s < 0) ? a.negate() : a.clone(); + if (x.compareTo(y) < 0) { + var t = x; + x = y; + y = t; + } + var i = x.getLowestSetBit(), + g = y.getLowestSetBit(); + if (g < 0) return x; + if (i < g) g = i; + if (g > 0) { + x.rShiftTo(g, x); + y.rShiftTo(g, y); + } + while (x.signum() > 0) { + if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); + if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); + if (x.compareTo(y) >= 0) { + x.subTo(y, x); + x.rShiftTo(1, x); } else { - return new BigInteger(ba); + y.subTo(x, y); + y.rShiftTo(1, y); } - }; - - /** - * Converts big integer to signed byte representation. - * - * The format for this value uses a the most significant bit as a sign - * bit. If the most significant bit is already occupied by the - * absolute value, an extra byte is prepended and the sign bit is set - * there. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0x81 - * 127 => 0x7f - * -127 => 0xff - * 128 => 0x0080 - * -128 => 0x8080 - * 255 => 0x00ff - * -255 => 0x80ff - * 16300 => 0x3fac - * -16300 => 0xbfac - * 62300 => 0x00f35c - * -62300 => 0x80f35c - */ - BigInteger.prototype.toByteArraySigned = function () { - var val = this.abs().toByteArrayUnsigned(); - var neg = this.compareTo(BigInteger.ZERO) < 0; - - if (neg) { - if (val[0] & 0x80) { - val.unshift(0x80); - } else { - val[0] |= 0x80; - } - } else { - if (val[0] & 0x80) { - val.unshift(0x00); - } - } - - return val; - }; - - /** - * Parse a signed big integer byte representation. - * - * For details on the format please see BigInteger.toByteArraySigned. - */ - BigInteger.fromByteArraySigned = function (ba) { - // Check for negative value - if (ba[0] & 0x80) { - // Remove sign bit - ba[0] &= 0x7f; - - return BigInteger.fromByteArrayUnsigned(ba).negate(); - } else { - return BigInteger.fromByteArrayUnsigned(ba); - } - }; - // Copyright Stephan Thomas (end) --- // - - - - - // ****** REDUCTION ******* // - - // Modular reduction using "classic" algorithm - var Classic = window.Classic = function Classic(m) { - this.m = m; } - Classic.prototype.convert = function (x) { - if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; - }; - Classic.prototype.revert = function (x) { - return x; - }; - Classic.prototype.reduce = function (x) { - x.divRemTo(this.m, null, x); - }; - Classic.prototype.mulTo = function (x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - }; - Classic.prototype.sqrTo = function (x, r) { - x.squareTo(r); - this.reduce(r); - }; - - - - - - // Montgomery reduction - var Montgomery = window.Montgomery = function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp & 0x7fff; - this.mph = this.mp >> 15; - this.um = (1 << (m.DB - 15)) - 1; - this.mt2 = 2 * m.t; + if (g > 0) y.lShiftTo(g, y); + return y; + }; + + // (public) test primality with certainty >= 1-.5^t + BigInteger.prototype.isProbablePrime = function (t) { + var i, x = this.abs(); + if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { + for (i = 0; i < lowprimes.length; ++i) + if (x[0] == lowprimes[i]) return true; + return false; } - // xR mod m - Montgomery.prototype.convert = function (x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t, r); - r.divRemTo(this.m, null, r); - if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); - return r; + if (x.isEven()) return false; + i = 1; + while (i < lowprimes.length) { + var m = lowprimes[i], + j = i + 1; + while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while (i < j) + if (m % lowprimes[i++] == 0) return false; } - // x/R mod m - Montgomery.prototype.revert = function (x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - }; - // x = x/R mod m (HAC 14.32) - Montgomery.prototype.reduce = function (x) { - while (x.t <= this.mt2) // pad x so am has enough room later - x[x.t++] = 0; - for (var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i] & 0x7fff; - var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; - // use am to combine the multiply-shift-add into one call - j = i + this.m.t; - x[j] += this.m.am(0, u0, x, i, 0, this.m.t); - // propagate carry - while (x[j] >= x.DV) { - x[j] -= x.DV; - x[++j]++; - } - } - x.clamp(); - x.drShiftTo(this.m.t, x); - if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - }; - // r = "xy/R mod m"; x,y != r - Montgomery.prototype.mulTo = function (x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - }; - // r = "x^2/R mod m"; x != r - Montgomery.prototype.sqrTo = function (x, r) { - x.squareTo(r); - this.reduce(r); - }; - - - - - - // A "null" reducer - var NullExp = window.NullExp = function NullExp() {} - NullExp.prototype.convert = function (x) { - return x; - }; - NullExp.prototype.revert = function (x) { - return x; - }; - NullExp.prototype.mulTo = function (x, y, r) { - x.multiplyTo(y, r); - }; - NullExp.prototype.sqrTo = function (x, r) { - x.squareTo(r); - }; - - - - - - // Barrett modular reduction - var Barrett = window.Barrett = function Barrett(m) { - // setup Barrett - this.r2 = nbi(); - this.q3 = nbi(); - BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); - this.mu = this.r2.divide(m); - this.m = m; - } - Barrett.prototype.convert = function (x) { - if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); - else if (x.compareTo(this.m) < 0) return x; - else { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - }; - Barrett.prototype.revert = function (x) { - return x; - }; - // x = x mod m (HAC 14.42) - Barrett.prototype.reduce = function (x) { - x.drShiftTo(this.m.t - 1, this.r2); - if (x.t > this.m.t + 1) { - x.t = this.m.t + 1; - x.clamp(); - } - this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); - this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); - while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); - x.subTo(this.r2, x); - while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - }; - // r = x*y mod m; x,y != r - Barrett.prototype.mulTo = function (x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - }; - // r = x^2 mod m; x != r - Barrett.prototype.sqrTo = function (x, r) { - x.squareTo(r); - this.reduce(r); - }; - - })(); - - // BigInteger interfaces not implemented in jsbn: - + return x.millerRabin(t); + }; + + + // JSBN-specific extension + + // (public) this^2 + BigInteger.prototype.square = function () { + var r = nbi(); + this.squareTo(r); + return r; + }; + + + // NOTE: BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) - - - - - - //ellipticcurve.js - /*! - * Basic Javascript Elliptic Curve implementation - * Ported loosely from BouncyCastle's Java EC code - * Only Fp curves implemented for now + + + + // Copyright Stephan Thomas (start) --- // + // https://raw.github.com/bitcoinjs/bitcoinjs-lib/07f9d55ccb6abd962efb6befdd37671f85ea4ff9/src/util.js + // BigInteger monkey patching + BigInteger.valueOf = nbv; + + /** + * Returns a byte array representation of the big integer. + * + * This returns the absolute of the contained value in big endian + * form. A value of zero results in an empty array. + */ + BigInteger.prototype.toByteArrayUnsigned = function () { + var ba = this.abs().toByteArray(); + if (ba.length) { + if (ba[0] == 0) { + ba = ba.slice(1); + } + return ba.map(function (v) { + return (v < 0) ? v + 256 : v; + }); + } else { + // Empty array, nothing to do + return ba; + } + }; + + /** + * Turns a byte array into a big integer. + * + * This function will interpret a byte array as a big integer in big + * endian notation and ignore leading zeros. + */ + BigInteger.fromByteArrayUnsigned = function (ba) { + if (!ba.length) { + return ba.valueOf(0); + } else if (ba[0] & 0x80) { + // Prepend a zero so the BigInteger class doesn't mistake this + // for a negative integer. + return new BigInteger([0].concat(ba)); + } else { + return new BigInteger(ba); + } + }; + + /** + * Converts big integer to signed byte representation. + * + * The format for this value uses a the most significant bit as a sign + * bit. If the most significant bit is already occupied by the + * absolute value, an extra byte is prepended and the sign bit is set + * there. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0x81 + * 127 => 0x7f + * -127 => 0xff + * 128 => 0x0080 + * -128 => 0x8080 + * 255 => 0x00ff + * -255 => 0x80ff + * 16300 => 0x3fac + * -16300 => 0xbfac + * 62300 => 0x00f35c + * -62300 => 0x80f35c + */ + BigInteger.prototype.toByteArraySigned = function () { + var val = this.abs().toByteArrayUnsigned(); + var neg = this.compareTo(BigInteger.ZERO) < 0; + + if (neg) { + if (val[0] & 0x80) { + val.unshift(0x80); + } else { + val[0] |= 0x80; + } + } else { + if (val[0] & 0x80) { + val.unshift(0x00); + } + } + + return val; + }; + + /** + * Parse a signed big integer byte representation. + * + * For details on the format please see BigInteger.toByteArraySigned. + */ + BigInteger.fromByteArraySigned = function (ba) { + // Check for negative value + if (ba[0] & 0x80) { + // Remove sign bit + ba[0] &= 0x7f; + + return BigInteger.fromByteArrayUnsigned(ba).negate(); + } else { + return BigInteger.fromByteArrayUnsigned(ba); + } + }; + // Copyright Stephan Thomas (end) --- // + + + + + // ****** REDUCTION ******* // + + // Modular reduction using "classic" algorithm + var Classic = window.Classic = function Classic(m) { + this.m = m; + } + Classic.prototype.convert = function (x) { + if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; + }; + Classic.prototype.revert = function (x) { + return x; + }; + Classic.prototype.reduce = function (x) { + x.divRemTo(this.m, null, x); + }; + Classic.prototype.mulTo = function (x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + }; + Classic.prototype.sqrTo = function (x, r) { + x.squareTo(r); + this.reduce(r); + }; + + + + + + // Montgomery reduction + var Montgomery = window.Montgomery = function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp & 0x7fff; + this.mph = this.mp >> 15; + this.um = (1 << (m.DB - 15)) - 1; + this.mt2 = 2 * m.t; + } + // xR mod m + Montgomery.prototype.convert = function (x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t, r); + r.divRemTo(this.m, null, r); + if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); + return r; + } + // x/R mod m + Montgomery.prototype.revert = function (x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + }; + // x = x/R mod m (HAC 14.32) + Montgomery.prototype.reduce = function (x) { + while (x.t <= this.mt2) // pad x so am has enough room later + x[x.t++] = 0; + for (var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x[i]*mp mod DV + var j = x[i] & 0x7fff; + var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; + // use am to combine the multiply-shift-add into one call + j = i + this.m.t; + x[j] += this.m.am(0, u0, x, i, 0, this.m.t); + // propagate carry + while (x[j] >= x.DV) { + x[j] -= x.DV; + x[++j]++; + } + } + x.clamp(); + x.drShiftTo(this.m.t, x); + if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); + }; + // r = "xy/R mod m"; x,y != r + Montgomery.prototype.mulTo = function (x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + }; + // r = "x^2/R mod m"; x != r + Montgomery.prototype.sqrTo = function (x, r) { + x.squareTo(r); + this.reduce(r); + }; + + + + + + // A "null" reducer + var NullExp = window.NullExp = function NullExp() {} + NullExp.prototype.convert = function (x) { + return x; + }; + NullExp.prototype.revert = function (x) { + return x; + }; + NullExp.prototype.mulTo = function (x, y, r) { + x.multiplyTo(y, r); + }; + NullExp.prototype.sqrTo = function (x, r) { + x.squareTo(r); + }; + + + + + + // Barrett modular reduction + var Barrett = window.Barrett = function Barrett(m) { + // setup Barrett + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); + this.mu = this.r2.divide(m); + this.m = m; + } + Barrett.prototype.convert = function (x) { + if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); + else if (x.compareTo(this.m) < 0) return x; + else { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + }; + Barrett.prototype.revert = function (x) { + return x; + }; + // x = x mod m (HAC 14.42) + Barrett.prototype.reduce = function (x) { + x.drShiftTo(this.m.t - 1, this.r2); + if (x.t > this.m.t + 1) { + x.t = this.m.t + 1; + x.clamp(); + } + this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); + this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); + while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); + x.subTo(this.r2, x); + while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); + }; + // r = x*y mod m; x,y != r + Barrett.prototype.mulTo = function (x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + }; + // r = x^2 mod m; x != r + Barrett.prototype.sqrTo = function (x, r) { + x.squareTo(r); + this.reduce(r); + }; + + })(); + + // BigInteger interfaces not implemented in jsbn: + + // BigInteger(int signum, byte[] magnitude) + // double doubleValue() + // float floatValue() + // int hashCode() + // long longValue() + // static BigInteger valueOf(long val) + + + + + + //ellipticcurve.js + /*! + * Basic Javascript Elliptic Curve implementation + * Ported loosely from BouncyCastle's Java EC code + * Only Fp curves implemented for now + * + * Copyright Tom Wu, bitaddress.org BSD License. + * http://www-cs-students.stanford.edu/~tjw/jsbn/LICENSE + */ + (function () { + + // Constructor function of Global EllipticCurve object + var ec = window.EllipticCurve = function () {}; + + // ---------------- + // ECFieldElementFp constructor + // q instanceof BigInteger + // x instanceof BigInteger + ec.FieldElementFp = function (q, x) { + this.x = x; + // TODO if(x.compareTo(q) >= 0) error + this.q = q; + }; + + ec.FieldElementFp.prototype.equals = function (other) { + if (other == this) return true; + return (this.q.equals(other.q) && this.x.equals(other.x)); + }; + + ec.FieldElementFp.prototype.toBigInteger = function () { + return this.x; + }; + + ec.FieldElementFp.prototype.negate = function () { + return new ec.FieldElementFp(this.q, this.x.negate().mod(this.q)); + }; + + ec.FieldElementFp.prototype.add = function (b) { + return new ec.FieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); + }; + + ec.FieldElementFp.prototype.subtract = function (b) { + return new ec.FieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); + }; + + ec.FieldElementFp.prototype.multiply = function (b) { + return new ec.FieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); + }; + + ec.FieldElementFp.prototype.square = function () { + return new ec.FieldElementFp(this.q, this.x.square().mod(this.q)); + }; + + ec.FieldElementFp.prototype.divide = function (b) { + return new ec.FieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod( + this.q)); + }; + + ec.FieldElementFp.prototype.getByteLength = function () { + return Math.floor((this.toBigInteger().bitLength() + 7) / 8); + }; + + // D.1.4 91 + /** + * return a sqrt root - the routine verifies that the calculation + * returns the right value - if none exists it returns null. * - * Copyright Tom Wu, bitaddress.org BSD License. - * http://www-cs-students.stanford.edu/~tjw/jsbn/LICENSE + * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) + * Ported to JavaScript by bitaddress.org */ - (function () { - - // Constructor function of Global EllipticCurve object - var ec = window.EllipticCurve = function () {}; - - // ---------------- - // ECFieldElementFp constructor - // q instanceof BigInteger - // x instanceof BigInteger - ec.FieldElementFp = function (q, x) { - this.x = x; - // TODO if(x.compareTo(q) >= 0) error - this.q = q; - }; - - ec.FieldElementFp.prototype.equals = function (other) { - if (other == this) return true; - return (this.q.equals(other.q) && this.x.equals(other.x)); - }; - - ec.FieldElementFp.prototype.toBigInteger = function () { - return this.x; - }; - - ec.FieldElementFp.prototype.negate = function () { - return new ec.FieldElementFp(this.q, this.x.negate().mod(this.q)); - }; - - ec.FieldElementFp.prototype.add = function (b) { - return new ec.FieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); - }; - - ec.FieldElementFp.prototype.subtract = function (b) { - return new ec.FieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); - }; - - ec.FieldElementFp.prototype.multiply = function (b) { - return new ec.FieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); - }; - - ec.FieldElementFp.prototype.square = function () { - return new ec.FieldElementFp(this.q, this.x.square().mod(this.q)); - }; - - ec.FieldElementFp.prototype.divide = function (b) { - return new ec.FieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod( + ec.FieldElementFp.prototype.sqrt = function () { + if (!this.q.testBit(0)) throw new Error("even value of q"); + + // p mod 4 == 3 + if (this.q.testBit(1)) { + // z = g^(u+1) + p, p = 4u + 3 + var z = new ec.FieldElementFp(this.q, this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE), this.q)); - }; - - ec.FieldElementFp.prototype.getByteLength = function () { - return Math.floor((this.toBigInteger().bitLength() + 7) / 8); - }; - - // D.1.4 91 - /** - * return a sqrt root - the routine verifies that the calculation - * returns the right value - if none exists it returns null. - * - * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) - * Ported to JavaScript by bitaddress.org - */ - ec.FieldElementFp.prototype.sqrt = function () { - if (!this.q.testBit(0)) throw new Error("even value of q"); - - // p mod 4 == 3 - if (this.q.testBit(1)) { - // z = g^(u+1) + p, p = 4u + 3 - var z = new ec.FieldElementFp(this.q, this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE), - this.q)); - return z.square().equals(this) ? z : null; - } - - // p mod 4 == 1 - var qMinusOne = this.q.subtract(BigInteger.ONE); - var legendreExponent = qMinusOne.shiftRight(1); - if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) return null; - var u = qMinusOne.shiftRight(2); - var k = u.shiftLeft(1).add(BigInteger.ONE); - var Q = this.x; - var fourQ = Q.shiftLeft(2).mod(this.q); - var U, V; - + return z.square().equals(this) ? z : null; + } + + // p mod 4 == 1 + var qMinusOne = this.q.subtract(BigInteger.ONE); + var legendreExponent = qMinusOne.shiftRight(1); + if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) return null; + var u = qMinusOne.shiftRight(2); + var k = u.shiftLeft(1).add(BigInteger.ONE); + var Q = this.x; + var fourQ = Q.shiftLeft(2).mod(this.q); + var U, V; + + do { + var rand = new SecureRandom(); + var P; do { - var rand = new SecureRandom(); - var P; - do { - P = new BigInteger(this.q.bitLength(), rand); + P = new BigInteger(this.q.bitLength(), rand); + } + while (P.compareTo(this.q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, + this.q).equals(qMinusOne))); + + var result = ec.FieldElementFp.fastLucasSequence(this.q, P, Q, k); + + U = result[0]; + V = result[1]; + if (V.multiply(V).mod(this.q).equals(fourQ)) { + // Integer division by 2, mod q + if (V.testBit(0)) { + V = V.add(this.q); } - while (P.compareTo(this.q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, - this.q).equals(qMinusOne))); - - var result = ec.FieldElementFp.fastLucasSequence(this.q, P, Q, k); - - U = result[0]; - V = result[1]; - if (V.multiply(V).mod(this.q).equals(fourQ)) { - // Integer division by 2, mod q - if (V.testBit(0)) { - V = V.add(this.q); - } - V = V.shiftRight(1); - return new ec.FieldElementFp(this.q, V); + V = V.shiftRight(1); + return new ec.FieldElementFp(this.q, V); + } + } + while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); + + return null; + }; + /*! + * Crypto-JS 2.5.4 BlockModes.js + * contribution from Simon Greatrix + */ + + (function (C) { + + // Create pad namespace + var C_pad = C.pad = {}; + + // Calculate the number of padding bytes required. + function _requiredPadding(cipher, message) { + var blockSizeInBytes = cipher._blocksize * 4; + var reqd = blockSizeInBytes - message.length % blockSizeInBytes; + return reqd; + } + + // Remove padding when the final byte gives the number of padding bytes. + var _unpadLength = function (cipher, message, alg, padding) { + var pad = message.pop(); + if (pad == 0) { + throw new Error("Invalid zero-length padding specified for " + alg + + ". Wrong cipher specification or key used?"); + } + var maxPad = cipher._blocksize * 4; + if (pad > maxPad) { + throw new Error("Invalid padding length of " + pad + + " specified for " + alg + + ". Wrong cipher specification or key used?"); + } + for (var i = 1; i < pad; i++) { + var b = message.pop(); + if (padding != undefined && padding != b) { + throw new Error("Invalid padding byte of 0x" + b.toString(16) + + " specified for " + alg + + ". Wrong cipher specification or key used?"); + } + } + }; + + // No-operation padding, used for stream ciphers + C_pad.NoPadding = { + pad: function (cipher, message) {}, + unpad: function (cipher, message) {} + }; + + // Zero Padding. + // + // If the message is not an exact number of blocks, the final block is + // completed with 0x00 bytes. There is no unpadding. + C_pad.ZeroPadding = { + pad: function (cipher, message) { + var blockSizeInBytes = cipher._blocksize * 4; + var reqd = message.length % blockSizeInBytes; + if (reqd != 0) { + for (reqd = blockSizeInBytes - reqd; reqd > 0; reqd--) { + message.push(0x00); } } - while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); - - return null; - }; - - /* - * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) - * Ported to JavaScript by bitaddress.org - */ - ec.FieldElementFp.fastLucasSequence = function (p, P, Q, k) { - // TODO Research and apply "common-multiplicand multiplication here" - - var n = k.bitLength(); - var s = k.getLowestSetBit(); - var Uh = BigInteger.ONE; - var Vl = BigInteger.TWO; - var Vh = P; - var Ql = BigInteger.ONE; - var Qh = BigInteger.ONE; - - for (var j = n - 1; j >= s + 1; --j) { - Ql = Ql.multiply(Qh).mod(p); - if (k.testBit(j)) { - Qh = Ql.multiply(Q).mod(p); - Uh = Uh.multiply(Vh).mod(p); - Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); - Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p); - } else { - Qh = Ql; - Uh = Uh.multiply(Vl).subtract(Ql).mod(p); - Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); - Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); + }, + + unpad: function (cipher, message) { + while (message[message.length - 1] == 0) { + message.pop(); + } + } + }; + + // ISO/IEC 7816-4 padding. + // + // Pads the plain text with an 0x80 byte followed by as many 0x00 + // bytes are required to complete the block. + C_pad.iso7816 = { + pad: function (cipher, message) { + var reqd = _requiredPadding(cipher, message); + message.push(0x80); + for (; reqd > 1; reqd--) { + message.push(0x00); + } + }, + + unpad: function (cipher, message) { + var padLength; + for (padLength = cipher._blocksize * 4; padLength > 0; padLength--) { + var b = message.pop(); + if (b == 0x80) return; + if (b != 0x00) { + throw new Error("ISO-7816 padding byte must be 0, not 0x" + b.toString(16) + + ". Wrong cipher specification or key used?"); } } - - Ql = Ql.multiply(Qh).mod(p); - Qh = Ql.multiply(Q).mod(p); - Uh = Uh.multiply(Vl).subtract(Ql).mod(p); - Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); - Ql = Ql.multiply(Qh).mod(p); - - for (var j = 1; j <= s; ++j) { - Uh = Uh.multiply(Vl).mod(p); - Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); - Ql = Ql.multiply(Ql).mod(p); + throw new Error( + "ISO-7816 padded beyond cipher block size. Wrong cipher specification or key used?" + ); + } + }; + + // ANSI X.923 padding + // + // The final block is padded with zeros except for the last byte of the + // last block which contains the number of padding bytes. + C_pad.ansix923 = { + pad: function (cipher, message) { + var reqd = _requiredPadding(cipher, message); + for (var i = 1; i < reqd; i++) { + message.push(0x00); } - - return [Uh, Vl]; - }; - - // ---------------- - // ECPointFp constructor - ec.PointFp = function (curve, x, y, z, compressed) { - this.curve = curve; - this.x = x; - this.y = y; - // Projective coordinates: either zinv == null or z * zinv == 1 - // z and zinv are just BigIntegers, not fieldElements - if (z == null) { - this.z = BigInteger.ONE; + message.push(reqd); + }, + + unpad: function (cipher, message) { + _unpadLength(cipher, message, "ANSI X.923", 0); + } + }; + + // ISO 10126 + // + // The final block is padded with random bytes except for the last + // byte of the last block which contains the number of padding bytes. + C_pad.iso10126 = { + pad: function (cipher, message) { + var reqd = _requiredPadding(cipher, message); + for (var i = 1; i < reqd; i++) { + message.push(Math.floor(Math.random() * 256)); + } + message.push(reqd); + }, + + unpad: function (cipher, message) { + _unpadLength(cipher, message, "ISO 10126", undefined); + } + }; + + // PKCS7 padding + // + // PKCS7 is described in RFC 5652. Padding is in whole bytes. The + // value of each added byte is the number of bytes that are added, + // i.e. N bytes, each of value N are added. + C_pad.pkcs7 = { + pad: function (cipher, message) { + var reqd = _requiredPadding(cipher, message); + for (var i = 0; i < reqd; i++) { + message.push(reqd); + } + }, + + unpad: function (cipher, message) { + _unpadLength(cipher, message, "PKCS 7", message[message.length - 1]); + } + }; + + // Create mode namespace + var C_mode = C.mode = {}; + + /** + * Mode base "class". + */ + var Mode = C_mode.Mode = function (padding) { + if (padding) { + this._padding = padding; + } + }; + + Mode.prototype = { + encrypt: function (cipher, m, iv) { + this._padding.pad(cipher, m); + this._doEncrypt(cipher, m, iv); + }, + + decrypt: function (cipher, m, iv) { + this._doDecrypt(cipher, m, iv); + this._padding.unpad(cipher, m); + }, + + // Default padding + _padding: C_pad.iso7816 + }; + + + /** + * Electronic Code Book mode. + * + * ECB applies the cipher directly against each block of the input. + * + * ECB does not require an initialization vector. + */ + var ECB = C_mode.ECB = function () { + // Call parent constructor + Mode.apply(this, arguments); + }; + + // Inherit from Mode + var ECB_prototype = ECB.prototype = new Mode; + + // Concrete steps for Mode template + ECB_prototype._doEncrypt = function (cipher, m, iv) { + var blockSizeInBytes = cipher._blocksize * 4; + // Encrypt each block + for (var offset = 0; offset < m.length; offset += blockSizeInBytes) { + cipher._encryptblock(m, offset); + } + }; + ECB_prototype._doDecrypt = function (cipher, c, iv) { + var blockSizeInBytes = cipher._blocksize * 4; + // Decrypt each block + for (var offset = 0; offset < c.length; offset += blockSizeInBytes) { + cipher._decryptblock(c, offset); + } + }; + + // ECB never uses an IV + ECB_prototype.fixOptions = function (options) { + options.iv = []; + }; + + + /** + * Cipher block chaining + * + * The first block is XORed with the IV. Subsequent blocks are XOR with the + * previous cipher output. + */ + var CBC = C_mode.CBC = function () { + // Call parent constructor + Mode.apply(this, arguments); + }; + + // Inherit from Mode + var CBC_prototype = CBC.prototype = new Mode; + + // Concrete steps for Mode template + CBC_prototype._doEncrypt = function (cipher, m, iv) { + var blockSizeInBytes = cipher._blocksize * 4; + + // Encrypt each block + for (var offset = 0; offset < m.length; offset += blockSizeInBytes) { + if (offset == 0) { + // XOR first block using IV + for (var i = 0; i < blockSizeInBytes; i++) + m[i] ^= iv[i]; } else { - this.z = z; + // XOR this block using previous crypted block + for (var i = 0; i < blockSizeInBytes; i++) + m[offset + i] ^= m[offset + i - blockSizeInBytes]; } - this.zinv = null; - // compression flag - this.compressed = !!compressed; - }; - - ec.PointFp.prototype.getX = function () { - if (this.zinv == null) { - this.zinv = this.z.modInverse(this.curve.q); + // Encrypt block + cipher._encryptblock(m, offset); + } + }; + CBC_prototype._doDecrypt = function (cipher, c, iv) { + var blockSizeInBytes = cipher._blocksize * 4; + + // At the start, the previously crypted block is the IV + var prevCryptedBlock = iv; + + // Decrypt each block + for (var offset = 0; offset < c.length; offset += blockSizeInBytes) { + // Save this crypted block + var thisCryptedBlock = c.slice(offset, offset + blockSizeInBytes); + // Decrypt block + cipher._decryptblock(c, offset); + // XOR decrypted block using previous crypted block + for (var i = 0; i < blockSizeInBytes; i++) { + c[offset + i] ^= prevCryptedBlock[i]; } - var r = this.x.toBigInteger().multiply(this.zinv); - this.curve.reduce(r); - return this.curve.fromBigInteger(r); - }; - - ec.PointFp.prototype.getY = function () { - if (this.zinv == null) { - this.zinv = this.z.modInverse(this.curve.q); + prevCryptedBlock = thisCryptedBlock; + } + }; + + + /** + * Cipher feed back + * + * The cipher output is XORed with the plain text to produce the cipher output, + * which is then fed back into the cipher to produce a bit pattern to XOR the + * next block with. + * + * This is a stream cipher mode and does not require padding. + */ + var CFB = C_mode.CFB = function () { + // Call parent constructor + Mode.apply(this, arguments); + }; + + // Inherit from Mode + var CFB_prototype = CFB.prototype = new Mode; + + // Override padding + CFB_prototype._padding = C_pad.NoPadding; + + // Concrete steps for Mode template + CFB_prototype._doEncrypt = function (cipher, m, iv) { + var blockSizeInBytes = cipher._blocksize * 4, + keystream = iv.slice(0); + + // Encrypt each byte + for (var i = 0; i < m.length; i++) { + + var j = i % blockSizeInBytes; + if (j == 0) cipher._encryptblock(keystream, 0); + + m[i] ^= keystream[j]; + keystream[j] = m[i]; + } + }; + CFB_prototype._doDecrypt = function (cipher, c, iv) { + var blockSizeInBytes = cipher._blocksize * 4, + keystream = iv.slice(0); + + // Encrypt each byte + for (var i = 0; i < c.length; i++) { + + var j = i % blockSizeInBytes; + if (j == 0) cipher._encryptblock(keystream, 0); + + var b = c[i]; + c[i] ^= keystream[j]; + keystream[j] = b; + } + }; + + + /** + * Output feed back + * + * The cipher repeatedly encrypts its own output. The output is XORed with the + * plain text to produce the cipher text. + * + * This is a stream cipher mode and does not require padding. + */ + var OFB = C_mode.OFB = function () { + // Call parent constructor + Mode.apply(this, arguments); + }; + + // Inherit from Mode + var OFB_prototype = OFB.prototype = new Mode; + + // Override padding + OFB_prototype._padding = C_pad.NoPadding; + + // Concrete steps for Mode template + OFB_prototype._doEncrypt = function (cipher, m, iv) { + + var blockSizeInBytes = cipher._blocksize * 4, + keystream = iv.slice(0); + + // Encrypt each byte + for (var i = 0; i < m.length; i++) { + + // Generate keystream + if (i % blockSizeInBytes == 0) + cipher._encryptblock(keystream, 0); + + // Encrypt byte + m[i] ^= keystream[i % blockSizeInBytes]; + + } + }; + OFB_prototype._doDecrypt = OFB_prototype._doEncrypt; + + /** + * Counter + * @author Gergely Risko + * + * After every block the last 4 bytes of the IV is increased by one + * with carry and that IV is used for the next block. + * + * This is a stream cipher mode and does not require padding. + */ + var CTR = C_mode.CTR = function () { + // Call parent constructor + Mode.apply(this, arguments); + }; + + // Inherit from Mode + var CTR_prototype = CTR.prototype = new Mode; + + // Override padding + CTR_prototype._padding = C_pad.NoPadding; + + CTR_prototype._doEncrypt = function (cipher, m, iv) { + var blockSizeInBytes = cipher._blocksize * 4; + var counter = iv.slice(0); + + for (var i = 0; i < m.length;) { + // do not lose iv + var keystream = counter.slice(0); + + // Generate keystream for next block + cipher._encryptblock(keystream, 0); + + // XOR keystream with block + for (var j = 0; i < m.length && j < blockSizeInBytes; j++, i++) { + m[i] ^= keystream[j]; } - var r = this.y.toBigInteger().multiply(this.zinv); - this.curve.reduce(r); - return this.curve.fromBigInteger(r); - }; - - ec.PointFp.prototype.equals = function (other) { - if (other == this) return true; - if (this.isInfinity()) return other.isInfinity(); - if (other.isInfinity()) return this.isInfinity(); - var u, v; - // u = Y2 * Z1 - Y1 * Z2 - u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod( - this.curve.q); - if (!u.equals(BigInteger.ZERO)) return false; - // v = X2 * Z1 - X1 * Z2 - v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod( - this.curve.q); - return v.equals(BigInteger.ZERO); - }; - - ec.PointFp.prototype.isInfinity = function () { - if ((this.x == null) && (this.y == null)) return true; - return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); - }; - - ec.PointFp.prototype.negate = function () { - return new ec.PointFp(this.curve, this.x, this.y.negate(), this.z); - }; - - ec.PointFp.prototype.add = function (b) { - if (this.isInfinity()) return b; - if (b.isInfinity()) return this; - - // u = Y2 * Z1 - Y1 * Z2 - var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod( - this.curve.q); - // v = X2 * Z1 - X1 * Z2 - var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod( - this.curve.q); - - - if (BigInteger.ZERO.equals(v)) { - if (BigInteger.ZERO.equals(u)) { - return this.twice(); // this == b, so double - } - return this.curve.getInfinity(); // this = -b, so infinity - } - - var THREE = new BigInteger("3"); - var x1 = this.x.toBigInteger(); - var y1 = this.y.toBigInteger(); - var x2 = b.x.toBigInteger(); - var y2 = b.y.toBigInteger(); - - var v2 = v.square(); - var v3 = v2.multiply(v); - var x1v2 = x1.multiply(v2); - var zu2 = u.square().multiply(this.z); - - // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) - var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); - // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 - var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply( - b.z).add(u.multiply(v3)).mod(this.curve.q); - // z3 = v^3 * z1 * z2 - var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); - - return new ec.PointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), - z3); - }; - - ec.PointFp.prototype.twice = function () { - if (this.isInfinity()) return this; - if (this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); - - // TODO: optimized handling of constants - var THREE = new BigInteger("3"); - var x1 = this.x.toBigInteger(); - var y1 = this.y.toBigInteger(); - - var y1z1 = y1.multiply(this.z); - var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); - var a = this.curve.a.toBigInteger(); - - // w = 3 * x1^2 + a * z1^2 - var w = x1.square().multiply(THREE); - if (!BigInteger.ZERO.equals(a)) { - w = w.add(this.z.square().multiply(a)); - } - w = w.mod(this.curve.q); - //this.curve.reduce(w); - // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) - var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod( - this.curve.q); - // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 - var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply( - y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); - // z3 = 8 * (y1 * z1)^3 - var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); - - return new ec.PointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), - z3); - }; - - // Simple NAF (Non-Adjacent Form) multiplication algorithm - // TODO: modularize the multiplication algorithm - ec.PointFp.prototype.multiply = function (k) { - if (this.isInfinity()) return this; - if (k.signum() == 0) return this.curve.getInfinity(); - - var e = k; - var h = e.multiply(new BigInteger("3")); - - var neg = this.negate(); - var R = this; - - var i; - for (i = h.bitLength() - 2; i > 0; --i) { - R = R.twice(); - - var hBit = h.testBit(i); - var eBit = e.testBit(i); - - if (hBit != eBit) { - R = R.add(hBit ? this : neg); - } - } - - return R; - }; - - // Compute this*j + x*k (simultaneous multiplication) - ec.PointFp.prototype.multiplyTwo = function (j, x, k) { - var i; - if (j.bitLength() > k.bitLength()) - i = j.bitLength() - 1; - else - i = k.bitLength() - 1; - - var R = this.curve.getInfinity(); - var both = this.add(x); - while (i >= 0) { - R = R.twice(); - if (j.testBit(i)) { - if (k.testBit(i)) { - R = R.add(both); - } else { - R = R.add(this); - } - } else { - if (k.testBit(i)) { - R = R.add(x); + + // Increase counter + if (++(counter[blockSizeInBytes - 1]) == 256) { + counter[blockSizeInBytes - 1] = 0; + if (++(counter[blockSizeInBytes - 2]) == 256) { + counter[blockSizeInBytes - 2] = 0; + if (++(counter[blockSizeInBytes - 3]) == 256) { + counter[blockSizeInBytes - 3] = 0; + ++(counter[blockSizeInBytes - 4]); } } - --i; } - - return R; - }; - - // patched by bitaddress.org and Casascius for use with Bitcoin.ECKey - // patched by coretechs to support compressed public keys - ec.PointFp.prototype.getEncoded = function (compressed) { - var x = this.getX().toBigInteger(); - var y = this.getY().toBigInteger(); - var len = 32; // integerToBytes will zero pad if integer is less than 32 bytes. 32 bytes length is required by the Bitcoin protocol. - var enc = ec.integerToBytes(x, len); - - // when compressed prepend byte depending if y point is even or odd - if (compressed) { - if (y.isEven()) { - enc.unshift(0x02); - } else { - enc.unshift(0x03); - } - } else { - enc.unshift(0x04); - enc = enc.concat(ec.integerToBytes(y, len)); // uncompressed public key appends the bytes of the y point - } - return enc; - }; - - ec.PointFp.decodeFrom = function (curve, enc) { - var type = enc[0]; - var dataLen = enc.length - 1; - - // Extract x and y as byte arrays - var xBa = enc.slice(1, 1 + dataLen / 2); - var yBa = enc.slice(1 + dataLen / 2, 1 + dataLen); - - // Prepend zero byte to prevent interpretation as negative integer - xBa.unshift(0); - yBa.unshift(0); - - // Convert to BigIntegers - var x = new BigInteger(xBa); - var y = new BigInteger(yBa); - - // Return point - return new ec.PointFp(curve, curve.fromBigInteger(x), curve.fromBigInteger(y)); - }; - - ec.PointFp.prototype.add2D = function (b) { - if (this.isInfinity()) return b; - if (b.isInfinity()) return this; - - if (this.x.equals(b.x)) { - if (this.y.equals(b.y)) { - // this = b, i.e. this must be doubled - return this.twice(); - } - // this = -b, i.e. the result is the point at infinity - return this.curve.getInfinity(); - } - - var x_x = b.x.subtract(this.x); - var y_y = b.y.subtract(this.y); - var gamma = y_y.divide(x_x); - - var x3 = gamma.square().subtract(this.x).subtract(b.x); - var y3 = gamma.multiply(this.x.subtract(x3)).subtract(this.y); - - return new ec.PointFp(this.curve, x3, y3); - }; - - ec.PointFp.prototype.twice2D = function () { - if (this.isInfinity()) return this; - if (this.y.toBigInteger().signum() == 0) { - // if y1 == 0, then (x1, y1) == (x1, -y1) - // and hence this = -this and thus 2(x1, y1) == infinity - return this.curve.getInfinity(); - } - - var TWO = this.curve.fromBigInteger(BigInteger.valueOf(2)); - var THREE = this.curve.fromBigInteger(BigInteger.valueOf(3)); - var gamma = this.x.square().multiply(THREE).add(this.curve.a).divide(this.y.multiply(TWO)); - - var x3 = gamma.square().subtract(this.x.multiply(TWO)); - var y3 = gamma.multiply(this.x.subtract(x3)).subtract(this.y); - - return new ec.PointFp(this.curve, x3, y3); - }; - - ec.PointFp.prototype.multiply2D = function (k) { - if (this.isInfinity()) return this; - if (k.signum() == 0) return this.curve.getInfinity(); - - var e = k; - var h = e.multiply(new BigInteger("3")); - - var neg = this.negate(); - var R = this; - - var i; - for (i = h.bitLength() - 2; i > 0; --i) { - R = R.twice(); - - var hBit = h.testBit(i); - var eBit = e.testBit(i); - - if (hBit != eBit) { - R = R.add2D(hBit ? this : neg); - } - } - - return R; - }; - - ec.PointFp.prototype.isOnCurve = function () { - var x = this.getX().toBigInteger(); - var y = this.getY().toBigInteger(); - var a = this.curve.getA().toBigInteger(); - var b = this.curve.getB().toBigInteger(); - var n = this.curve.getQ(); - var lhs = y.multiply(y).mod(n); - var rhs = x.multiply(x).multiply(x).add(a.multiply(x)).add(b).mod(n); - return lhs.equals(rhs); - }; - - ec.PointFp.prototype.toString = function () { - return '(' + this.getX().toBigInteger().toString() + ',' + this.getY().toBigInteger().toString() + - ')'; - }; - - /** - * Validate an elliptic curve point. - * - * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive - */ - ec.PointFp.prototype.validate = function () { - var n = this.curve.getQ(); - - // Check Q != O - if (this.isInfinity()) { - throw new Error("Point is at infinity."); - } - - // Check coordinate bounds - var x = this.getX().toBigInteger(); - var y = this.getY().toBigInteger(); - if (x.compareTo(BigInteger.ONE) < 0 || x.compareTo(n.subtract(BigInteger.ONE)) > 0) { - throw new Error('x coordinate out of bounds'); - } - if (y.compareTo(BigInteger.ONE) < 0 || y.compareTo(n.subtract(BigInteger.ONE)) > 0) { - throw new Error('y coordinate out of bounds'); - } - - // Check y^2 = x^3 + ax + b (mod n) - if (!this.isOnCurve()) { - throw new Error("Point is not on the curve."); - } - - // Check nQ = 0 (Q is a scalar multiple of G) - if (this.multiply(n).isInfinity()) { - // TODO: This check doesn't work - fix. - throw new Error("Point is not a scalar multiple of G."); - } - - return true; - }; - - - - - // ---------------- - // ECCurveFp constructor - ec.CurveFp = function (q, a, b) { - this.q = q; - this.a = this.fromBigInteger(a); - this.b = this.fromBigInteger(b); - this.infinity = new ec.PointFp(this, null, null); - this.reducer = new Barrett(this.q); } - - ec.CurveFp.prototype.getQ = function () { - return this.q; - }; - - ec.CurveFp.prototype.getA = function () { - return this.a; - }; - - ec.CurveFp.prototype.getB = function () { - return this.b; - }; - - ec.CurveFp.prototype.equals = function (other) { - if (other == this) return true; - return (this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); - }; - - ec.CurveFp.prototype.getInfinity = function () { - return this.infinity; - }; - - ec.CurveFp.prototype.fromBigInteger = function (x) { - return new ec.FieldElementFp(this.q, x); - }; - - ec.CurveFp.prototype.reduce = function (x) { - this.reducer.reduce(x); - }; - - // for now, work with hex strings because they're easier in JS - // compressed support added by bitaddress.org - ec.CurveFp.prototype.decodePointHex = function (s) { - var firstByte = parseInt(s.substr(0, 2), 16); - switch (firstByte) { // first byte - case 0: - return this.infinity; - case 2: // compressed - case 3: // compressed - var yTilde = firstByte & 1; - var xHex = s.substr(2, s.length - 2); - var X1 = new BigInteger(xHex, 16); - return this.decompressPoint(yTilde, X1); - case 4: // uncompressed - case 6: // hybrid - case 7: // hybrid - var len = (s.length - 2) / 2; - var xHex = s.substr(2, len); - var yHex = s.substr(len + 2, len); - - return new ec.PointFp(this, - this.fromBigInteger(new BigInteger(xHex, 16)), - this.fromBigInteger(new BigInteger(yHex, 16))); - - default: // unsupported - return null; - } - }; - - ec.CurveFp.prototype.encodePointHex = function (p) { - if (p.isInfinity()) return "00"; - var xHex = p.getX().toBigInteger().toString(16); - var yHex = p.getY().toBigInteger().toString(16); - var oLen = this.getQ().toString(16).length; - if ((oLen % 2) != 0) oLen++; - while (xHex.length < oLen) { - xHex = "0" + xHex; - } - while (yHex.length < oLen) { - yHex = "0" + yHex; - } - return "04" + xHex + yHex; - }; - - /* - * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) - * Ported to JavaScript by bitaddress.org - * - * Number yTilde - * BigInteger X1 - */ - ec.CurveFp.prototype.decompressPoint = function (yTilde, X1) { - var x = this.fromBigInteger(X1); - var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); - var beta = alpha.sqrt(); - // if we can't find a sqrt we haven't got a point on the curve - run! - if (beta == null) throw new Error("Invalid point compression"); - var betaValue = beta.toBigInteger(); - var bit0 = betaValue.testBit(0) ? 1 : 0; - if (bit0 != yTilde) { - // Use the other root - beta = this.fromBigInteger(this.getQ().subtract(betaValue)); - } - return new ec.PointFp(this, x, beta, null, true); - }; - - - ec.fromHex = function (s) { - return new BigInteger(s, 16); - }; - - ec.integerToBytes = function (i, len) { - var bytes = i.toByteArrayUnsigned(); - if (len < bytes.length) { - bytes = bytes.slice(bytes.length - len); - } else - while (len > bytes.length) { - bytes.unshift(0); - } - return bytes; - }; - - - // Named EC curves - // ---------------- - // X9ECParameters constructor - ec.X9Parameters = function (curve, g, n, h) { - this.curve = curve; - this.g = g; - this.n = n; - this.h = h; - } - ec.X9Parameters.prototype.getCurve = function () { - return this.curve; - }; - ec.X9Parameters.prototype.getG = function () { - return this.g; - }; - ec.X9Parameters.prototype.getN = function () { - return this.n; - }; - ec.X9Parameters.prototype.getH = function () { - return this.h; - }; - - // secp256k1 is the Curve used by Bitcoin - ec.secNamedCurves = { - // used by Bitcoin - "secp256k1": function () { - // p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 - var p = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"); - var a = BigInteger.ZERO; - var b = ec.fromHex("7"); - var n = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); - var h = BigInteger.ONE; - var curve = new ec.CurveFp(p, a, b); - var G = curve.decodePointHex("04" + - "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798" + - "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8"); - return new ec.X9Parameters(curve, G, n, h); - } - }; - - // secp256k1 called by Bitcoin's ECKEY - ec.getSECCurveByName = function (name) { - if (ec.secNamedCurves[name] == undefined) return null; - return ec.secNamedCurves[name](); - } - })(); - - - //bitTrx.js - (function () { - - var bitjs = window.bitjs = function () {}; - - /* public vars */ - bitjs.pub = 0x23; // flochange - changed the prefix to FLO Mainnet PublicKey Prefix 0x23 - bitjs.priv = 0xa3; //flochange - changed the prefix to FLO Mainnet Private key prefix 0xa3 - bitjs.compressed = false; - - /* provide a privkey and return an WIF */ - bitjs.privkey2wif = function (h) { - var r = Crypto.util.hexToBytes(h); - - if (bitjs.compressed == true) { - r.push(0x01); - } - - r.unshift(bitjs.priv); - var hash = Crypto.SHA256(Crypto.SHA256(r, { - asBytes: true - }), { + }; + CTR_prototype._doDecrypt = CTR_prototype._doEncrypt; + + })(Crypto); + + /*! + * Crypto-JS v2.5.4 PBKDF2.js + * http://code.google.com/p/crypto-js/ + * Copyright (c) 2009-2013, Jeff Mott. All rights reserved. + * http://code.google.com/p/crypto-js/wiki/License + */ + (function () { + + // Shortcuts + var C = Crypto, + util = C.util, + charenc = C.charenc, + UTF8 = charenc.UTF8, + Binary = charenc.Binary; + + C.PBKDF2 = function (password, salt, keylen, options) { + + // Convert to byte arrays + if (password.constructor == String) password = UTF8.stringToBytes(password); + if (salt.constructor == String) salt = UTF8.stringToBytes(salt); + /* else, assume byte arrays already */ + + // Defaults + var hasher = options && options.hasher || C.SHA1, + iterations = options && options.iterations || 1; + + // Pseudo-random function + function PRF(password, salt) { + return C.HMAC(hasher, salt, password, { asBytes: true }); - var checksum = hash.slice(0, 4); - - return B58.encode(r.concat(checksum)); } - - /* convert a wif key back to a private key */ - bitjs.wif2privkey = function (wif) { - var compressed = false; - var decode = B58.decode(wif); - var key = decode.slice(0, decode.length - 4); - key = key.slice(1, key.length); - if (key.length >= 33 && key[key.length - 1] == 0x01) { - key = key.slice(0, key.length - 1); - compressed = true; + + // Generate key + var derivedKeyBytes = [], + blockindex = 1; + while (derivedKeyBytes.length < keylen) { + var block = PRF(password, salt.concat(util.wordsToBytes([blockindex]))); + for (var u = block, i = 1; i < iterations; i++) { + u = PRF(password, u); + for (var j = 0; j < block.length; j++) block[j] ^= u[j]; } - return { - 'privkey': Crypto.util.bytesToHex(key), - 'compressed': compressed - }; + derivedKeyBytes = derivedKeyBytes.concat(block); + blockindex++; } - - /* convert a wif to a pubkey */ - bitjs.wif2pubkey = function (wif) { - var compressed = bitjs.compressed; - var r = bitjs.wif2privkey(wif); - bitjs.compressed = r['compressed']; - var pubkey = bitjs.newPubkey(r['privkey']); - bitjs.compressed = compressed; - return { - 'pubkey': pubkey, - 'compressed': r['compressed'] - }; - } - - /* convert a wif to a address */ - bitjs.wif2address = function (wif) { - var r = bitjs.wif2pubkey(wif); - return { - 'address': bitjs.pubkey2address(r['pubkey']), - 'compressed': r['compressed'] - }; - } - - /* generate a public key from a private key */ - bitjs.newPubkey = function (hash) { - var privateKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(hash)); - var curve = EllipticCurve.getSECCurveByName("secp256k1"); - - var curvePt = curve.getG().multiply(privateKeyBigInt); - var x = curvePt.getX().toBigInteger(); - var y = curvePt.getY().toBigInteger(); - - var publicKeyBytes = EllipticCurve.integerToBytes(x, 32); - publicKeyBytes = publicKeyBytes.concat(EllipticCurve.integerToBytes(y, 32)); - publicKeyBytes.unshift(0x04); - - if (bitjs.compressed == true) { - var publicKeyBytesCompressed = EllipticCurve.integerToBytes(x, 32) - if (y.isEven()) { - publicKeyBytesCompressed.unshift(0x02) - } else { - publicKeyBytesCompressed.unshift(0x03) + + // Truncate excess bytes + derivedKeyBytes.length = keylen; + + return options && options.asBytes ? derivedKeyBytes : + options && options.asString ? Binary.bytesToString(derivedKeyBytes) : + util.bytesToHex(derivedKeyBytes); + + }; + + })(); + + /* + * Copyright (c) 2010-2011 Intalio Pte, All Rights Reserved + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + // https://github.com/cheongwy/node-scrypt-js + (function () { + + var MAX_VALUE = 2147483647; + var workerUrl = null; + + //function scrypt(byte[] passwd, byte[] salt, int N, int r, int p, int dkLen) + /* + * N = Cpu cost + * r = Memory cost + * p = parallelization cost + * + */ + window.Crypto_scrypt = function (passwd, salt, N, r, p, dkLen, callback) { + if (N == 0 || (N & (N - 1)) != 0) throw Error("N must be > 0 and a power of 2"); + + if (N > MAX_VALUE / 128 / r) throw Error("Parameter N is too large"); + if (r > MAX_VALUE / 128 / p) throw Error("Parameter r is too large"); + + var PBKDF2_opts = { + iterations: 1, + hasher: Crypto.SHA256, + asBytes: true + }; + + var B = Crypto.PBKDF2(passwd, salt, p * 128 * r, PBKDF2_opts); + + try { + var i = 0; + var worksDone = 0; + var makeWorker = function () { + if (!workerUrl) { + var code = '(' + scryptCore.toString() + ')()'; + var blob; + try { + blob = new Blob([code], { + type: "text/javascript" + }); + } catch (e) { + window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || + window.MozBlobBuilder || + window.MSBlobBuilder; + blob = new BlobBuilder(); + blob.append(code); + blob = blob.getBlob("text/javascript"); + } + workerUrl = URL.createObjectURL(blob); } - return Crypto.util.bytesToHex(publicKeyBytesCompressed); - } else { - return Crypto.util.bytesToHex(publicKeyBytes); - } - } - - /* provide a public key and return address */ - bitjs.pubkey2address = function (h, byte) { - var r = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(h), { - asBytes: true - })); - r.unshift(byte || bitjs.pub); - var hash = Crypto.SHA256(Crypto.SHA256(r, { - asBytes: true - }), { - asBytes: true - }); - var checksum = hash.slice(0, 4); - return B58.encode(r.concat(checksum)); - } - - bitjs.transaction = function () { - var btrx = {}; - btrx.version = 2; //flochange look at this version - btrx.inputs = []; - btrx.outputs = []; - btrx.locktime = 0; - btrx.floData = ""; //flochange .. look at this - - - btrx.addinput = function (txid, index, scriptPubKey, sequence) { - var o = {}; - o.outpoint = { - 'hash': txid, - 'index': index + var worker = new Worker(workerUrl); + worker.onmessage = function (event) { + var Bi = event.data[0], + Bslice = event.data[1]; + worksDone++; + + if (i < p) { + worker.postMessage([N, r, p, B, i++]); + } + + var length = Bslice.length, + destPos = Bi * 128 * r, + srcPos = 0; + while (length--) { + B[destPos++] = Bslice[srcPos++]; + } + + if (worksDone == p) { + callback(Crypto.PBKDF2(passwd, B, dkLen, PBKDF2_opts)); + } }; - //o.script = []; Signature and Public Key should be added after singning - o.script = Crypto.util.hexToBytes(scriptPubKey); //push previous output pubkey script - o.sequence = sequence || ((btrx.locktime == 0) ? 4294967295 : 0); - return this.inputs.push(o); + return worker; + }; + var workers = [makeWorker(), makeWorker()]; + workers[0].postMessage([N, r, p, B, i++]); + if (p > 1) { + workers[1].postMessage([N, r, p, B, i++]); } - - btrx.addoutput = function (address, value) { - var o = {}; - var buf = []; - var addrDecoded = btrx.addressDecode(address); - o.value = new BigInteger('' + Math.round((value * 1) * 1e8), 10); - buf.push(118); //OP_DUP - buf.push(169); //OP_HASH160 - buf.push(addrDecoded.length); - buf = buf.concat(addrDecoded); // address in bytes - buf.push(136); //OP_EQUALVERIFY - buf.push(172); // OP_CHECKSIG - o.script = buf; - return this.outputs.push(o); - } - - - btrx.addflodata = function (txcomments) { // flochange - this whole function needs to be done - this.floData = txcomments; - return this.floData; //flochange .. returning the txcomments -- check if the function return will assign - } - - - // Only standard addresses - btrx.addressDecode = function (address) { - var bytes = B58.decode(address); - var front = bytes.slice(0, bytes.length - 4); - var back = bytes.slice(bytes.length - 4); - var checksum = Crypto.SHA256(Crypto.SHA256(front, { - asBytes: true - }), { - asBytes: true - }).slice(0, 4); - if (checksum + "" == back + "") { - return front.slice(1); + } catch (e) { + window.setTimeout(function () { + scryptCore(); + callback(Crypto.PBKDF2(passwd, B, dkLen, PBKDF2_opts)); + }, 0); + } + + // using this function to enclose everything needed to create a worker (but also invokable directly for synchronous use) + function scryptCore() { + var XY = [], + V = []; + + if (typeof B === 'undefined') { + onmessage = function (event) { + var data = event.data; + var N = data[0], + r = data[1], + p = data[2], + B = data[3], + i = data[4]; + + var Bslice = []; + arraycopy32(B, i * 128 * r, Bslice, 0, 128 * r); + smix(Bslice, 0, r, N, V, XY); + + postMessage([i, Bslice]); + }; + } else { + for (var i = 0; i < p; i++) { + smix(B, i * 128 * r, r, N, V, XY); } } - - /* generate the transaction hash to sign from a transaction input */ - btrx.transactionHash = function (index, sigHashType) { - - var clone = bitjs.clone(this); - var shType = sigHashType || 1; - - /* black out all other ins, except this one */ - for (var i = 0; i < clone.inputs.length; i++) { - if (index != i) { - clone.inputs[i].script = []; - } + + function smix(B, Bi, r, N, V, XY) { + var Xi = 0; + var Yi = 128 * r; + var i; + + arraycopy32(B, Bi, XY, Xi, Yi); + + for (i = 0; i < N; i++) { + arraycopy32(XY, Xi, V, i * Yi, Yi); + blockmix_salsa8(XY, Xi, Yi, r); } + + for (i = 0; i < N; i++) { + var j = integerify(XY, Xi, r) & (N - 1); + blockxor(V, j * Yi, XY, Xi, Yi); + blockmix_salsa8(XY, Xi, Yi, r); + } + + arraycopy32(XY, Xi, B, Bi, Yi); + } + + function blockmix_salsa8(BY, Bi, Yi, r) { + var X = []; + var i; + + arraycopy32(BY, Bi + (2 * r - 1) * 64, X, 0, 64); + + for (i = 0; i < 2 * r; i++) { + blockxor(BY, i * 64, X, 0, 64); + salsa20_8(X); + arraycopy32(X, 0, BY, Yi + (i * 64), 64); + } + + for (i = 0; i < r; i++) { + arraycopy32(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64); + } + + for (i = 0; i < r; i++) { + arraycopy32(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64); + } + } + + function R(a, b) { + return (a << b) | (a >>> (32 - b)); + } + + function salsa20_8(B) { + var B32 = new Array(32); + var x = new Array(32); + var i; + + for (i = 0; i < 16; i++) { + B32[i] = (B[i * 4 + 0] & 0xff) << 0; + B32[i] |= (B[i * 4 + 1] & 0xff) << 8; + B32[i] |= (B[i * 4 + 2] & 0xff) << 16; + B32[i] |= (B[i * 4 + 3] & 0xff) << 24; + } + + arraycopy(B32, 0, x, 0, 16); + + for (i = 8; i > 0; i -= 2) { + x[4] ^= R(x[0] + x[12], 7); + x[8] ^= R(x[4] + x[0], 9); + x[12] ^= R(x[8] + x[4], 13); + x[0] ^= R(x[12] + x[8], 18); + x[9] ^= R(x[5] + x[1], 7); + x[13] ^= R(x[9] + x[5], 9); + x[1] ^= R(x[13] + x[9], 13); + x[5] ^= R(x[1] + x[13], 18); + x[14] ^= R(x[10] + x[6], 7); + x[2] ^= R(x[14] + x[10], 9); + x[6] ^= R(x[2] + x[14], 13); + x[10] ^= R(x[6] + x[2], 18); + x[3] ^= R(x[15] + x[11], 7); + x[7] ^= R(x[3] + x[15], 9); + x[11] ^= R(x[7] + x[3], 13); + x[15] ^= R(x[11] + x[7], 18); + x[1] ^= R(x[0] + x[3], 7); + x[2] ^= R(x[1] + x[0], 9); + x[3] ^= R(x[2] + x[1], 13); + x[0] ^= R(x[3] + x[2], 18); + x[6] ^= R(x[5] + x[4], 7); + x[7] ^= R(x[6] + x[5], 9); + x[4] ^= R(x[7] + x[6], 13); + x[5] ^= R(x[4] + x[7], 18); + x[11] ^= R(x[10] + x[9], 7); + x[8] ^= R(x[11] + x[10], 9); + x[9] ^= R(x[8] + x[11], 13); + x[10] ^= R(x[9] + x[8], 18); + x[12] ^= R(x[15] + x[14], 7); + x[13] ^= R(x[12] + x[15], 9); + x[14] ^= R(x[13] + x[12], 13); + x[15] ^= R(x[14] + x[13], 18); + } + + for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]; + + for (i = 0; i < 16; i++) { + var bi = i * 4; + B[bi + 0] = (B32[i] >> 0 & 0xff); + B[bi + 1] = (B32[i] >> 8 & 0xff); + B[bi + 2] = (B32[i] >> 16 & 0xff); + B[bi + 3] = (B32[i] >> 24 & 0xff); + } + } + + function blockxor(S, Si, D, Di, len) { + var i = len >> 6; + while (i--) { + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + D[Di++] ^= S[Si++]; + } + } + + function integerify(B, bi, r) { + var n; + + bi += (2 * r - 1) * 64; + + n = (B[bi + 0] & 0xff) << 0; + n |= (B[bi + 1] & 0xff) << 8; + n |= (B[bi + 2] & 0xff) << 16; + n |= (B[bi + 3] & 0xff) << 24; + + return n; + } + + function arraycopy(src, srcPos, dest, destPos, length) { + while (length--) { + dest[destPos++] = src[srcPos++]; + } + } + + function arraycopy32(src, srcPos, dest, destPos, length) { + var i = length >> 5; + while (i--) { + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + } + } + } // scryptCore + }; // window.Crypto_scrypt + })(); + + /*! + * Crypto-JS v2.5.4 AES.js + * http://code.google.com/p/crypto-js/ + * Copyright (c) 2009-2013, Jeff Mott. All rights reserved. + * http://code.google.com/p/crypto-js/wiki/License + */ + (function () { + + // Shortcuts + var C = Crypto, + util = C.util, + charenc = C.charenc, + UTF8 = charenc.UTF8; + + // Precomputed SBOX + var SBOX = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, + 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, + 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, + 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, + 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, + 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, + 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, + 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, + 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, + 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, + 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, + 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, + 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, + 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, + 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, + 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, + 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, + 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, + 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, + 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, + 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, + 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, + 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, + 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, + 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, + 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, + 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, + 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, + 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, + 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, + 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, + 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 + ]; + + // Compute inverse SBOX lookup table + for (var INVSBOX = [], i = 0; i < 256; i++) INVSBOX[SBOX[i]] = i; + + // Compute multiplication in GF(2^8) lookup tables + var MULT2 = [], + MULT3 = [], + MULT9 = [], + MULTB = [], + MULTD = [], + MULTE = []; + + function xtime(a, b) { + for (var result = 0, i = 0; i < 8; i++) { + if (b & 1) result ^= a; + var hiBitSet = a & 0x80; + a = (a << 1) & 0xFF; + if (hiBitSet) a ^= 0x1b; + b >>>= 1; + } + return result; + } + + for (var i = 0; i < 256; i++) { + MULT2[i] = xtime(i, 2); + MULT3[i] = xtime(i, 3); + MULT9[i] = xtime(i, 9); + MULTB[i] = xtime(i, 0xB); + MULTD[i] = xtime(i, 0xD); + MULTE[i] = xtime(i, 0xE); + } + + // Precomputed RCon lookup + var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; + + // Inner state + var state = [ + [], + [], + [], + [] + ], + keylength, + nrounds, + keyschedule; + + var AES = C.AES = { + + /** + * Public API + */ + + encrypt: function (message, password, options) { + + options = options || {}; + + // Determine mode + var mode = options.mode || new C.mode.OFB; + + // Allow mode to override options + if (mode.fixOptions) mode.fixOptions(options); + + var + + // Convert to bytes if message is a string + m = ( + message.constructor == String ? + UTF8.stringToBytes(message) : + message + ), + + // Generate random IV + iv = options.iv || util.randomBytes(AES._blocksize * 4), + + // Generate key + k = ( + password.constructor == String ? + // Derive key from pass-phrase + C.PBKDF2(password, iv, 32, { + asBytes: true + }) : + // else, assume byte array representing cryptographic key + password + ); + + // Encrypt + AES._init(k); + mode.encrypt(AES, m, iv); + + // Return ciphertext + m = options.iv ? m : iv.concat(m); + return (options && options.asBytes) ? m : util.bytesToBase64(m); + + }, + + decrypt: function (ciphertext, password, options) { + + options = options || {}; + + // Determine mode + var mode = options.mode || new C.mode.OFB; + + // Allow mode to override options + if (mode.fixOptions) mode.fixOptions(options); + + var + + // Convert to bytes if ciphertext is a string + c = ( + ciphertext.constructor == String ? + util.base64ToBytes(ciphertext) : + ciphertext + ), + + // Separate IV and message + iv = options.iv || c.splice(0, AES._blocksize * 4), + + // Generate key + k = ( + password.constructor == String ? + // Derive key from pass-phrase + C.PBKDF2(password, iv, 32, { + asBytes: true + }) : + // else, assume byte array representing cryptographic key + password + ); + + // Decrypt + AES._init(k); + mode.decrypt(AES, c, iv); + + // Return plaintext + return (options && options.asBytes) ? c : UTF8.bytesToString(c); + + }, + + + /** + * Package private methods and properties + */ + + _blocksize: 4, + + _encryptblock: function (m, offset) { + + // Set input + for (var row = 0; row < AES._blocksize; row++) { + for (var col = 0; col < 4; col++) + state[row][col] = m[offset + col * 4 + row]; + } + + // Add round key + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] ^= keyschedule[col][row]; + } + + for (var round = 1; round < nrounds; round++) { + + // Sub bytes + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] = SBOX[state[row][col]]; + } + + // Shift rows + state[1].push(state[1].shift()); + state[2].push(state[2].shift()); + state[2].push(state[2].shift()); + state[3].unshift(state[3].pop()); + + // Mix columns + for (var col = 0; col < 4; col++) { + + var s0 = state[0][col], + s1 = state[1][col], + s2 = state[2][col], + s3 = state[3][col]; + + state[0][col] = MULT2[s0] ^ MULT3[s1] ^ s2 ^ s3; + state[1][col] = s0 ^ MULT2[s1] ^ MULT3[s2] ^ s3; + state[2][col] = s0 ^ s1 ^ MULT2[s2] ^ MULT3[s3]; + state[3][col] = MULT3[s0] ^ s1 ^ s2 ^ MULT2[s3]; + + } + + // Add round key + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] ^= keyschedule[round * 4 + col][row]; + } + + } + + // Sub bytes + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] = SBOX[state[row][col]]; + } + + // Shift rows + state[1].push(state[1].shift()); + state[2].push(state[2].shift()); + state[2].push(state[2].shift()); + state[3].unshift(state[3].pop()); + + // Add round key + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] ^= keyschedule[nrounds * 4 + col][row]; + } + + // Set output + for (var row = 0; row < AES._blocksize; row++) { + for (var col = 0; col < 4; col++) + m[offset + col * 4 + row] = state[row][col]; + } + + }, + + _decryptblock: function (c, offset) { + + // Set input + for (var row = 0; row < AES._blocksize; row++) { + for (var col = 0; col < 4; col++) + state[row][col] = c[offset + col * 4 + row]; + } + + // Add round key + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] ^= keyschedule[nrounds * 4 + col][row]; + } + + for (var round = 1; round < nrounds; round++) { + + // Inv shift rows + state[1].unshift(state[1].pop()); + state[2].push(state[2].shift()); + state[2].push(state[2].shift()); + state[3].push(state[3].shift()); + + // Inv sub bytes + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] = INVSBOX[state[row][col]]; + } + + // Add round key + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] ^= keyschedule[(nrounds - round) * 4 + col][row]; + } + + // Inv mix columns + for (var col = 0; col < 4; col++) { + + var s0 = state[0][col], + s1 = state[1][col], + s2 = state[2][col], + s3 = state[3][col]; + + state[0][col] = MULTE[s0] ^ MULTB[s1] ^ MULTD[s2] ^ MULT9[s3]; + state[1][col] = MULT9[s0] ^ MULTE[s1] ^ MULTB[s2] ^ MULTD[s3]; + state[2][col] = MULTD[s0] ^ MULT9[s1] ^ MULTE[s2] ^ MULTB[s3]; + state[3][col] = MULTB[s0] ^ MULTD[s1] ^ MULT9[s2] ^ MULTE[s3]; + + } + + } + + // Inv shift rows + state[1].unshift(state[1].pop()); + state[2].push(state[2].shift()); + state[2].push(state[2].shift()); + state[3].push(state[3].shift()); + + // Inv sub bytes + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] = INVSBOX[state[row][col]]; + } + + // Add round key + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] ^= keyschedule[col][row]; + } + + // Set output + for (var row = 0; row < AES._blocksize; row++) { + for (var col = 0; col < 4; col++) + c[offset + col * 4 + row] = state[row][col]; + } + + }, + + + /** + * Private methods + */ + + _init: function (k) { + keylength = k.length / 4; + nrounds = keylength + 6; + AES._keyexpansion(k); + }, + + // Generate a key schedule + _keyexpansion: function (k) { + + keyschedule = []; + + for (var row = 0; row < keylength; row++) { + keyschedule[row] = [ + k[row * 4], + k[row * 4 + 1], + k[row * 4 + 2], + k[row * 4 + 3] + ]; + } + + for (var row = keylength; row < AES._blocksize * (nrounds + 1); row++) { + + var temp = [ + keyschedule[row - 1][0], + keyschedule[row - 1][1], + keyschedule[row - 1][2], + keyschedule[row - 1][3] + ]; + + if (row % keylength == 0) { + + // Rot word + temp.push(temp.shift()); + + // Sub word + temp[0] = SBOX[temp[0]]; + temp[1] = SBOX[temp[1]]; + temp[2] = SBOX[temp[2]]; + temp[3] = SBOX[temp[3]]; + + temp[0] ^= RCON[row / keylength]; + + } else if (keylength > 6 && row % keylength == 4) { + + // Sub word + temp[0] = SBOX[temp[0]]; + temp[1] = SBOX[temp[1]]; + temp[2] = SBOX[temp[2]]; + temp[3] = SBOX[temp[3]]; + + } + + keyschedule[row] = [ + keyschedule[row - keylength][0] ^ temp[0], + keyschedule[row - keylength][1] ^ temp[1], + keyschedule[row - keylength][2] ^ temp[2], + keyschedule[row - keylength][3] ^ temp[3] + ]; + + } + + } + + }; + + })(); - - if ((clone.inputs) && clone.inputs[index]) { - - /* SIGHASH : For more info on sig hashs see https://en.bitcoin.it/wiki/OP_CHECKSIG - and https://bitcoin.org/en/developer-guide#signature-hash-type */ - - if (shType == 1) { - //SIGHASH_ALL 0x01 - - } else if (shType == 2) { - //SIGHASH_NONE 0x02 - clone.outputs = []; - for (var i = 0; i < clone.inputs.length; i++) { - if (index != i) { - clone.inputs[i].sequence = 0; - } + /* + * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) + * Ported to JavaScript by bitaddress.org + */ + ec.FieldElementFp.fastLucasSequence = function (p, P, Q, k) { + // TODO Research and apply "common-multiplicand multiplication here" + + var n = k.bitLength(); + var s = k.getLowestSetBit(); + var Uh = BigInteger.ONE; + var Vl = BigInteger.TWO; + var Vh = P; + var Ql = BigInteger.ONE; + var Qh = BigInteger.ONE; + + for (var j = n - 1; j >= s + 1; --j) { + Ql = Ql.multiply(Qh).mod(p); + if (k.testBit(j)) { + Qh = Ql.multiply(Q).mod(p); + Uh = Uh.multiply(Vh).mod(p); + Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); + Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p); + } else { + Qh = Ql; + Uh = Uh.multiply(Vl).subtract(Ql).mod(p); + Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); + Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); + } + } + + Ql = Ql.multiply(Qh).mod(p); + Qh = Ql.multiply(Q).mod(p); + Uh = Uh.multiply(Vl).subtract(Ql).mod(p); + Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); + Ql = Ql.multiply(Qh).mod(p); + + for (var j = 1; j <= s; ++j) { + Uh = Uh.multiply(Vl).mod(p); + Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); + Ql = Ql.multiply(Ql).mod(p); + } + + return [Uh, Vl]; + }; + + // ---------------- + // ECPointFp constructor + ec.PointFp = function (curve, x, y, z, compressed) { + this.curve = curve; + this.x = x; + this.y = y; + // Projective coordinates: either zinv == null or z * zinv == 1 + // z and zinv are just BigIntegers, not fieldElements + if (z == null) { + this.z = BigInteger.ONE; + } else { + this.z = z; + } + this.zinv = null; + // compression flag + this.compressed = !!compressed; + }; + + ec.PointFp.prototype.getX = function () { + if (this.zinv == null) { + this.zinv = this.z.modInverse(this.curve.q); + } + var r = this.x.toBigInteger().multiply(this.zinv); + this.curve.reduce(r); + return this.curve.fromBigInteger(r); + }; + + ec.PointFp.prototype.getY = function () { + if (this.zinv == null) { + this.zinv = this.z.modInverse(this.curve.q); + } + var r = this.y.toBigInteger().multiply(this.zinv); + this.curve.reduce(r); + return this.curve.fromBigInteger(r); + }; + + ec.PointFp.prototype.equals = function (other) { + if (other == this) return true; + if (this.isInfinity()) return other.isInfinity(); + if (other.isInfinity()) return this.isInfinity(); + var u, v; + // u = Y2 * Z1 - Y1 * Z2 + u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod( + this.curve.q); + if (!u.equals(BigInteger.ZERO)) return false; + // v = X2 * Z1 - X1 * Z2 + v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod( + this.curve.q); + return v.equals(BigInteger.ZERO); + }; + + ec.PointFp.prototype.isInfinity = function () { + if ((this.x == null) && (this.y == null)) return true; + return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); + }; + + ec.PointFp.prototype.negate = function () { + return new ec.PointFp(this.curve, this.x, this.y.negate(), this.z); + }; + + ec.PointFp.prototype.add = function (b) { + if (this.isInfinity()) return b; + if (b.isInfinity()) return this; + + // u = Y2 * Z1 - Y1 * Z2 + var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod( + this.curve.q); + // v = X2 * Z1 - X1 * Z2 + var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod( + this.curve.q); + + + if (BigInteger.ZERO.equals(v)) { + if (BigInteger.ZERO.equals(u)) { + return this.twice(); // this == b, so double + } + return this.curve.getInfinity(); // this = -b, so infinity + } + + var THREE = new BigInteger("3"); + var x1 = this.x.toBigInteger(); + var y1 = this.y.toBigInteger(); + var x2 = b.x.toBigInteger(); + var y2 = b.y.toBigInteger(); + + var v2 = v.square(); + var v3 = v2.multiply(v); + var x1v2 = x1.multiply(v2); + var zu2 = u.square().multiply(this.z); + + // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) + var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); + // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 + var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply( + b.z).add(u.multiply(v3)).mod(this.curve.q); + // z3 = v^3 * z1 * z2 + var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); + + return new ec.PointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), + z3); + }; + + ec.PointFp.prototype.twice = function () { + if (this.isInfinity()) return this; + if (this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); + + // TODO: optimized handling of constants + var THREE = new BigInteger("3"); + var x1 = this.x.toBigInteger(); + var y1 = this.y.toBigInteger(); + + var y1z1 = y1.multiply(this.z); + var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); + var a = this.curve.a.toBigInteger(); + + // w = 3 * x1^2 + a * z1^2 + var w = x1.square().multiply(THREE); + if (!BigInteger.ZERO.equals(a)) { + w = w.add(this.z.square().multiply(a)); + } + w = w.mod(this.curve.q); + //this.curve.reduce(w); + // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) + var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod( + this.curve.q); + // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 + var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply( + y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); + // z3 = 8 * (y1 * z1)^3 + var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); + + return new ec.PointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), + z3); + }; + + // Simple NAF (Non-Adjacent Form) multiplication algorithm + // TODO: modularize the multiplication algorithm + ec.PointFp.prototype.multiply = function (k) { + if (this.isInfinity()) return this; + if (k.signum() == 0) return this.curve.getInfinity(); + + var e = k; + var h = e.multiply(new BigInteger("3")); + + var neg = this.negate(); + var R = this; + + var i; + for (i = h.bitLength() - 2; i > 0; --i) { + R = R.twice(); + + var hBit = h.testBit(i); + var eBit = e.testBit(i); + + if (hBit != eBit) { + R = R.add(hBit ? this : neg); + } + } + + return R; + }; + + // Compute this*j + x*k (simultaneous multiplication) + ec.PointFp.prototype.multiplyTwo = function (j, x, k) { + var i; + if (j.bitLength() > k.bitLength()) + i = j.bitLength() - 1; + else + i = k.bitLength() - 1; + + var R = this.curve.getInfinity(); + var both = this.add(x); + while (i >= 0) { + R = R.twice(); + if (j.testBit(i)) { + if (k.testBit(i)) { + R = R.add(both); + } else { + R = R.add(this); + } + } else { + if (k.testBit(i)) { + R = R.add(x); + } + } + --i; + } + + return R; + }; + + // patched by bitaddress.org and Casascius for use with Bitcoin.ECKey + // patched by coretechs to support compressed public keys + ec.PointFp.prototype.getEncoded = function (compressed) { + var x = this.getX().toBigInteger(); + var y = this.getY().toBigInteger(); + var len = 32; // integerToBytes will zero pad if integer is less than 32 bytes. 32 bytes length is required by the Bitcoin protocol. + var enc = ec.integerToBytes(x, len); + + // when compressed prepend byte depending if y point is even or odd + if (compressed) { + if (y.isEven()) { + enc.unshift(0x02); + } else { + enc.unshift(0x03); + } + } else { + enc.unshift(0x04); + enc = enc.concat(ec.integerToBytes(y, len)); // uncompressed public key appends the bytes of the y point + } + return enc; + }; + + ec.PointFp.decodeFrom = function (curve, enc) { + var type = enc[0]; + var dataLen = enc.length - 1; + + // Extract x and y as byte arrays + var xBa = enc.slice(1, 1 + dataLen / 2); + var yBa = enc.slice(1 + dataLen / 2, 1 + dataLen); + + // Prepend zero byte to prevent interpretation as negative integer + xBa.unshift(0); + yBa.unshift(0); + + // Convert to BigIntegers + var x = new BigInteger(xBa); + var y = new BigInteger(yBa); + + // Return point + return new ec.PointFp(curve, curve.fromBigInteger(x), curve.fromBigInteger(y)); + }; + + ec.PointFp.prototype.add2D = function (b) { + if (this.isInfinity()) return b; + if (b.isInfinity()) return this; + + if (this.x.equals(b.x)) { + if (this.y.equals(b.y)) { + // this = b, i.e. this must be doubled + return this.twice(); + } + // this = -b, i.e. the result is the point at infinity + return this.curve.getInfinity(); + } + + var x_x = b.x.subtract(this.x); + var y_y = b.y.subtract(this.y); + var gamma = y_y.divide(x_x); + + var x3 = gamma.square().subtract(this.x).subtract(b.x); + var y3 = gamma.multiply(this.x.subtract(x3)).subtract(this.y); + + return new ec.PointFp(this.curve, x3, y3); + }; + + ec.PointFp.prototype.twice2D = function () { + if (this.isInfinity()) return this; + if (this.y.toBigInteger().signum() == 0) { + // if y1 == 0, then (x1, y1) == (x1, -y1) + // and hence this = -this and thus 2(x1, y1) == infinity + return this.curve.getInfinity(); + } + + var TWO = this.curve.fromBigInteger(BigInteger.valueOf(2)); + var THREE = this.curve.fromBigInteger(BigInteger.valueOf(3)); + var gamma = this.x.square().multiply(THREE).add(this.curve.a).divide(this.y.multiply(TWO)); + + var x3 = gamma.square().subtract(this.x.multiply(TWO)); + var y3 = gamma.multiply(this.x.subtract(x3)).subtract(this.y); + + return new ec.PointFp(this.curve, x3, y3); + }; + + ec.PointFp.prototype.multiply2D = function (k) { + if (this.isInfinity()) return this; + if (k.signum() == 0) return this.curve.getInfinity(); + + var e = k; + var h = e.multiply(new BigInteger("3")); + + var neg = this.negate(); + var R = this; + + var i; + for (i = h.bitLength() - 2; i > 0; --i) { + R = R.twice(); + + var hBit = h.testBit(i); + var eBit = e.testBit(i); + + if (hBit != eBit) { + R = R.add2D(hBit ? this : neg); + } + } + + return R; + }; + + ec.PointFp.prototype.isOnCurve = function () { + var x = this.getX().toBigInteger(); + var y = this.getY().toBigInteger(); + var a = this.curve.getA().toBigInteger(); + var b = this.curve.getB().toBigInteger(); + var n = this.curve.getQ(); + var lhs = y.multiply(y).mod(n); + var rhs = x.multiply(x).multiply(x).add(a.multiply(x)).add(b).mod(n); + return lhs.equals(rhs); + }; + + ec.PointFp.prototype.toString = function () { + return '(' + this.getX().toBigInteger().toString() + ',' + this.getY().toBigInteger().toString() + + ')'; + }; + + /** + * Validate an elliptic curve point. + * + * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive + */ + ec.PointFp.prototype.validate = function () { + var n = this.curve.getQ(); + + // Check Q != O + if (this.isInfinity()) { + throw new Error("Point is at infinity."); + } + + // Check coordinate bounds + var x = this.getX().toBigInteger(); + var y = this.getY().toBigInteger(); + if (x.compareTo(BigInteger.ONE) < 0 || x.compareTo(n.subtract(BigInteger.ONE)) > 0) { + throw new Error('x coordinate out of bounds'); + } + if (y.compareTo(BigInteger.ONE) < 0 || y.compareTo(n.subtract(BigInteger.ONE)) > 0) { + throw new Error('y coordinate out of bounds'); + } + + // Check y^2 = x^3 + ax + b (mod n) + if (!this.isOnCurve()) { + throw new Error("Point is not on the curve."); + } + + // Check nQ = 0 (Q is a scalar multiple of G) + if (this.multiply(n).isInfinity()) { + // TODO: This check doesn't work - fix. + throw new Error("Point is not a scalar multiple of G."); + } + + return true; + }; + + + + + // ---------------- + // ECCurveFp constructor + ec.CurveFp = function (q, a, b) { + this.q = q; + this.a = this.fromBigInteger(a); + this.b = this.fromBigInteger(b); + this.infinity = new ec.PointFp(this, null, null); + this.reducer = new Barrett(this.q); + } + + ec.CurveFp.prototype.getQ = function () { + return this.q; + }; + + ec.CurveFp.prototype.getA = function () { + return this.a; + }; + + ec.CurveFp.prototype.getB = function () { + return this.b; + }; + + ec.CurveFp.prototype.equals = function (other) { + if (other == this) return true; + return (this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); + }; + + ec.CurveFp.prototype.getInfinity = function () { + return this.infinity; + }; + + ec.CurveFp.prototype.fromBigInteger = function (x) { + return new ec.FieldElementFp(this.q, x); + }; + + ec.CurveFp.prototype.reduce = function (x) { + this.reducer.reduce(x); + }; + + // for now, work with hex strings because they're easier in JS + // compressed support added by bitaddress.org + ec.CurveFp.prototype.decodePointHex = function (s) { + var firstByte = parseInt(s.substr(0, 2), 16); + switch (firstByte) { // first byte + case 0: + return this.infinity; + case 2: // compressed + case 3: // compressed + var yTilde = firstByte & 1; + var xHex = s.substr(2, s.length - 2); + var X1 = new BigInteger(xHex, 16); + return this.decompressPoint(yTilde, X1); + case 4: // uncompressed + case 6: // hybrid + case 7: // hybrid + var len = (s.length - 2) / 2; + var xHex = s.substr(2, len); + var yHex = s.substr(len + 2, len); + + return new ec.PointFp(this, + this.fromBigInteger(new BigInteger(xHex, 16)), + this.fromBigInteger(new BigInteger(yHex, 16))); + + default: // unsupported + return null; + } + }; + + ec.CurveFp.prototype.encodePointHex = function (p) { + if (p.isInfinity()) return "00"; + var xHex = p.getX().toBigInteger().toString(16); + var yHex = p.getY().toBigInteger().toString(16); + var oLen = this.getQ().toString(16).length; + if ((oLen % 2) != 0) oLen++; + while (xHex.length < oLen) { + xHex = "0" + xHex; + } + while (yHex.length < oLen) { + yHex = "0" + yHex; + } + return "04" + xHex + yHex; + }; + + /* + * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) + * Ported to JavaScript by bitaddress.org + * + * Number yTilde + * BigInteger X1 + */ + ec.CurveFp.prototype.decompressPoint = function (yTilde, X1) { + var x = this.fromBigInteger(X1); + var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); + var beta = alpha.sqrt(); + // if we can't find a sqrt we haven't got a point on the curve - run! + if (beta == null) throw new Error("Invalid point compression"); + var betaValue = beta.toBigInteger(); + var bit0 = betaValue.testBit(0) ? 1 : 0; + if (bit0 != yTilde) { + // Use the other root + beta = this.fromBigInteger(this.getQ().subtract(betaValue)); + } + return new ec.PointFp(this, x, beta, null, true); + }; + + + ec.fromHex = function (s) { + return new BigInteger(s, 16); + }; + + ec.integerToBytes = function (i, len) { + var bytes = i.toByteArrayUnsigned(); + if (len < bytes.length) { + bytes = bytes.slice(bytes.length - len); + } else + while (len > bytes.length) { + bytes.unshift(0); + } + return bytes; + }; + + + // Named EC curves + // ---------------- + // X9ECParameters constructor + ec.X9Parameters = function (curve, g, n, h) { + this.curve = curve; + this.g = g; + this.n = n; + this.h = h; + } + ec.X9Parameters.prototype.getCurve = function () { + return this.curve; + }; + ec.X9Parameters.prototype.getG = function () { + return this.g; + }; + ec.X9Parameters.prototype.getN = function () { + return this.n; + }; + ec.X9Parameters.prototype.getH = function () { + return this.h; + }; + + // secp256k1 is the Curve used by Bitcoin + ec.secNamedCurves = { + // used by Bitcoin + "secp256k1": function () { + // p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 + var p = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"); + var a = BigInteger.ZERO; + var b = ec.fromHex("7"); + var n = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); + var h = BigInteger.ONE; + var curve = new ec.CurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798" + + "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8"); + return new ec.X9Parameters(curve, G, n, h); + } + }; + + // secp256k1 called by Bitcoin's ECKEY + ec.getSECCurveByName = function (name) { + if (ec.secNamedCurves[name] == undefined) return null; + return ec.secNamedCurves[name](); + } + })(); + + + //bitTrx.js + (function () { + + var bitjs = window.bitjs = function () {}; + + /* public vars */ + bitjs.pub = 0x23; // flochange - changed the prefix to FLO Mainnet PublicKey Prefix 0x23 + bitjs.priv = 0xa3; //flochange - changed the prefix to FLO Mainnet Private key prefix 0xa3 + bitjs.compressed = false; + + /* provide a privkey and return an WIF */ + bitjs.privkey2wif = function (h) { + var r = Crypto.util.hexToBytes(h); + + if (bitjs.compressed == true) { + r.push(0x01); + } + + r.unshift(bitjs.priv); + var hash = Crypto.SHA256(Crypto.SHA256(r, { + asBytes: true + }), { + asBytes: true + }); + var checksum = hash.slice(0, 4); + + return B58.encode(r.concat(checksum)); + } + + /* convert a wif key back to a private key */ + bitjs.wif2privkey = function (wif) { + var compressed = false; + var decode = B58.decode(wif); + var key = decode.slice(0, decode.length - 4); + key = key.slice(1, key.length); + if (key.length >= 33 && key[key.length - 1] == 0x01) { + key = key.slice(0, key.length - 1); + compressed = true; + } + return { + 'privkey': Crypto.util.bytesToHex(key), + 'compressed': compressed + }; + } + + /* convert a wif to a pubkey */ + bitjs.wif2pubkey = function (wif) { + var compressed = bitjs.compressed; + var r = bitjs.wif2privkey(wif); + bitjs.compressed = r['compressed']; + var pubkey = bitjs.newPubkey(r['privkey']); + bitjs.compressed = compressed; + return { + 'pubkey': pubkey, + 'compressed': r['compressed'] + }; + } + + /* convert a wif to a address */ + bitjs.wif2address = function (wif) { + var r = bitjs.wif2pubkey(wif); + return { + 'address': bitjs.pubkey2address(r['pubkey']), + 'compressed': r['compressed'] + }; + } + + /* generate a public key from a private key */ + bitjs.newPubkey = function (hash) { + var privateKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(hash)); + var curve = EllipticCurve.getSECCurveByName("secp256k1"); + + var curvePt = curve.getG().multiply(privateKeyBigInt); + var x = curvePt.getX().toBigInteger(); + var y = curvePt.getY().toBigInteger(); + + var publicKeyBytes = EllipticCurve.integerToBytes(x, 32); + publicKeyBytes = publicKeyBytes.concat(EllipticCurve.integerToBytes(y, 32)); + publicKeyBytes.unshift(0x04); + + if (bitjs.compressed == true) { + var publicKeyBytesCompressed = EllipticCurve.integerToBytes(x, 32) + if (y.isEven()) { + publicKeyBytesCompressed.unshift(0x02) + } else { + publicKeyBytesCompressed.unshift(0x03) + } + return Crypto.util.bytesToHex(publicKeyBytesCompressed); + } else { + return Crypto.util.bytesToHex(publicKeyBytes); + } + } + + /* provide a public key and return address */ + bitjs.pubkey2address = function (h, byte) { + var r = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(h), { + asBytes: true + })); + r.unshift(byte || bitjs.pub); + var hash = Crypto.SHA256(Crypto.SHA256(r, { + asBytes: true + }), { + asBytes: true + }); + var checksum = hash.slice(0, 4); + return B58.encode(r.concat(checksum)); + } + + bitjs.transaction = function () { + var btrx = {}; + btrx.version = 2; //flochange look at this version + btrx.inputs = []; + btrx.outputs = []; + btrx.locktime = 0; + btrx.floData = ""; //flochange .. look at this + + + btrx.addinput = function (txid, index, scriptPubKey, sequence) { + var o = {}; + o.outpoint = { + 'hash': txid, + 'index': index + }; + //o.script = []; Signature and Public Key should be added after singning + o.script = Crypto.util.hexToBytes(scriptPubKey); //push previous output pubkey script + o.sequence = sequence || ((btrx.locktime == 0) ? 4294967295 : 0); + return this.inputs.push(o); + } + + btrx.addoutput = function (address, value) { + var o = {}; + var buf = []; + var addrDecoded = btrx.addressDecode(address); + o.value = new BigInteger('' + Math.round((value * 1) * 1e8), 10); + buf.push(118); //OP_DUP + buf.push(169); //OP_HASH160 + buf.push(addrDecoded.length); + buf = buf.concat(addrDecoded); // address in bytes + buf.push(136); //OP_EQUALVERIFY + buf.push(172); // OP_CHECKSIG + o.script = buf; + return this.outputs.push(o); + } + + + btrx.addflodata = function (txcomments) { // flochange - this whole function needs to be done + this.floData = txcomments; + return this.floData; //flochange .. returning the txcomments -- check if the function return will assign + } + + + // Only standard addresses + btrx.addressDecode = function (address) { + var bytes = B58.decode(address); + var front = bytes.slice(0, bytes.length - 4); + var back = bytes.slice(bytes.length - 4); + var checksum = Crypto.SHA256(Crypto.SHA256(front, { + asBytes: true + }), { + asBytes: true + }).slice(0, 4); + if (checksum + "" == back + "") { + return front.slice(1); + } + } + + /* generate the transaction hash to sign from a transaction input */ + btrx.transactionHash = function (index, sigHashType) { + + var clone = bitjs.clone(this); + var shType = sigHashType || 1; + + /* black out all other ins, except this one */ + for (var i = 0; i < clone.inputs.length; i++) { + if (index != i) { + clone.inputs[i].script = []; + } + } + + + if ((clone.inputs) && clone.inputs[index]) { + + /* SIGHASH : For more info on sig hashs see https://en.bitcoin.it/wiki/OP_CHECKSIG + and https://bitcoin.org/en/developer-guide#signature-hash-type */ + + if (shType == 1) { + //SIGHASH_ALL 0x01 + + } else if (shType == 2) { + //SIGHASH_NONE 0x02 + clone.outputs = []; + for (var i = 0; i < clone.inputs.length; i++) { + if (index != i) { + clone.inputs[i].sequence = 0; } - - } else if (shType == 3) { - - //SIGHASH_SINGLE 0x03 + } + + } else if (shType == 3) { + + //SIGHASH_SINGLE 0x03 + clone.outputs.length = index + 1; + + for (var i = 0; i < index; i++) { + clone.outputs[i].value = -1; + clone.outputs[i].script = []; + } + + for (var i = 0; i < clone.inputs.length; i++) { + if (index != i) { + clone.inputs[i].sequence = 0; + } + } + + } else if (shType >= 128) { + //SIGHASH_ANYONECANPAY 0x80 + clone.inputs = [clone.inputs[index]]; + + if (shType == 129) { + // SIGHASH_ALL + SIGHASH_ANYONECANPAY + + } else if (shType == 130) { + // SIGHASH_NONE + SIGHASH_ANYONECANPAY + clone.outputs = []; + + } else if (shType == 131) { + // SIGHASH_SINGLE + SIGHASH_ANYONECANPAY clone.outputs.length = index + 1; - for (var i = 0; i < index; i++) { clone.outputs[i].value = -1; clone.outputs[i].script = []; } - - for (var i = 0; i < clone.inputs.length; i++) { - if (index != i) { - clone.inputs[i].sequence = 0; - } - } - - } else if (shType >= 128) { - //SIGHASH_ANYONECANPAY 0x80 - clone.inputs = [clone.inputs[index]]; - - if (shType == 129) { - // SIGHASH_ALL + SIGHASH_ANYONECANPAY - - } else if (shType == 130) { - // SIGHASH_NONE + SIGHASH_ANYONECANPAY - clone.outputs = []; - - } else if (shType == 131) { - // SIGHASH_SINGLE + SIGHASH_ANYONECANPAY - clone.outputs.length = index + 1; - for (var i = 0; i < index; i++) { - clone.outputs[i].value = -1; - clone.outputs[i].script = []; - } - } } - - var buffer = Crypto.util.hexToBytes(clone.serialize()); - buffer = buffer.concat(bitjs.numToBytes(parseInt(shType), 4)); - var hash = Crypto.SHA256(buffer, { - asBytes: true - }); - var r = Crypto.util.bytesToHex(Crypto.SHA256(hash, { - asBytes: true - })); - return r; - } else { - return false; } + + var buffer = Crypto.util.hexToBytes(clone.serialize()); + buffer = buffer.concat(bitjs.numToBytes(parseInt(shType), 4)); + var hash = Crypto.SHA256(buffer, { + asBytes: true + }); + var r = Crypto.util.bytesToHex(Crypto.SHA256(hash, { + asBytes: true + })); + return r; + } else { + return false; } - - /* generate a signature from a transaction hash */ - btrx.transactionSig = function (index, wif, sigHashType, txhash) { - - function serializeSig(r, s) { - var rBa = r.toByteArraySigned(); - var sBa = s.toByteArraySigned(); - - var sequence = []; - sequence.push(0x02); // INTEGER - sequence.push(rBa.length); - sequence = sequence.concat(rBa); - - sequence.push(0x02); // INTEGER - sequence.push(sBa.length); - sequence = sequence.concat(sBa); - - sequence.unshift(sequence.length); - sequence.unshift(0x30); // SEQUENCE - - return sequence; - } - - var shType = sigHashType || 1; - var hash = txhash || Crypto.util.hexToBytes(this.transactionHash(index, shType)); - - if (hash) { - var curve = EllipticCurve.getSECCurveByName("secp256k1"); - var key = bitjs.wif2privkey(wif); - var priv = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(key['privkey'])); - var n = curve.getN(); - var e = BigInteger.fromByteArrayUnsigned(hash); - var badrs = 0 - do { - var k = this.deterministicK(wif, hash, badrs); - var G = curve.getG(); - var Q = G.multiply(k); - var r = Q.getX().toBigInteger().mod(n); - var s = k.modInverse(n).multiply(e.add(priv.multiply(r))).mod(n); - badrs++ - } while (r.compareTo(BigInteger.ZERO) <= 0 || s.compareTo(BigInteger.ZERO) <= 0); - - // Force lower s values per BIP62 - var halfn = n.shiftRight(1); - if (s.compareTo(halfn) > 0) { - s = n.subtract(s); - }; - - var sig = serializeSig(r, s); - sig.push(parseInt(shType, 10)); - - return Crypto.util.bytesToHex(sig); - } else { - return false; - } + } + + /* generate a signature from a transaction hash */ + btrx.transactionSig = function (index, wif, sigHashType, txhash) { + + function serializeSig(r, s) { + var rBa = r.toByteArraySigned(); + var sBa = s.toByteArraySigned(); + + var sequence = []; + sequence.push(0x02); // INTEGER + sequence.push(rBa.length); + sequence = sequence.concat(rBa); + + sequence.push(0x02); // INTEGER + sequence.push(sBa.length); + sequence = sequence.concat(sBa); + + sequence.unshift(sequence.length); + sequence.unshift(0x30); // SEQUENCE + + return sequence; } - - // https://tools.ietf.org/html/rfc6979#section-3.2 - btrx.deterministicK = function (wif, hash, badrs) { - // if r or s were invalid when this function was used in signing, - // we do not want to actually compute r, s here for efficiency, so, - // we can increment badrs. explained at end of RFC 6979 section 3.2 - - // wif is b58check encoded wif privkey. - // hash is byte array of transaction digest. - // badrs is used only if the k resulted in bad r or s. - - // some necessary things out of the way for clarity. - badrs = badrs || 0; - var key = bitjs.wif2privkey(wif); - var x = Crypto.util.hexToBytes(key['privkey']) + + var shType = sigHashType || 1; + var hash = txhash || Crypto.util.hexToBytes(this.transactionHash(index, shType)); + + if (hash) { var curve = EllipticCurve.getSECCurveByName("secp256k1"); - var N = curve.getN(); - - // Step: a - // hash is a byteArray of the message digest. so h1 == hash in our case - - // Step: b - var v = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1 - ]; - - // Step: c - var k = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0 - ]; - - // Step: d - k = Crypto.HMAC(Crypto.SHA256, v.concat([0]).concat(x).concat(hash), k, { + var key = bitjs.wif2privkey(wif); + var priv = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(key['privkey'])); + var n = curve.getN(); + var e = BigInteger.fromByteArrayUnsigned(hash); + var badrs = 0 + do { + var k = this.deterministicK(wif, hash, badrs); + var G = curve.getG(); + var Q = G.multiply(k); + var r = Q.getX().toBigInteger().mod(n); + var s = k.modInverse(n).multiply(e.add(priv.multiply(r))).mod(n); + badrs++ + } while (r.compareTo(BigInteger.ZERO) <= 0 || s.compareTo(BigInteger.ZERO) <= 0); + + // Force lower s values per BIP62 + var halfn = n.shiftRight(1); + if (s.compareTo(halfn) > 0) { + s = n.subtract(s); + }; + + var sig = serializeSig(r, s); + sig.push(parseInt(shType, 10)); + + return Crypto.util.bytesToHex(sig); + } else { + return false; + } + } + + // https://tools.ietf.org/html/rfc6979#section-3.2 + btrx.deterministicK = function (wif, hash, badrs) { + // if r or s were invalid when this function was used in signing, + // we do not want to actually compute r, s here for efficiency, so, + // we can increment badrs. explained at end of RFC 6979 section 3.2 + + // wif is b58check encoded wif privkey. + // hash is byte array of transaction digest. + // badrs is used only if the k resulted in bad r or s. + + // some necessary things out of the way for clarity. + badrs = badrs || 0; + var key = bitjs.wif2privkey(wif); + var x = Crypto.util.hexToBytes(key['privkey']) + var curve = EllipticCurve.getSECCurveByName("secp256k1"); + var N = curve.getN(); + + // Step: a + // hash is a byteArray of the message digest. so h1 == hash in our case + + // Step: b + var v = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1 + ]; + + // Step: c + var k = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0 + ]; + + // Step: d + k = Crypto.HMAC(Crypto.SHA256, v.concat([0]).concat(x).concat(hash), k, { + asBytes: true + }); + + // Step: e + v = Crypto.HMAC(Crypto.SHA256, v, k, { + asBytes: true + }); + + // Step: f + k = Crypto.HMAC(Crypto.SHA256, v.concat([1]).concat(x).concat(hash), k, { + asBytes: true + }); + + // Step: g + v = Crypto.HMAC(Crypto.SHA256, v, k, { + asBytes: true + }); + + // Step: h1 + var T = []; + + // Step: h2 (since we know tlen = qlen, just copy v to T.) + v = Crypto.HMAC(Crypto.SHA256, v, k, { + asBytes: true + }); + T = v; + + // Step: h3 + var KBigInt = BigInteger.fromByteArrayUnsigned(T); + + // loop if KBigInt is not in the range of [1, N-1] or if badrs needs incrementing. + var i = 0 + while (KBigInt.compareTo(N) >= 0 || KBigInt.compareTo(BigInteger.ZERO) <= 0 || i < + badrs) { + k = Crypto.HMAC(Crypto.SHA256, v.concat([0]), k, { asBytes: true }); - - // Step: e v = Crypto.HMAC(Crypto.SHA256, v, k, { asBytes: true }); - - // Step: f - k = Crypto.HMAC(Crypto.SHA256, v.concat([1]).concat(x).concat(hash), k, { - asBytes: true - }); - - // Step: g - v = Crypto.HMAC(Crypto.SHA256, v, k, { - asBytes: true - }); - - // Step: h1 - var T = []; - - // Step: h2 (since we know tlen = qlen, just copy v to T.) v = Crypto.HMAC(Crypto.SHA256, v, k, { asBytes: true }); T = v; - - // Step: h3 - var KBigInt = BigInteger.fromByteArrayUnsigned(T); - - // loop if KBigInt is not in the range of [1, N-1] or if badrs needs incrementing. - var i = 0 - while (KBigInt.compareTo(N) >= 0 || KBigInt.compareTo(BigInteger.ZERO) <= 0 || i < - badrs) { - k = Crypto.HMAC(Crypto.SHA256, v.concat([0]), k, { - asBytes: true - }); - v = Crypto.HMAC(Crypto.SHA256, v, k, { - asBytes: true - }); - v = Crypto.HMAC(Crypto.SHA256, v, k, { - asBytes: true - }); - T = v; - KBigInt = BigInteger.fromByteArrayUnsigned(T); - i++ - }; - - return KBigInt; + KBigInt = BigInteger.fromByteArrayUnsigned(T); + i++ }; - - /* sign a "standard" input */ - btrx.signinput = function (index, wif, sigHashType) { - var key = bitjs.wif2pubkey(wif); - var shType = sigHashType || 1; - var signature = this.transactionSig(index, wif, shType); - var buf = []; - var sigBytes = Crypto.util.hexToBytes(signature); - buf.push(sigBytes.length); - buf = buf.concat(sigBytes); - var pubKeyBytes = Crypto.util.hexToBytes(key['pubkey']); - buf.push(pubKeyBytes.length); - buf = buf.concat(pubKeyBytes); - this.inputs[index].script = buf; - return true; - } - - /* sign inputs */ - btrx.sign = function (wif, sigHashType) { - var shType = sigHashType || 1; - for (var i = 0; i < this.inputs.length; i++) { - this.signinput(i, wif, shType); - } - return this.serialize(); - } - - - /* serialize a transaction */ - btrx.serialize = function () { - var buffer = []; - buffer = buffer.concat(bitjs.numToBytes(parseInt(this.version), 4)); - - buffer = buffer.concat(bitjs.numToVarInt(this.inputs.length)); - for (var i = 0; i < this.inputs.length; i++) { - var txin = this.inputs[i]; - buffer = buffer.concat(Crypto.util.hexToBytes(txin.outpoint.hash).reverse()); - buffer = buffer.concat(bitjs.numToBytes(parseInt(txin.outpoint.index), 4)); - var scriptBytes = txin.script; - buffer = buffer.concat(bitjs.numToVarInt(scriptBytes.length)); - buffer = buffer.concat(scriptBytes); - buffer = buffer.concat(bitjs.numToBytes(parseInt(txin.sequence), 4)); - - } - buffer = buffer.concat(bitjs.numToVarInt(this.outputs.length)); - - for (var i = 0; i < this.outputs.length; i++) { - var txout = this.outputs[i]; - buffer = buffer.concat(bitjs.numToBytes(txout.value, 8)); - var scriptBytes = txout.script; - buffer = buffer.concat(bitjs.numToVarInt(scriptBytes.length)); - buffer = buffer.concat(scriptBytes); - } - - buffer = buffer.concat(bitjs.numToBytes(parseInt(this.locktime),4)); - flohex = ascii_to_hexa(this.floData); - floDataCount = this.floData.length; - - //flochange -- creating unique data character count logic for floData. This string is prefixed before actual floData string in Raw Transaction - if (floDataCount <= 16) { - floDataCountString = floDataCount.toString(16); - floDataCountString = "0"+ floDataCountString; - } else if (floDataCount < 253) { - floDataCountString = floDataCount.toString(16); - } else if (floDataCount <= 1023) { - floDataCountAdjusted = (floDataCount - 253) + parseInt("0xfd00fd"); - floDataCountStringAdjusted = floDataCountAdjusted.toString(16); - floDataCountString = floDataCountStringAdjusted.substr(0,2)+ floDataCountStringAdjusted.substr(4,2)+ floDataCountStringAdjusted.substr(2,2); - } else { - floDataCountString = "Character Limit Exceeded"; - } - - - return Crypto.util.bytesToHex(buffer)+floDataCountString+flohex; // flochange -- Addition of floDataCountString and floData in serialization - } - - - - return btrx; - + + return KBigInt; + }; + + /* sign a "standard" input */ + btrx.signinput = function (index, wif, sigHashType) { + var key = bitjs.wif2pubkey(wif); + var shType = sigHashType || 1; + var signature = this.transactionSig(index, wif, shType); + var buf = []; + var sigBytes = Crypto.util.hexToBytes(signature); + buf.push(sigBytes.length); + buf = buf.concat(sigBytes); + var pubKeyBytes = Crypto.util.hexToBytes(key['pubkey']); + buf.push(pubKeyBytes.length); + buf = buf.concat(pubKeyBytes); + this.inputs[index].script = buf; + return true; } - - bitjs.numToBytes = function (num, bytes) { - if (typeof bytes === "undefined") bytes = 8; - if (bytes == 0) { - return []; - } else if (num == -1) { - return Crypto.util.hexToBytes("ffffffffffffffff"); + + /* sign inputs */ + btrx.sign = function (wif, sigHashType) { + var shType = sigHashType || 1; + for (var i = 0; i < this.inputs.length; i++) { + this.signinput(i, wif, shType); + } + return this.serialize(); + } + + + /* serialize a transaction */ + btrx.serialize = function () { + var buffer = []; + buffer = buffer.concat(bitjs.numToBytes(parseInt(this.version), 4)); + + buffer = buffer.concat(bitjs.numToVarInt(this.inputs.length)); + for (var i = 0; i < this.inputs.length; i++) { + var txin = this.inputs[i]; + buffer = buffer.concat(Crypto.util.hexToBytes(txin.outpoint.hash).reverse()); + buffer = buffer.concat(bitjs.numToBytes(parseInt(txin.outpoint.index), 4)); + var scriptBytes = txin.script; + buffer = buffer.concat(bitjs.numToVarInt(scriptBytes.length)); + buffer = buffer.concat(scriptBytes); + buffer = buffer.concat(bitjs.numToBytes(parseInt(txin.sequence), 4)); + + } + buffer = buffer.concat(bitjs.numToVarInt(this.outputs.length)); + + for (var i = 0; i < this.outputs.length; i++) { + var txout = this.outputs[i]; + buffer = buffer.concat(bitjs.numToBytes(txout.value, 8)); + var scriptBytes = txout.script; + buffer = buffer.concat(bitjs.numToVarInt(scriptBytes.length)); + buffer = buffer.concat(scriptBytes); + } + + buffer = buffer.concat(bitjs.numToBytes(parseInt(this.locktime),4)); + flohex = ascii_to_hexa(this.floData); + floDataCount = this.floData.length; + + //flochange -- creating unique data character count logic for floData. This string is prefixed before actual floData string in Raw Transaction + if (floDataCount <= 16) { + floDataCountString = floDataCount.toString(16); + floDataCountString = "0"+ floDataCountString; + } else if (floDataCount < 253) { + floDataCountString = floDataCount.toString(16); + } else if (floDataCount <= 1023) { + floDataCountAdjusted = (floDataCount - 253) + parseInt("0xfd00fd"); + floDataCountStringAdjusted = floDataCountAdjusted.toString(16); + floDataCountString = floDataCountStringAdjusted.substr(0,2)+ floDataCountStringAdjusted.substr(4,2)+ floDataCountStringAdjusted.substr(2,2); } else { - return [num % 256].concat(bitjs.numToBytes(Math.floor(num / 256), bytes - 1)); - } + floDataCountString = "Character Limit Exceeded"; + } + + + return Crypto.util.bytesToHex(buffer)+floDataCountString+flohex; // flochange -- Addition of floDataCountString and floData in serialization } - - bitjs.numToByteArray = function (num) { - if (num <= 256) { - return [num]; - } else { - return [num % 256].concat(bitjs.numToByteArray(Math.floor(num / 256))); - } - } - - bitjs.numToVarInt = function (num) { - if (num < 253) { - return [num]; - } else if (num < 65536) { - return [253].concat(bitjs.numToBytes(num, 2)); - } else if (num < 4294967296) { - return [254].concat(bitjs.numToBytes(num, 4)); - } else { - return [255].concat(bitjs.numToBytes(num, 8)); - } - } - - bitjs.bytesToNum = function (bytes) { - if (bytes.length == 0) return 0; - else return bytes[0] + 256 * bitjs.bytesToNum(bytes.slice(1)); - } - - /* clone an object */ - bitjs.clone = function (obj) { - if (obj == null || typeof (obj) != 'object') return obj; - var temp = new obj.constructor(); - - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - temp[key] = bitjs.clone(obj[key]); - } - } - return temp; - } - - var B58 = bitjs.Base58 = { - alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", - validRegex: /^[1-9A-HJ-NP-Za-km-z]+$/, - base: BigInteger.valueOf(58), - - /** - * Convert a byte array to a base58-encoded string. - * - * Written by Mike Hearn for BitcoinJ. - * Copyright (c) 2011 Google Inc. - * - * Ported to JavaScript by Stefan Thomas. - */ - encode: function (input) { - var bi = BigInteger.fromByteArrayUnsigned(input); - var chars = []; - - while (bi.compareTo(B58.base) >= 0) { - var mod = bi.mod(B58.base); - chars.unshift(B58.alphabet[mod.intValue()]); - bi = bi.subtract(mod).divide(B58.base); - } - chars.unshift(B58.alphabet[bi.intValue()]); - - // Convert leading zeros too. - for (var i = 0; i < input.length; i++) { - if (input[i] == 0x00) { - chars.unshift(B58.alphabet[0]); - } else break; - } - - return chars.join(''); - }, - - /** - * Convert a base58-encoded string to a byte array. - * - * Written by Mike Hearn for BitcoinJ. - * Copyright (c) 2011 Google Inc. - * - * Ported to JavaScript by Stefan Thomas. - */ - decode: function (input) { - var bi = BigInteger.valueOf(0); - var leadingZerosNum = 0; - for (var i = input.length - 1; i >= 0; i--) { - var alphaIndex = B58.alphabet.indexOf(input[i]); - if (alphaIndex < 0) { - throw "Invalid character"; - } - bi = bi.add(BigInteger.valueOf(alphaIndex) - .multiply(B58.base.pow(input.length - 1 - i))); - - // This counts leading zero bytes - if (input[i] == "1") leadingZerosNum++; - else leadingZerosNum = 0; - } - var bytes = bi.toByteArrayUnsigned(); - - // Add leading zeros - while (leadingZerosNum-- > 0) bytes.unshift(0); - - return bytes; - } - } - return bitjs; - - })(); - - - - /* - Copyright (c) 2011 Stefan Thomas - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - - //https://raw.github.com/bitcoinjs/bitcoinjs-lib/1a7fc9d063f864058809d06ef4542af40be3558f/src/bitcoin.js - (function (exports) { - var Bitcoin = exports; - })( - 'object' === typeof module ? module.exports : (window.Bitcoin = {}) - ); - - //https://raw.github.com/bitcoinjs/bitcoinjs-lib/c952aaeb3ee472e3776655b8ea07299ebed702c7/src/base58.js - (function (Bitcoin) { - Bitcoin.Base58 = { - alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", - validRegex: /^[1-9A-HJ-NP-Za-km-z]+$/, - base: BigInteger.valueOf(58), - - /** - * Convert a byte array to a base58-encoded string. - * - * Written by Mike Hearn for BitcoinJ. - * Copyright (c) 2011 Google Inc. - * - * Ported to JavaScript by Stefan Thomas. - */ - encode: function (input) { - var bi = BigInteger.fromByteArrayUnsigned(input); - var chars = []; - - while (bi.compareTo(B58.base) >= 0) { - var mod = bi.mod(B58.base); - chars.unshift(B58.alphabet[mod.intValue()]); - bi = bi.subtract(mod).divide(B58.base); - } - chars.unshift(B58.alphabet[bi.intValue()]); - - // Convert leading zeros too. - for (var i = 0; i < input.length; i++) { - if (input[i] == 0x00) { - chars.unshift(B58.alphabet[0]); - } else break; - } - - return chars.join(''); - }, - - /** - * Convert a base58-encoded string to a byte array. - * - * Written by Mike Hearn for BitcoinJ. - * Copyright (c) 2011 Google Inc. - * - * Ported to JavaScript by Stefan Thomas. - */ - decode: function (input) { - var bi = BigInteger.valueOf(0); - var leadingZerosNum = 0; - for (var i = input.length - 1; i >= 0; i--) { - var alphaIndex = B58.alphabet.indexOf(input[i]); - if (alphaIndex < 0) { - throw "Invalid character"; - } - bi = bi.add(BigInteger.valueOf(alphaIndex) - .multiply(B58.base.pow(input.length - 1 - i))); - - // This counts leading zero bytes - if (input[i] == "1") leadingZerosNum++; - else leadingZerosNum = 0; - } - var bytes = bi.toByteArrayUnsigned(); - - // Add leading zeros - while (leadingZerosNum-- > 0) bytes.unshift(0); - - return bytes; + + + + return btrx; + } + + bitjs.numToBytes = function (num, bytes) { + if (typeof bytes === "undefined") bytes = 8; + if (bytes == 0) { + return []; + } else if (num == -1) { + return Crypto.util.hexToBytes("ffffffffffffffff"); + } else { + return [num % 256].concat(bitjs.numToBytes(Math.floor(num / 256), bytes - 1)); + } + } + + bitjs.numToByteArray = function (num) { + if (num <= 256) { + return [num]; + } else { + return [num % 256].concat(bitjs.numToByteArray(Math.floor(num / 256))); + } + } + + bitjs.numToVarInt = function (num) { + if (num < 253) { + return [num]; + } else if (num < 65536) { + return [253].concat(bitjs.numToBytes(num, 2)); + } else if (num < 4294967296) { + return [254].concat(bitjs.numToBytes(num, 4)); + } else { + return [255].concat(bitjs.numToBytes(num, 8)); + } + } + + bitjs.bytesToNum = function (bytes) { + if (bytes.length == 0) return 0; + else return bytes[0] + 256 * bitjs.bytesToNum(bytes.slice(1)); + } + + /* clone an object */ + bitjs.clone = function (obj) { + if (obj == null || typeof (obj) != 'object') return obj; + var temp = new obj.constructor(); + + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + temp[key] = bitjs.clone(obj[key]); + } + } + return temp; + } + + var B58 = bitjs.Base58 = { + alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", + validRegex: /^[1-9A-HJ-NP-Za-km-z]+$/, + base: BigInteger.valueOf(58), + + /** + * Convert a byte array to a base58-encoded string. + * + * Written by Mike Hearn for BitcoinJ. + * Copyright (c) 2011 Google Inc. + * + * Ported to JavaScript by Stefan Thomas. + */ + encode: function (input) { + var bi = BigInteger.fromByteArrayUnsigned(input); + var chars = []; + + while (bi.compareTo(B58.base) >= 0) { + var mod = bi.mod(B58.base); + chars.unshift(B58.alphabet[mod.intValue()]); + bi = bi.subtract(mod).divide(B58.base); + } + chars.unshift(B58.alphabet[bi.intValue()]); + + // Convert leading zeros too. + for (var i = 0; i < input.length; i++) { + if (input[i] == 0x00) { + chars.unshift(B58.alphabet[0]); + } else break; + } + + return chars.join(''); + }, + + /** + * Convert a base58-encoded string to a byte array. + * + * Written by Mike Hearn for BitcoinJ. + * Copyright (c) 2011 Google Inc. + * + * Ported to JavaScript by Stefan Thomas. + */ + decode: function (input) { + var bi = BigInteger.valueOf(0); + var leadingZerosNum = 0; + for (var i = input.length - 1; i >= 0; i--) { + var alphaIndex = B58.alphabet.indexOf(input[i]); + if (alphaIndex < 0) { + throw "Invalid character"; + } + bi = bi.add(BigInteger.valueOf(alphaIndex) + .multiply(B58.base.pow(input.length - 1 - i))); + + // This counts leading zero bytes + if (input[i] == "1") leadingZerosNum++; + else leadingZerosNum = 0; + } + var bytes = bi.toByteArrayUnsigned(); + + // Add leading zeros + while (leadingZerosNum-- > 0) bytes.unshift(0); + + return bytes; + } + } + return bitjs; + + })(); + + + +/* +Copyright (c) 2011 Stefan Thomas + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +//https://raw.github.com/bitcoinjs/bitcoinjs-lib/1a7fc9d063f864058809d06ef4542af40be3558f/src/bitcoin.js +(function (exports) { + var Bitcoin = exports; +})( + 'object' === typeof module ? module.exports : (window.Bitcoin = {}) +); + +//https://raw.github.com/bitcoinjs/bitcoinjs-lib/c952aaeb3ee472e3776655b8ea07299ebed702c7/src/base58.js +(function (Bitcoin) { + Bitcoin.Base58 = { + alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", + validRegex: /^[1-9A-HJ-NP-Za-km-z]+$/, + base: BigInteger.valueOf(58), + + /** + * Convert a byte array to a base58-encoded string. + * + * Written by Mike Hearn for BitcoinJ. + * Copyright (c) 2011 Google Inc. + * + * Ported to JavaScript by Stefan Thomas. + */ + encode: function (input) { + var bi = BigInteger.fromByteArrayUnsigned(input); + var chars = []; + + while (bi.compareTo(B58.base) >= 0) { + var mod = bi.mod(B58.base); + chars.unshift(B58.alphabet[mod.intValue()]); + bi = bi.subtract(mod).divide(B58.base); + } + chars.unshift(B58.alphabet[bi.intValue()]); + + // Convert leading zeros too. + for (var i = 0; i < input.length; i++) { + if (input[i] == 0x00) { + chars.unshift(B58.alphabet[0]); + } else break; + } + + return chars.join(''); + }, + + /** + * Convert a base58-encoded string to a byte array. + * + * Written by Mike Hearn for BitcoinJ. + * Copyright (c) 2011 Google Inc. + * + * Ported to JavaScript by Stefan Thomas. + */ + decode: function (input) { + var bi = BigInteger.valueOf(0); + var leadingZerosNum = 0; + for (var i = input.length - 1; i >= 0; i--) { + var alphaIndex = B58.alphabet.indexOf(input[i]); + if (alphaIndex < 0) { + throw "Invalid character"; + } + bi = bi.add(BigInteger.valueOf(alphaIndex) + .multiply(B58.base.pow(input.length - 1 - i))); + + // This counts leading zero bytes + if (input[i] == "1") leadingZerosNum++; + else leadingZerosNum = 0; + } + var bytes = bi.toByteArrayUnsigned(); + + // Add leading zeros + while (leadingZerosNum-- > 0) bytes.unshift(0); + + return bytes; + } + }; + + var B58 = Bitcoin.Base58; +})( + 'undefined' != typeof Bitcoin ? Bitcoin : module.exports +); +//https://raw.github.com/bitcoinjs/bitcoinjs-lib/09e8c6e184d6501a0c2c59d73ca64db5c0d3eb95/src/address.js +Bitcoin.Address = function (bytes) { + if(floGlobals.blockchain == "FLO") + this.version = 0x23; // FLO mainnet public address + else if(floGlobals.blockchain == "FLO_TEST") + this.version = 0x73; // FLO testnet public address + if ("string" == typeof bytes) { + bytes = Bitcoin.Address.decodeString(bytes,this.version); + } + this.hash = bytes; +}; + +Bitcoin.Address.networkVersion = 0x23; // (FLO mainnet 0x23, 35D), (Bitcoin Mainnet, 0x00, 0D) // *this has no effect * + +/** +* Serialize this object as a standard Bitcoin address. +* +* Returns the address as a base58-encoded string in the standardized format. +*/ +Bitcoin.Address.prototype.toString = function () { + // Get a copy of the hash + var hash = this.hash.slice(0); + + // Version + hash.unshift(this.version); + var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); + var bytes = hash.concat(checksum.slice(0, 4)); + return Bitcoin.Base58.encode(bytes); +}; + +Bitcoin.Address.prototype.getHashBase64 = function () { + return Crypto.util.bytesToBase64(this.hash); +}; + +/** +* Parse a Bitcoin address contained in a string. +*/ +Bitcoin.Address.decodeString = function (string,version) { + var bytes = Bitcoin.Base58.decode(string); + var hash = bytes.slice(0, 21); + var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); + + if (checksum[0] != bytes[21] || + checksum[1] != bytes[22] || + checksum[2] != bytes[23] || + checksum[3] != bytes[24]) { + throw "Checksum validation failed!"; + } + + if (version != hash.shift()) { + throw "Version " + hash.shift() + " not supported!"; + } + + return hash; +}; +//https://raw.github.com/bitcoinjs/bitcoinjs-lib/e90780d3d3b8fc0d027d2bcb38b80479902f223e/src/ecdsa.js +Bitcoin.ECDSA = (function () { + var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); + var rng = new SecureRandom(); + + var P_OVER_FOUR = null; + + function implShamirsTrick(P, k, Q, l) { + var m = Math.max(k.bitLength(), l.bitLength()); + var Z = P.add2D(Q); + var R = P.curve.getInfinity(); + + for (var i = m - 1; i >= 0; --i) { + R = R.twice2D(); + + R.z = BigInteger.ONE; + + if (k.testBit(i)) { + if (l.testBit(i)) { + R = R.add2D(Z); + } else { + R = R.add2D(P); + } + } else { + if (l.testBit(i)) { + R = R.add2D(Q); + } + } + } + + return R; + }; + + var ECDSA = { + getBigRandom: function (limit) { + return new BigInteger(limit.bitLength(), rng) + .mod(limit.subtract(BigInteger.ONE)) + .add(BigInteger.ONE); + }, + sign: function (hash, priv) { + var d = priv; + var n = ecparams.getN(); + var e = BigInteger.fromByteArrayUnsigned(hash); + + do { + var k = ECDSA.getBigRandom(n); + var G = ecparams.getG(); + var Q = G.multiply(k); + var r = Q.getX().toBigInteger().mod(n); + } while (r.compareTo(BigInteger.ZERO) <= 0); + + var s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n); + + return ECDSA.serializeSig(r, s); + }, + + verify: function (hash, sig, pubkey) { + var r, s; + if (Bitcoin.Util.isArray(sig)) { + var obj = ECDSA.parseSig(sig); + r = obj.r; + s = obj.s; + } else if ("object" === typeof sig && sig.r && sig.s) { + r = sig.r; + s = sig.s; + } else { + throw "Invalid value for signature"; + } + + var Q; + if (pubkey instanceof ec.PointFp) { + Q = pubkey; + } else if (Bitcoin.Util.isArray(pubkey)) { + Q = EllipticCurve.PointFp.decodeFrom(ecparams.getCurve(), pubkey); + } else { + throw "Invalid format for pubkey value, must be byte array or ec.PointFp"; + } + var e = BigInteger.fromByteArrayUnsigned(hash); + + return ECDSA.verifyRaw(e, r, s, Q); + }, + + verifyRaw: function (e, r, s, Q) { + var n = ecparams.getN(); + var G = ecparams.getG(); + + if (r.compareTo(BigInteger.ONE) < 0 || + r.compareTo(n) >= 0) + return false; + + if (s.compareTo(BigInteger.ONE) < 0 || + s.compareTo(n) >= 0) + return false; + + var c = s.modInverse(n); + + var u1 = e.multiply(c).mod(n); + var u2 = r.multiply(c).mod(n); + + // TODO(!!!): For some reason Shamir's trick isn't working with + // signed message verification!? Probably an implementation + // error! + //var point = implShamirsTrick(G, u1, Q, u2); + var point = G.multiply(u1).add(Q.multiply(u2)); + + var v = point.getX().toBigInteger().mod(n); + + return v.equals(r); + }, + + /** + * Serialize a signature into DER format. + * + * Takes two BigIntegers representing r and s and returns a byte array. + */ + serializeSig: function (r, s) { + var rBa = r.toByteArraySigned(); + var sBa = s.toByteArraySigned(); + + var sequence = []; + sequence.push(0x02); // INTEGER + sequence.push(rBa.length); + sequence = sequence.concat(rBa); + + sequence.push(0x02); // INTEGER + sequence.push(sBa.length); + sequence = sequence.concat(sBa); + + sequence.unshift(sequence.length); + sequence.unshift(0x30); // SEQUENCE + + return sequence; + }, + + /** + * Parses a byte array containing a DER-encoded signature. + * + * This function will return an object of the form: + * + * { + * r: BigInteger, + * s: BigInteger + * } + */ + parseSig: function (sig) { + var cursor; + if (sig[0] != 0x30) + throw new Error("Signature not a valid DERSequence"); + + cursor = 2; + if (sig[cursor] != 0x02) + throw new Error("First element in signature must be a DERInteger");; + var rBa = sig.slice(cursor + 2, cursor + 2 + sig[cursor + 1]); + + cursor += 2 + sig[cursor + 1]; + if (sig[cursor] != 0x02) + throw new Error("Second element in signature must be a DERInteger"); + var sBa = sig.slice(cursor + 2, cursor + 2 + sig[cursor + 1]); + + cursor += 2 + sig[cursor + 1]; + + //if (cursor != sig.length) + // throw new Error("Extra bytes in signature"); + + var r = BigInteger.fromByteArrayUnsigned(rBa); + var s = BigInteger.fromByteArrayUnsigned(sBa); + + return { + r: r, + s: s + }; + }, + + parseSigCompact: function (sig) { + if (sig.length !== 65) { + throw "Signature has the wrong length"; + } + + // Signature is prefixed with a type byte storing three bits of + // information. + var i = sig[0] - 27; + if (i < 0 || i > 7) { + throw "Invalid signature type"; + } + + var n = ecparams.getN(); + var r = BigInteger.fromByteArrayUnsigned(sig.slice(1, 33)).mod(n); + var s = BigInteger.fromByteArrayUnsigned(sig.slice(33, 65)).mod(n); + + return { + r: r, + s: s, + i: i + }; + }, + + /** + * Recover a public key from a signature. + * + * See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public + * Key Recovery Operation". + * + * http://www.secg.org/download/aid-780/sec1-v2.pdf + */ + recoverPubKey: function (r, s, hash, i) { + // The recovery parameter i has two bits. + i = i & 3; + + // The less significant bit specifies whether the y coordinate + // of the compressed point is even or not. + var isYEven = i & 1; + + // The more significant bit specifies whether we should use the + // first or second candidate key. + var isSecondKey = i >> 1; + + var n = ecparams.getN(); + var G = ecparams.getG(); + var curve = ecparams.getCurve(); + var p = curve.getQ(); + var a = curve.getA().toBigInteger(); + var b = curve.getB().toBigInteger(); + + // We precalculate (p + 1) / 4 where p is if the field order + if (!P_OVER_FOUR) { + P_OVER_FOUR = p.add(BigInteger.ONE).divide(BigInteger.valueOf(4)); + } + + // 1.1 Compute x + var x = isSecondKey ? r.add(n) : r; + + // 1.3 Convert x to point + var alpha = x.multiply(x).multiply(x).add(a.multiply(x)).add(b).mod(p); + var beta = alpha.modPow(P_OVER_FOUR, p); + + var xorOdd = beta.isEven() ? (i % 2) : ((i + 1) % 2); + // If beta is even, but y isn't or vice versa, then convert it, + // otherwise we're done and y == beta. + var y = (beta.isEven() ? !isYEven : isYEven) ? beta : p.subtract(beta); + + // 1.4 Check that nR is at infinity + var R = new EllipticCurve.PointFp(curve, + curve.fromBigInteger(x), + curve.fromBigInteger(y)); + R.validate(); + + // 1.5 Compute e from M + var e = BigInteger.fromByteArrayUnsigned(hash); + var eNeg = BigInteger.ZERO.subtract(e).mod(n); + + // 1.6 Compute Q = r^-1 (sR - eG) + var rInv = r.modInverse(n); + var Q = implShamirsTrick(R, s, G, eNeg).multiply(rInv); + + Q.validate(); + if (!ECDSA.verifyRaw(e, r, s, Q)) { + throw "Pubkey recovery unsuccessful"; + } + + var pubKey = new Bitcoin.ECKey(); + pubKey.pub = Q; + return pubKey; + }, + + /** + * Calculate pubkey extraction parameter. + * + * When extracting a pubkey from a signature, we have to + * distinguish four different cases. Rather than putting this + * burden on the verifier, Bitcoin includes a 2-bit value with the + * signature. + * + * This function simply tries all four cases and returns the value + * that resulted in a successful pubkey recovery. + */ + calcPubkeyRecoveryParam: function (address, r, s, hash) { + for (var i = 0; i < 4; i++) { + try { + var pubkey = Bitcoin.ECDSA.recoverPubKey(r, s, hash, i); + if (pubkey.getBitcoinAddress().toString() == address) { + return i; + } + } catch (e) {} + } + throw "Unable to find valid recovery factor"; + } + }; + + return ECDSA; +})(); +Bitcoin.KeyPool = (function () { + var KeyPool = function () { + this.keyArray = []; + + this.push = function (item) { + if (item == null || item.priv == null) return; + var doAdd = true; + // prevent duplicates from being added to the array + for (var index in this.keyArray) { + var currentItem = this.keyArray[index]; + if (currentItem != null && currentItem.priv != null && item.getBitcoinAddress() == currentItem.getBitcoinAddress()) { + doAdd = false; + break; + } + } + if (doAdd) this.keyArray.push(item); }; - - var B58 = Bitcoin.Base58; - })( - 'undefined' != typeof Bitcoin ? Bitcoin : module.exports - ); - //https://raw.github.com/bitcoinjs/bitcoinjs-lib/09e8c6e184d6501a0c2c59d73ca64db5c0d3eb95/src/address.js - Bitcoin.Address = function (bytes) { - if(floGlobals.blockchain == "FLO") - this.version = 0x23; // FLO mainnet public address - else if(floGlobals.blockchain == "FLO_TEST") - this.version = 0x73; // FLO testnet public address - if ("string" == typeof bytes) { - bytes = Bitcoin.Address.decodeString(bytes,this.version); - } - this.hash = bytes; + + this.reset = function () { + this.keyArray = []; + }; + + this.getArray = function () { + // copy array + return this.keyArray.slice(0); + }; + + this.setArray = function (ka) { + this.keyArray = ka; + }; + + this.length = function () { + return this.keyArray.length; + }; + + this.toString = function () { + var keyPoolString = "# = " + this.length() + "\n"; + var pool = this.getArray(); + for (var index in pool) { + var item = pool[index]; + if (Bitcoin.Util.hasMethods(item, 'getBitcoinAddress', 'toString')) { + if (item != null) { + keyPoolString += "\"" + item.getBitcoinAddress() + "\"" + ", \"" + item.toString("wif") + "\"\n"; + } + } + } + + return keyPoolString; + }; + + return this; }; - - Bitcoin.Address.networkVersion = 0x23; // (FLO mainnet 0x23, 35D), (Bitcoin Mainnet, 0x00, 0D) // *this has no effect * - + + return new KeyPool(); +})(); + +Bitcoin.Bip38Key = (function () { + var Bip38 = function (address, encryptedKey) { + this.address = address; + this.priv = encryptedKey; + }; + + Bip38.prototype.getBitcoinAddress = function () { + return this.address; + }; + + Bip38.prototype.toString = function () { + return this.priv; + }; + + return Bip38; +})(); + +//https://raw.github.com/pointbiz/bitcoinjs-lib/9b2f94a028a7bc9bed94e0722563e9ff1d8e8db8/src/eckey.js +Bitcoin.ECKey = (function () { + var ECDSA = Bitcoin.ECDSA; + var KeyPool = Bitcoin.KeyPool; + var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); + + var ECKey = function (input) { + if (!input) { + // Generate new key + var n = ecparams.getN(); + this.priv = ECDSA.getBigRandom(n); + } else if (input instanceof BigInteger) { + // Input is a private key value + this.priv = input; + } else if (Bitcoin.Util.isArray(input)) { + // Prepend zero byte to prevent interpretation as negative integer + this.priv = BigInteger.fromByteArrayUnsigned(input); + } else if ("string" == typeof input) { + var bytes = null; + try{ + + // This part is edited for FLO. FLO WIF are always compressed WIF. FLO WIF (private key) starts with R for mainnet and c for testnet. + if(((floGlobals.blockchain == "FLO") && /^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(input)) || + ((floGlobals.blockchain == "FLO_TEST") && /^c[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(input))) { + bytes = ECKey.decodeCompressedWalletImportFormat(input); + this.compressed = true; + }else if (ECKey.isHexFormat(input)) { + bytes = Crypto.util.hexToBytes(input); + } + + + /* + if (ECKey.isWalletImportFormat(input)) { + bytes = ECKey.decodeWalletImportFormat(input); + } else if (ECKey.isCompressedWalletImportFormat(input)) { + bytes = ECKey.decodeCompressedWalletImportFormat(input); + this.compressed = true; + } else if (ECKey.isMiniFormat(input)) { + bytes = Crypto.SHA256(input, { asBytes: true }); + } else if (ECKey.isHexFormat(input)) { + bytes = Crypto.util.hexToBytes(input); + } else if (ECKey.isBase64Format(input)) { + bytes = Crypto.util.base64ToBytes(input); + } + */ + } catch (exc1) { + this.setError(exc1); + } + + if (ECKey.isBase6Format(input)) { + this.priv = new BigInteger(input, 6); + } else if (bytes == null || bytes.length != 32) { + this.priv = null; + } else { + // Prepend zero byte to prevent interpretation as negative integer + this.priv = BigInteger.fromByteArrayUnsigned(bytes); + } + } + + this.compressed = (this.compressed == undefined) ? !!ECKey.compressByDefault : this.compressed; + try { + // check not zero + if (this.priv != null && BigInteger.ZERO.compareTo(this.priv) == 0) this.setError("Error: BigInteger equal to zero."); + // valid range [0x1, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140]) + var hexKeyRangeLimit = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140"; + var rangeLimitBytes = Crypto.util.hexToBytes(hexKeyRangeLimit); + var limitBigInt = BigInteger.fromByteArrayUnsigned(rangeLimitBytes); + if (this.priv != null && limitBigInt.compareTo(this.priv) < 0) this.setError("Error: BigInteger outside of curve range.") + + if (this.priv != null) { + KeyPool.push(this); + } + } catch (exc2) { + this.setError(exc2); + } + }; + + if(floGlobals.blockchain == "FLO") + ECKey.privateKeyPrefix = 0xA3; //(Bitcoin mainnet 0x80 testnet 0xEF) (FLO mainnet 0xA3 163 D) + else if(floGlobals.blockchain == "FLO_TEST") + ECKey.privateKeyPrefix = 0xEF; //FLO testnet + /** - * Serialize this object as a standard Bitcoin address. + * Whether public keys should be returned compressed by default. + */ + ECKey.compressByDefault = false; + + /** + * Set whether the public key should be returned compressed or not. + */ + ECKey.prototype.setError = function (err) { + this.error = err; + this.priv = null; + return this; + }; + + /** + * Set whether the public key should be returned compressed or not. + */ + ECKey.prototype.setCompressed = function (v) { + this.compressed = !!v; + if (this.pubPoint) this.pubPoint.compressed = this.compressed; + return this; + }; + + /* + * Return public key as a byte array in DER encoding + */ + ECKey.prototype.getPub = function () { + if (this.compressed) { + if (this.pubComp) return this.pubComp; + return this.pubComp = this.getPubPoint().getEncoded(1); + } else { + if (this.pubUncomp) return this.pubUncomp; + return this.pubUncomp = this.getPubPoint().getEncoded(0); + } + }; + + /** + * Return public point as ECPoint object. + */ + ECKey.prototype.getPubPoint = function () { + if (!this.pubPoint) { + this.pubPoint = ecparams.getG().multiply(this.priv); + this.pubPoint.compressed = this.compressed; + } + return this.pubPoint; + }; + + ECKey.prototype.getPubKeyHex = function () { + if (this.compressed) { + if (this.pubKeyHexComp) return this.pubKeyHexComp; + return this.pubKeyHexComp = Crypto.util.bytesToHex(this.getPub()).toString().toUpperCase(); + } else { + if (this.pubKeyHexUncomp) return this.pubKeyHexUncomp; + return this.pubKeyHexUncomp = Crypto.util.bytesToHex(this.getPub()).toString().toUpperCase(); + } + }; + + /** + * Get the pubKeyHash for this key. * - * Returns the address as a base58-encoded string in the standardized format. + * This is calculated as RIPE160(SHA256([encoded pubkey])) and returned as + * a byte array. */ - Bitcoin.Address.prototype.toString = function () { - // Get a copy of the hash - var hash = this.hash.slice(0); - - // Version - hash.unshift(this.version); - var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); - var bytes = hash.concat(checksum.slice(0, 4)); - return Bitcoin.Base58.encode(bytes); + ECKey.prototype.getPubKeyHash = function () { + if (this.compressed) { + if (this.pubKeyHashComp) return this.pubKeyHashComp; + return this.pubKeyHashComp = Bitcoin.Util.sha256ripe160(this.getPub()); + } else { + if (this.pubKeyHashUncomp) return this.pubKeyHashUncomp; + return this.pubKeyHashUncomp = Bitcoin.Util.sha256ripe160(this.getPub()); + } }; - - Bitcoin.Address.prototype.getHashBase64 = function () { - return Crypto.util.bytesToBase64(this.hash); + + ECKey.prototype.getBitcoinAddress = function () { + var hash = this.getPubKeyHash(); + var addr = new Bitcoin.Address(hash); + return addr.toString(); }; - + + /* + * Takes a public point as a hex string or byte array + */ + ECKey.prototype.setPub = function (pub) { + // byte array + if (Bitcoin.Util.isArray(pub)) { + pub = Crypto.util.bytesToHex(pub).toString().toUpperCase(); + } + var ecPoint = ecparams.getCurve().decodePointHex(pub); + this.setCompressed(ecPoint.compressed); + this.pubPoint = ecPoint; + return this; + }; + + // Sipa Private Key Wallet Import Format + ECKey.prototype.getBitcoinWalletImportFormat = function () { + var bytes = this.getBitcoinPrivateKeyByteArray(); + if (bytes == null) return ""; + bytes.unshift(ECKey.privateKeyPrefix); // prepend 0x80 byte + if (this.compressed) bytes.push(0x01); // append 0x01 byte for compressed format + var checksum = Crypto.SHA256(Crypto.SHA256(bytes, { asBytes: true }), { asBytes: true }); + bytes = bytes.concat(checksum.slice(0, 4)); + var privWif = Bitcoin.Base58.encode(bytes); + return privWif; + }; + + // Private Key Hex Format + ECKey.prototype.getBitcoinHexFormat = function () { + return Crypto.util.bytesToHex(this.getBitcoinPrivateKeyByteArray()).toString().toUpperCase(); + }; + + // Private Key Base64 Format + ECKey.prototype.getBitcoinBase64Format = function () { + return Crypto.util.bytesToBase64(this.getBitcoinPrivateKeyByteArray()); + }; + + ECKey.prototype.getBitcoinPrivateKeyByteArray = function () { + if (this.priv == null) return null; + // Get a copy of private key as a byte array + var bytes = this.priv.toByteArrayUnsigned(); + // zero pad if private key is less than 32 bytes + while (bytes.length < 32) bytes.unshift(0x00); + return bytes; + }; + + ECKey.prototype.toString = function (format) { + format = format || ""; + if (format.toString().toLowerCase() == "base64" || format.toString().toLowerCase() == "b64") { + return this.getBitcoinBase64Format(); + } + // Wallet Import Format + else if (format.toString().toLowerCase() == "wif") { + return this.getBitcoinWalletImportFormat(); + } + else { + return this.getBitcoinHexFormat(); + } + }; + + ECKey.prototype.sign = function (hash) { + return ECDSA.sign(hash, this.priv); + }; + + ECKey.prototype.verify = function (hash, sig) { + return ECDSA.verify(hash, sig, this.getPub()); + }; + /** - * Parse a Bitcoin address contained in a string. + * Parse a wallet import format private key contained in a string. */ - Bitcoin.Address.decodeString = function (string,version) { - var bytes = Bitcoin.Base58.decode(string); - var hash = bytes.slice(0, 21); + ECKey.decodeWalletImportFormat = function (privStr) { + var bytes = Bitcoin.Base58.decode(privStr); + var hash = bytes.slice(0, 33); var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); - - if (checksum[0] != bytes[21] || - checksum[1] != bytes[22] || - checksum[2] != bytes[23] || - checksum[3] != bytes[24]) { + if (checksum[0] != bytes[33] || + checksum[1] != bytes[34] || + checksum[2] != bytes[35] || + checksum[3] != bytes[36]) { throw "Checksum validation failed!"; + } - - if (version != hash.shift()) { - throw "Version " + hash.shift() + " not supported!"; + var version = hash.shift(); + if (version != ECKey.privateKeyPrefix) { + throw "Version " + version + " not supported!"; } - return hash; }; - //https://raw.github.com/bitcoinjs/bitcoinjs-lib/e90780d3d3b8fc0d027d2bcb38b80479902f223e/src/ecdsa.js - Bitcoin.ECDSA = (function () { - var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); - var rng = new SecureRandom(); - - var P_OVER_FOUR = null; - - function implShamirsTrick(P, k, Q, l) { - var m = Math.max(k.bitLength(), l.bitLength()); - var Z = P.add2D(Q); - var R = P.curve.getInfinity(); - - for (var i = m - 1; i >= 0; --i) { - R = R.twice2D(); - - R.z = BigInteger.ONE; - - if (k.testBit(i)) { - if (l.testBit(i)) { - R = R.add2D(Z); - } else { - R = R.add2D(P); - } - } else { - if (l.testBit(i)) { - R = R.add2D(Q); - } - } - } - - return R; - }; - - var ECDSA = { - getBigRandom: function (limit) { - return new BigInteger(limit.bitLength(), rng) - .mod(limit.subtract(BigInteger.ONE)) - .add(BigInteger.ONE); - }, - sign: function (hash, priv) { - var d = priv; - var n = ecparams.getN(); - var e = BigInteger.fromByteArrayUnsigned(hash); - - do { - var k = ECDSA.getBigRandom(n); - var G = ecparams.getG(); - var Q = G.multiply(k); - var r = Q.getX().toBigInteger().mod(n); - } while (r.compareTo(BigInteger.ZERO) <= 0); - - var s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n); - - return ECDSA.serializeSig(r, s); - }, - - verify: function (hash, sig, pubkey) { - var r, s; - if (Bitcoin.Util.isArray(sig)) { - var obj = ECDSA.parseSig(sig); - r = obj.r; - s = obj.s; - } else if ("object" === typeof sig && sig.r && sig.s) { - r = sig.r; - s = sig.s; - } else { - throw "Invalid value for signature"; - } - - var Q; - if (pubkey instanceof ec.PointFp) { - Q = pubkey; - } else if (Bitcoin.Util.isArray(pubkey)) { - Q = EllipticCurve.PointFp.decodeFrom(ecparams.getCurve(), pubkey); - } else { - throw "Invalid format for pubkey value, must be byte array or ec.PointFp"; - } - var e = BigInteger.fromByteArrayUnsigned(hash); - - return ECDSA.verifyRaw(e, r, s, Q); - }, - - verifyRaw: function (e, r, s, Q) { - var n = ecparams.getN(); - var G = ecparams.getG(); - - if (r.compareTo(BigInteger.ONE) < 0 || - r.compareTo(n) >= 0) - return false; - - if (s.compareTo(BigInteger.ONE) < 0 || - s.compareTo(n) >= 0) - return false; - - var c = s.modInverse(n); - - var u1 = e.multiply(c).mod(n); - var u2 = r.multiply(c).mod(n); - - // TODO(!!!): For some reason Shamir's trick isn't working with - // signed message verification!? Probably an implementation - // error! - //var point = implShamirsTrick(G, u1, Q, u2); - var point = G.multiply(u1).add(Q.multiply(u2)); - - var v = point.getX().toBigInteger().mod(n); - - return v.equals(r); - }, - - /** - * Serialize a signature into DER format. - * - * Takes two BigIntegers representing r and s and returns a byte array. - */ - serializeSig: function (r, s) { - var rBa = r.toByteArraySigned(); - var sBa = s.toByteArraySigned(); - - var sequence = []; - sequence.push(0x02); // INTEGER - sequence.push(rBa.length); - sequence = sequence.concat(rBa); - - sequence.push(0x02); // INTEGER - sequence.push(sBa.length); - sequence = sequence.concat(sBa); - - sequence.unshift(sequence.length); - sequence.unshift(0x30); // SEQUENCE - - return sequence; - }, - - /** - * Parses a byte array containing a DER-encoded signature. - * - * This function will return an object of the form: - * - * { - * r: BigInteger, - * s: BigInteger - * } - */ - parseSig: function (sig) { - var cursor; - if (sig[0] != 0x30) - throw new Error("Signature not a valid DERSequence"); - - cursor = 2; - if (sig[cursor] != 0x02) - throw new Error("First element in signature must be a DERInteger");; - var rBa = sig.slice(cursor + 2, cursor + 2 + sig[cursor + 1]); - - cursor += 2 + sig[cursor + 1]; - if (sig[cursor] != 0x02) - throw new Error("Second element in signature must be a DERInteger"); - var sBa = sig.slice(cursor + 2, cursor + 2 + sig[cursor + 1]); - - cursor += 2 + sig[cursor + 1]; - - //if (cursor != sig.length) - // throw new Error("Extra bytes in signature"); - - var r = BigInteger.fromByteArrayUnsigned(rBa); - var s = BigInteger.fromByteArrayUnsigned(sBa); - - return { - r: r, - s: s - }; - }, - - parseSigCompact: function (sig) { - if (sig.length !== 65) { - throw "Signature has the wrong length"; - } - - // Signature is prefixed with a type byte storing three bits of - // information. - var i = sig[0] - 27; - if (i < 0 || i > 7) { - throw "Invalid signature type"; - } - - var n = ecparams.getN(); - var r = BigInteger.fromByteArrayUnsigned(sig.slice(1, 33)).mod(n); - var s = BigInteger.fromByteArrayUnsigned(sig.slice(33, 65)).mod(n); - - return { - r: r, - s: s, - i: i - }; - }, - - /** - * Recover a public key from a signature. - * - * See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public - * Key Recovery Operation". - * - * http://www.secg.org/download/aid-780/sec1-v2.pdf - */ - recoverPubKey: function (r, s, hash, i) { - // The recovery parameter i has two bits. - i = i & 3; - - // The less significant bit specifies whether the y coordinate - // of the compressed point is even or not. - var isYEven = i & 1; - - // The more significant bit specifies whether we should use the - // first or second candidate key. - var isSecondKey = i >> 1; - - var n = ecparams.getN(); - var G = ecparams.getG(); - var curve = ecparams.getCurve(); - var p = curve.getQ(); - var a = curve.getA().toBigInteger(); - var b = curve.getB().toBigInteger(); - - // We precalculate (p + 1) / 4 where p is if the field order - if (!P_OVER_FOUR) { - P_OVER_FOUR = p.add(BigInteger.ONE).divide(BigInteger.valueOf(4)); - } - - // 1.1 Compute x - var x = isSecondKey ? r.add(n) : r; - - // 1.3 Convert x to point - var alpha = x.multiply(x).multiply(x).add(a.multiply(x)).add(b).mod(p); - var beta = alpha.modPow(P_OVER_FOUR, p); - - var xorOdd = beta.isEven() ? (i % 2) : ((i + 1) % 2); - // If beta is even, but y isn't or vice versa, then convert it, - // otherwise we're done and y == beta. - var y = (beta.isEven() ? !isYEven : isYEven) ? beta : p.subtract(beta); - - // 1.4 Check that nR is at infinity - var R = new EllipticCurve.PointFp(curve, - curve.fromBigInteger(x), - curve.fromBigInteger(y)); - R.validate(); - - // 1.5 Compute e from M - var e = BigInteger.fromByteArrayUnsigned(hash); - var eNeg = BigInteger.ZERO.subtract(e).mod(n); - - // 1.6 Compute Q = r^-1 (sR - eG) - var rInv = r.modInverse(n); - var Q = implShamirsTrick(R, s, G, eNeg).multiply(rInv); - - Q.validate(); - if (!ECDSA.verifyRaw(e, r, s, Q)) { - throw "Pubkey recovery unsuccessful"; - } - - var pubKey = new Bitcoin.ECKey(); - pubKey.pub = Q; - return pubKey; - }, - - /** - * Calculate pubkey extraction parameter. - * - * When extracting a pubkey from a signature, we have to - * distinguish four different cases. Rather than putting this - * burden on the verifier, Bitcoin includes a 2-bit value with the - * signature. - * - * This function simply tries all four cases and returns the value - * that resulted in a successful pubkey recovery. - */ - calcPubkeyRecoveryParam: function (address, r, s, hash) { - for (var i = 0; i < 4; i++) { - try { - var pubkey = Bitcoin.ECDSA.recoverPubKey(r, s, hash, i); - if (pubkey.getBitcoinAddress().toString() == address) { - return i; - } - } catch (e) {} - } - throw "Unable to find valid recovery factor"; - } - }; - - return ECDSA; - })(); - Bitcoin.KeyPool = (function () { - var KeyPool = function () { - this.keyArray = []; - - this.push = function (item) { - if (item == null || item.priv == null) return; - var doAdd = true; - // prevent duplicates from being added to the array - for (var index in this.keyArray) { - var currentItem = this.keyArray[index]; - if (currentItem != null && currentItem.priv != null && item.getBitcoinAddress() == currentItem.getBitcoinAddress()) { - doAdd = false; - break; - } - } - if (doAdd) this.keyArray.push(item); - }; - - this.reset = function () { - this.keyArray = []; - }; - - this.getArray = function () { - // copy array - return this.keyArray.slice(0); - }; - - this.setArray = function (ka) { - this.keyArray = ka; - }; - - this.length = function () { - return this.keyArray.length; - }; - - this.toString = function () { - var keyPoolString = "# = " + this.length() + "\n"; - var pool = this.getArray(); - for (var index in pool) { - var item = pool[index]; - if (Bitcoin.Util.hasMethods(item, 'getBitcoinAddress', 'toString')) { - if (item != null) { - keyPoolString += "\"" + item.getBitcoinAddress() + "\"" + ", \"" + item.toString("wif") + "\"\n"; - } - } - } - - return keyPoolString; - }; - - return this; - }; - - return new KeyPool(); - })(); - - Bitcoin.Bip38Key = (function () { - var Bip38 = function (address, encryptedKey) { - this.address = address; - this.priv = encryptedKey; - }; - - Bip38.prototype.getBitcoinAddress = function () { - return this.address; - }; - - Bip38.prototype.toString = function () { - return this.priv; - }; - - return Bip38; - })(); - - //https://raw.github.com/pointbiz/bitcoinjs-lib/9b2f94a028a7bc9bed94e0722563e9ff1d8e8db8/src/eckey.js - Bitcoin.ECKey = (function () { - var ECDSA = Bitcoin.ECDSA; - var KeyPool = Bitcoin.KeyPool; - var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); - - var ECKey = function (input) { - if (!input) { - // Generate new key - var n = ecparams.getN(); - this.priv = ECDSA.getBigRandom(n); - } else if (input instanceof BigInteger) { - // Input is a private key value - this.priv = input; - } else if (Bitcoin.Util.isArray(input)) { - // Prepend zero byte to prevent interpretation as negative integer - this.priv = BigInteger.fromByteArrayUnsigned(input); - } else if ("string" == typeof input) { - var bytes = null; - try{ - - // This part is edited for FLO. FLO WIF are always compressed WIF. FLO WIF (private key) starts with R for mainnet and c for testnet. - if(((floGlobals.blockchain == "FLO") && /^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(input)) || - ((floGlobals.blockchain == "FLO_TEST") && /^c[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(input))) { - bytes = ECKey.decodeCompressedWalletImportFormat(input); - this.compressed = true; - }else if (ECKey.isHexFormat(input)) { - bytes = Crypto.util.hexToBytes(input); - } - - - /* - if (ECKey.isWalletImportFormat(input)) { - bytes = ECKey.decodeWalletImportFormat(input); - } else if (ECKey.isCompressedWalletImportFormat(input)) { - bytes = ECKey.decodeCompressedWalletImportFormat(input); - this.compressed = true; - } else if (ECKey.isMiniFormat(input)) { - bytes = Crypto.SHA256(input, { asBytes: true }); - } else if (ECKey.isHexFormat(input)) { - bytes = Crypto.util.hexToBytes(input); - } else if (ECKey.isBase64Format(input)) { - bytes = Crypto.util.base64ToBytes(input); - } - */ - } catch (exc1) { - this.setError(exc1); - } - - if (ECKey.isBase6Format(input)) { - this.priv = new BigInteger(input, 6); - } else if (bytes == null || bytes.length != 32) { - this.priv = null; - } else { - // Prepend zero byte to prevent interpretation as negative integer - this.priv = BigInteger.fromByteArrayUnsigned(bytes); - } - } - - this.compressed = (this.compressed == undefined) ? !!ECKey.compressByDefault : this.compressed; - try { - // check not zero - if (this.priv != null && BigInteger.ZERO.compareTo(this.priv) == 0) this.setError("Error: BigInteger equal to zero."); - // valid range [0x1, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140]) - var hexKeyRangeLimit = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140"; - var rangeLimitBytes = Crypto.util.hexToBytes(hexKeyRangeLimit); - var limitBigInt = BigInteger.fromByteArrayUnsigned(rangeLimitBytes); - if (this.priv != null && limitBigInt.compareTo(this.priv) < 0) this.setError("Error: BigInteger outside of curve range.") - - if (this.priv != null) { - KeyPool.push(this); - } - } catch (exc2) { - this.setError(exc2); - } - }; - - if(floGlobals.blockchain == "FLO") - ECKey.privateKeyPrefix = 0xA3; //(Bitcoin mainnet 0x80 testnet 0xEF) (FLO mainnet 0xA3 163 D) - else if(floGlobals.blockchain == "FLO_TEST") - ECKey.privateKeyPrefix = 0xEF; //FLO testnet - - /** - * Whether public keys should be returned compressed by default. - */ - ECKey.compressByDefault = false; - - /** - * Set whether the public key should be returned compressed or not. - */ - ECKey.prototype.setError = function (err) { - this.error = err; - this.priv = null; - return this; - }; - - /** - * Set whether the public key should be returned compressed or not. - */ - ECKey.prototype.setCompressed = function (v) { - this.compressed = !!v; - if (this.pubPoint) this.pubPoint.compressed = this.compressed; - return this; - }; - - /* - * Return public key as a byte array in DER encoding - */ - ECKey.prototype.getPub = function () { - if (this.compressed) { - if (this.pubComp) return this.pubComp; - return this.pubComp = this.getPubPoint().getEncoded(1); - } else { - if (this.pubUncomp) return this.pubUncomp; - return this.pubUncomp = this.getPubPoint().getEncoded(0); - } - }; - - /** - * Return public point as ECPoint object. - */ - ECKey.prototype.getPubPoint = function () { - if (!this.pubPoint) { - this.pubPoint = ecparams.getG().multiply(this.priv); - this.pubPoint.compressed = this.compressed; - } - return this.pubPoint; - }; - - ECKey.prototype.getPubKeyHex = function () { - if (this.compressed) { - if (this.pubKeyHexComp) return this.pubKeyHexComp; - return this.pubKeyHexComp = Crypto.util.bytesToHex(this.getPub()).toString().toUpperCase(); - } else { - if (this.pubKeyHexUncomp) return this.pubKeyHexUncomp; - return this.pubKeyHexUncomp = Crypto.util.bytesToHex(this.getPub()).toString().toUpperCase(); - } - }; - - /** - * Get the pubKeyHash for this key. - * - * This is calculated as RIPE160(SHA256([encoded pubkey])) and returned as - * a byte array. - */ - ECKey.prototype.getPubKeyHash = function () { - if (this.compressed) { - if (this.pubKeyHashComp) return this.pubKeyHashComp; - return this.pubKeyHashComp = Bitcoin.Util.sha256ripe160(this.getPub()); - } else { - if (this.pubKeyHashUncomp) return this.pubKeyHashUncomp; - return this.pubKeyHashUncomp = Bitcoin.Util.sha256ripe160(this.getPub()); - } - }; - - ECKey.prototype.getBitcoinAddress = function () { - var hash = this.getPubKeyHash(); - var addr = new Bitcoin.Address(hash); - return addr.toString(); - }; - - /* - * Takes a public point as a hex string or byte array - */ - ECKey.prototype.setPub = function (pub) { - // byte array - if (Bitcoin.Util.isArray(pub)) { - pub = Crypto.util.bytesToHex(pub).toString().toUpperCase(); - } - var ecPoint = ecparams.getCurve().decodePointHex(pub); - this.setCompressed(ecPoint.compressed); - this.pubPoint = ecPoint; - return this; - }; - - // Sipa Private Key Wallet Import Format - ECKey.prototype.getBitcoinWalletImportFormat = function () { - var bytes = this.getBitcoinPrivateKeyByteArray(); - if (bytes == null) return ""; - bytes.unshift(ECKey.privateKeyPrefix); // prepend 0x80 byte - if (this.compressed) bytes.push(0x01); // append 0x01 byte for compressed format - var checksum = Crypto.SHA256(Crypto.SHA256(bytes, { asBytes: true }), { asBytes: true }); - bytes = bytes.concat(checksum.slice(0, 4)); - var privWif = Bitcoin.Base58.encode(bytes); - return privWif; - }; - - // Private Key Hex Format - ECKey.prototype.getBitcoinHexFormat = function () { - return Crypto.util.bytesToHex(this.getBitcoinPrivateKeyByteArray()).toString().toUpperCase(); - }; - - // Private Key Base64 Format - ECKey.prototype.getBitcoinBase64Format = function () { - return Crypto.util.bytesToBase64(this.getBitcoinPrivateKeyByteArray()); - }; - - ECKey.prototype.getBitcoinPrivateKeyByteArray = function () { - if (this.priv == null) return null; - // Get a copy of private key as a byte array - var bytes = this.priv.toByteArrayUnsigned(); - // zero pad if private key is less than 32 bytes - while (bytes.length < 32) bytes.unshift(0x00); - return bytes; - }; - - ECKey.prototype.toString = function (format) { - format = format || ""; - if (format.toString().toLowerCase() == "base64" || format.toString().toLowerCase() == "b64") { - return this.getBitcoinBase64Format(); - } - // Wallet Import Format - else if (format.toString().toLowerCase() == "wif") { - return this.getBitcoinWalletImportFormat(); - } - else { - return this.getBitcoinHexFormat(); - } - }; - - ECKey.prototype.sign = function (hash) { - return ECDSA.sign(hash, this.priv); - }; - - ECKey.prototype.verify = function (hash, sig) { - return ECDSA.verify(hash, sig, this.getPub()); - }; - - /** - * Parse a wallet import format private key contained in a string. - */ - ECKey.decodeWalletImportFormat = function (privStr) { - var bytes = Bitcoin.Base58.decode(privStr); - var hash = bytes.slice(0, 33); - var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); - if (checksum[0] != bytes[33] || - checksum[1] != bytes[34] || - checksum[2] != bytes[35] || - checksum[3] != bytes[36]) { - throw "Checksum validation failed!"; - - } - var version = hash.shift(); - if (version != ECKey.privateKeyPrefix) { - throw "Version " + version + " not supported!"; - } - return hash; - }; - - /** - * Parse a compressed wallet import format private key contained in a string. - */ - ECKey.decodeCompressedWalletImportFormat = function (privStr) { - var bytes = Bitcoin.Base58.decode(privStr); - var hash = bytes.slice(0, 34); - var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); - if (checksum[0] != bytes[34] || - checksum[1] != bytes[35] || - checksum[2] != bytes[36] || - checksum[3] != bytes[37]) { - throw "Checksum validation failed!"; - } - var version = hash.shift(); - if (version != ECKey.privateKeyPrefix) { - throw "Version " + version + " not supported!"; - } - hash.pop(); - return hash; - }; - - // 64 characters [0-9A-F] - ECKey.isHexFormat = function (key) { - key = key.toString(); - return /^[A-Fa-f0-9]{64}$/.test(key); - }; - - // 51 characters base58, always starts with a '5' - ECKey.isWalletImportFormat = function (key) { - key = key.toString(); - return (ECKey.privateKeyPrefix == 0x80) ? - (/^5[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{50}$/.test(key)) : - (/^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{50}$/.test(key)); - }; - - // 52 characters base58 - ECKey.isCompressedWalletImportFormat = function (key) { - key = key.toString(); - return (ECKey.privateKeyPrefix == 0x80) ? - (/^[LK][123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(key)) : - (/^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(key)); - }; - - // 44 characters - ECKey.isBase64Format = function (key) { - key = key.toString(); - return (/^[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789=+\/]{44}$/.test(key)); - }; - - // 99 characters, 1=1, if using dice convert 6 to 0 - ECKey.isBase6Format = function (key) { - key = key.toString(); - return (/^[012345]{99}$/.test(key)); - }; - - // 22, 26 or 30 characters, always starts with an 'S' - ECKey.isMiniFormat = function (key) { - key = key.toString(); - var validChars22 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21}$/.test(key); - var validChars26 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{25}$/.test(key); - var validChars30 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{29}$/.test(key); - var testBytes = Crypto.SHA256(key + "?", { asBytes: true }); - - return ((testBytes[0] === 0x00 || testBytes[0] === 0x01) && (validChars22 || validChars26 || validChars30)); - }; - - return ECKey; - })(); - //https://raw.github.com/bitcoinjs/bitcoinjs-lib/09e8c6e184d6501a0c2c59d73ca64db5c0d3eb95/src/util.js - // Bitcoin utility functions - Bitcoin.Util = { - /** - * Cross-browser compatibility version of Array.isArray. - */ - isArray: Array.isArray || function (o) { - return Object.prototype.toString.call(o) === '[object Array]'; - }, - /** - * Create an array of a certain length filled with a specific value. - */ - makeFilledArray: function (len, val) { - var array = []; - var i = 0; - while (i < len) { - array[i++] = val; - } - return array; - }, - /** - * Turn an integer into a "var_int". - * - * "var_int" is a variable length integer used by Bitcoin's binary format. - * - * Returns a byte array. - */ - numToVarInt: function (i) { - if (i < 0xfd) { - // unsigned char - return [i]; - } else if (i <= 1 << 16) { - // unsigned short (LE) - return [0xfd, i >>> 8, i & 255]; - } else if (i <= 1 << 32) { - // unsigned int (LE) - return [0xfe].concat(Crypto.util.wordsToBytes([i])); - } else { - // unsigned long long (LE) - return [0xff].concat(Crypto.util.wordsToBytes([i >>> 32, i])); - } - }, - /** - * Parse a Bitcoin value byte array, returning a BigInteger. - */ - valueToBigInt: function (valueBuffer) { - if (valueBuffer instanceof BigInteger) return valueBuffer; - - // Prepend zero byte to prevent interpretation as negative integer - return BigInteger.fromByteArrayUnsigned(valueBuffer); - }, - /** - * Format a Bitcoin value as a string. - * - * Takes a BigInteger or byte-array and returns that amount of Bitcoins in a - * nice standard formatting. - * - * Examples: - * 12.3555 - * 0.1234 - * 900.99998888 - * 34.00 - */ - formatValue: function (valueBuffer) { - var value = this.valueToBigInt(valueBuffer).toString(); - var integerPart = value.length > 8 ? value.substr(0, value.length - 8) : '0'; - var decimalPart = value.length > 8 ? value.substr(value.length - 8) : value; - while (decimalPart.length < 8) decimalPart = "0" + decimalPart; - decimalPart = decimalPart.replace(/0*$/, ''); - while (decimalPart.length < 2) decimalPart += "0"; - return integerPart + "." + decimalPart; - }, - /** - * Parse a floating point string as a Bitcoin value. - * - * Keep in mind that parsing user input is messy. You should always display - * the parsed value back to the user to make sure we understood his input - * correctly. - */ - parseValue: function (valueString) { - // TODO: Detect other number formats (e.g. comma as decimal separator) - var valueComp = valueString.split('.'); - var integralPart = valueComp[0]; - var fractionalPart = valueComp[1] || "0"; - while (fractionalPart.length < 8) fractionalPart += "0"; - fractionalPart = fractionalPart.replace(/^0+/g, ''); - var value = BigInteger.valueOf(parseInt(integralPart)); - value = value.multiply(BigInteger.valueOf(100000000)); - value = value.add(BigInteger.valueOf(parseInt(fractionalPart))); - return value; - }, - /** - * Calculate RIPEMD160(SHA256(data)). - * - * Takes an arbitrary byte array as inputs and returns the hash as a byte - * array. - */ - sha256ripe160: function (data) { - return ripemd160(Crypto.SHA256(data, { asBytes: true }), { asBytes: true }); - }, - // double sha256 - dsha256: function (data) { - return Crypto.SHA256(Crypto.SHA256(data, { asBytes: true }), { asBytes: true }); - }, - // duck typing method - hasMethods: function(obj /*, method list as strings */){ - var i = 1, methodName; - while((methodName = arguments[i++])){ - if(typeof obj[methodName] != 'function') { - return false; - } - } - return true; + + /** + * Parse a compressed wallet import format private key contained in a string. + */ + ECKey.decodeCompressedWalletImportFormat = function (privStr) { + var bytes = Bitcoin.Base58.decode(privStr); + var hash = bytes.slice(0, 34); + var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true }); + if (checksum[0] != bytes[34] || + checksum[1] != bytes[35] || + checksum[2] != bytes[36] || + checksum[3] != bytes[37]) { + throw "Checksum validation failed!"; } + var version = hash.shift(); + if (version != ECKey.privateKeyPrefix) { + throw "Version " + version + " not supported!"; + } + hash.pop(); + return hash; }; + // 64 characters [0-9A-F] + ECKey.isHexFormat = function (key) { + key = key.toString(); + return /^[A-Fa-f0-9]{64}$/.test(key); + }; + + // 51 characters base58, always starts with a '5' + ECKey.isWalletImportFormat = function (key) { + key = key.toString(); + return (ECKey.privateKeyPrefix == 0x80) ? + (/^5[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{50}$/.test(key)) : + (/^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{50}$/.test(key)); + }; + + // 52 characters base58 + ECKey.isCompressedWalletImportFormat = function (key) { + key = key.toString(); + return (ECKey.privateKeyPrefix == 0x80) ? + (/^[LK][123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(key)) : + (/^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(key)); + }; + + // 44 characters + ECKey.isBase64Format = function (key) { + key = key.toString(); + return (/^[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789=+\/]{44}$/.test(key)); + }; + + // 99 characters, 1=1, if using dice convert 6 to 0 + ECKey.isBase6Format = function (key) { + key = key.toString(); + return (/^[012345]{99}$/.test(key)); + }; + + // 22, 26 or 30 characters, always starts with an 'S' + ECKey.isMiniFormat = function (key) { + key = key.toString(); + var validChars22 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21}$/.test(key); + var validChars26 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{25}$/.test(key); + var validChars30 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{29}$/.test(key); + var testBytes = Crypto.SHA256(key + "?", { asBytes: true }); + + return ((testBytes[0] === 0x00 || testBytes[0] === 0x01) && (validChars22 || validChars26 || validChars30)); + }; + + return ECKey; +})(); +//https://raw.github.com/bitcoinjs/bitcoinjs-lib/09e8c6e184d6501a0c2c59d73ca64db5c0d3eb95/src/util.js +// Bitcoin utility functions +Bitcoin.Util = { + /** + * Cross-browser compatibility version of Array.isArray. + */ + isArray: Array.isArray || function (o) { + return Object.prototype.toString.call(o) === '[object Array]'; + }, + /** + * Create an array of a certain length filled with a specific value. + */ + makeFilledArray: function (len, val) { + var array = []; + var i = 0; + while (i < len) { + array[i++] = val; + } + return array; + }, + /** + * Turn an integer into a "var_int". + * + * "var_int" is a variable length integer used by Bitcoin's binary format. + * + * Returns a byte array. + */ + numToVarInt: function (i) { + if (i < 0xfd) { + // unsigned char + return [i]; + } else if (i <= 1 << 16) { + // unsigned short (LE) + return [0xfd, i >>> 8, i & 255]; + } else if (i <= 1 << 32) { + // unsigned int (LE) + return [0xfe].concat(Crypto.util.wordsToBytes([i])); + } else { + // unsigned long long (LE) + return [0xff].concat(Crypto.util.wordsToBytes([i >>> 32, i])); + } + }, + /** + * Parse a Bitcoin value byte array, returning a BigInteger. + */ + valueToBigInt: function (valueBuffer) { + if (valueBuffer instanceof BigInteger) return valueBuffer; + + // Prepend zero byte to prevent interpretation as negative integer + return BigInteger.fromByteArrayUnsigned(valueBuffer); + }, + /** + * Format a Bitcoin value as a string. + * + * Takes a BigInteger or byte-array and returns that amount of Bitcoins in a + * nice standard formatting. + * + * Examples: + * 12.3555 + * 0.1234 + * 900.99998888 + * 34.00 + */ + formatValue: function (valueBuffer) { + var value = this.valueToBigInt(valueBuffer).toString(); + var integerPart = value.length > 8 ? value.substr(0, value.length - 8) : '0'; + var decimalPart = value.length > 8 ? value.substr(value.length - 8) : value; + while (decimalPart.length < 8) decimalPart = "0" + decimalPart; + decimalPart = decimalPart.replace(/0*$/, ''); + while (decimalPart.length < 2) decimalPart += "0"; + return integerPart + "." + decimalPart; + }, + /** + * Parse a floating point string as a Bitcoin value. + * + * Keep in mind that parsing user input is messy. You should always display + * the parsed value back to the user to make sure we understood his input + * correctly. + */ + parseValue: function (valueString) { + // TODO: Detect other number formats (e.g. comma as decimal separator) + var valueComp = valueString.split('.'); + var integralPart = valueComp[0]; + var fractionalPart = valueComp[1] || "0"; + while (fractionalPart.length < 8) fractionalPart += "0"; + fractionalPart = fractionalPart.replace(/^0+/g, ''); + var value = BigInteger.valueOf(parseInt(integralPart)); + value = value.multiply(BigInteger.valueOf(100000000)); + value = value.add(BigInteger.valueOf(parseInt(fractionalPart))); + return value; + }, + /** + * Calculate RIPEMD160(SHA256(data)). + * + * Takes an arbitrary byte array as inputs and returns the hash as a byte + * array. + */ + sha256ripe160: function (data) { + return ripemd160(Crypto.SHA256(data, { asBytes: true }), { asBytes: true }); + }, + // double sha256 + dsha256: function (data) { + return Crypto.SHA256(Crypto.SHA256(data, { asBytes: true }), { asBytes: true }); + }, + // duck typing method + hasMethods: function(obj /*, method list as strings */){ + var i = 1, methodName; + while((methodName = arguments[i++])){ + if(typeof obj[methodName] != 'function') { + return false; + } + } + return true; + } +}; + + + (function (ellipticCurveType) { + + //Defining Elliptic Encryption Object + var ellipticEncryption = window.ellipticCurveEncryption = function () {}; + + ellipticEncryption.rng = new SecureRandom(); + + + + ellipticEncryption.getCurveParameters = function (curveName) { + + //Default is secp256k1 + curveName = typeof curveName !== 'undefined' ? curveName : "secp256k1"; + + var c = EllipticCurve.getSECCurveByName(curveName); + var curveDetails = { + Q: "", + A: "", + B: "", + GX: "", + GY: "", + N: "" + }; + + curveDetails.Q = c.getCurve().getQ().toString(); + curveDetails.A = c.getCurve().getA().toBigInteger().toString(); + curveDetails.B = c.getCurve().getB().toBigInteger().toString(); + curveDetails.GX = c.getG().getX().toBigInteger().toString(); + curveDetails.GY = c.getG().getY().toBigInteger().toString(); + curveDetails.N = c.getN().toString(); + + return curveDetails; + + } + + ellipticEncryption.selectedCurve = ellipticEncryption.getCurveParameters(ellipticCurveType); + + + ellipticEncryption.get_curve = function () { + return new EllipticCurve.CurveFp(new BigInteger(this.selectedCurve.Q), + new BigInteger(this.selectedCurve.A), + new BigInteger(this.selectedCurve.B)); + } + + ellipticEncryption.get_G = function (curve) { + return new EllipticCurve.PointFp(curve, + curve.fromBigInteger(new BigInteger(this.selectedCurve.GX)), + curve.fromBigInteger(new BigInteger(this.selectedCurve.GY))); + } + + + ellipticEncryption.pick_rand = function () { + var n = new BigInteger(this.selectedCurve.N); + var n1 = n.subtract(BigInteger.ONE); + var r = new BigInteger(n.bitLength(), this.rng); + return r.mod(n1).add(BigInteger.ONE); + } + + + ellipticEncryption.senderRandom = function () { + var r = this.pick_rand(); + return r.toString(); + }; + + + + ellipticEncryption.receiverRandom = function () { + + //This is receivers private key. For now we will use random. CHANGE IT LATER + var r = this.pick_rand(); + return r.toString(); + } + + + + ellipticEncryption.senderPublicString = function (senderPrivateKey) { + + var senderKeyECData = {}; + + var curve = this.get_curve(); + var G = this.get_G(curve); + var a = new BigInteger(senderPrivateKey); + var P = G.multiply(a); + senderKeyECData.XValuePublicString = P.getX().toBigInteger().toString(); + senderKeyECData.YValuePublicString = P.getY().toBigInteger().toString(); + + return senderKeyECData; + } + + //In real life ellipticEncryption.receiverPublicString is the public key of the receiver. + //you don't have to run receiverRandom and the bottom function + ellipticEncryption.receiverPublicString = function (receiverPublicKey) { + + var receiverKeyECData = {}; + + var curve = this.get_curve(); + var G = this.get_G(curve); + var a = new BigInteger(receiverPublicKey); + var P = G.multiply(a); + receiverKeyECData.XValuePublicString = P.getX().toBigInteger().toString(); + receiverKeyECData.YValuePublicString = P.getY().toBigInteger().toString(); + + return receiverKeyECData; + } + + ellipticEncryption.senderSharedKeyDerivation = function (receiverPublicStringXValue, + receiverPublicStringYValue, senderPrivateKey) { + + var senderDerivedKey = {}; + var curve = this.get_curve(); + var P = new EllipticCurve.PointFp(curve, + curve.fromBigInteger(new BigInteger(receiverPublicStringXValue)), + curve.fromBigInteger(new BigInteger(receiverPublicStringYValue))); + var a = new BigInteger(senderPrivateKey); + var S = P.multiply(a); + + senderDerivedKey.XValue = S.getX().toBigInteger().toString(); + senderDerivedKey.YValue = S.getY().toBigInteger().toString(); + + return senderDerivedKey; + } + + + ellipticEncryption.receiverSharedKeyDerivation = function (senderPublicStringXValue, + senderPublicStringYValue, receiverPrivateKey) { + + var receiverDerivedKey = {}; + var curve = this.get_curve(); + var P = new EllipticCurve.PointFp(curve, + curve.fromBigInteger(new BigInteger(senderPublicStringXValue)), + curve.fromBigInteger(new BigInteger(senderPublicStringYValue))); + var a = new BigInteger(receiverPrivateKey); + var S = P.multiply(a); + + receiverDerivedKey.XValue = S.getX().toBigInteger().toString(); + receiverDerivedKey.YValue = S.getY().toBigInteger().toString(); + + return receiverDerivedKey; + } + + })("secp256k1"); + + // secrets.js - by Alexander Stetsyuk - released under MIT License (function (exports, global) { var defaults = { From 1301caaa40b1b955d6f5d0ff39ab7700d7f149b6 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 5 Jan 2020 20:00:02 +0530 Subject: [PATCH 036/289] adding a dummy floID as adminID --- standard_Operations.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/standard_Operations.html b/standard_Operations.html index 64ab216..473c9af 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -16,7 +16,7 @@ FLO: ['https://explorer.mediciland.com/', 'https://livenet.flocha.in/', 'https://flosight.duckdns.org/', 'http://livenet-explorer.floexperiments.com/'], FLO_TEST: ['https://testnet-flosight.duckdns.org/', 'https://testnet.flocha.in/'] }, - adminID: "oTZw3ydCRKDhcYC5Bp6mRJMGTTVv9JHtg8", + adminID: "FMeiptdJNtYQEtzyYAVNP8fjsDJ1i4EPfE", sendAmt: 0.001, fee: 0.0005, From 2b847b7a4e80c03cfcdbfa283e7ecb78f935328f Mon Sep 17 00:00:00 2001 From: Sai Raj <39055732+sairajzero@users.noreply.github.com> Date: Sun, 5 Jan 2020 20:13:53 +0530 Subject: [PATCH 037/289] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 17fb054..04a52f2 100644 --- a/README.md +++ b/README.md @@ -73,8 +73,8 @@ This template contains standard operations that can be used for the following: 2. privateKey - private key of the signer #### Verify Signature - floCrypto.decryptData(data, signature, publicKey) -`decryptData` verifies signatue of the data using public-key + floCrypto.verifySign(data, signature, publicKey) +`verifySign` verifies signatue of the data using public-key 1. data - data of the given signature 2. signature - signature of the data 3. publicKey - public key of the signer From 73965d87fc2cf70c60ca12a8562965e1a12af8e9 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 5 Jan 2020 20:40:53 +0530 Subject: [PATCH 038/289] adding event listner to startup functions startUpSuccessLog and startUpSuccessLog Events are registered to log the start up functions --- standard_Operations.html | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/standard_Operations.html b/standard_Operations.html index 473c9af..a8b887e 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -7206,7 +7206,7 @@ Bitcoin.Util = { privKey: key.getBitcoinWalletImportFormat() } } catch (e) { - console.log(e); + console.error(e); } }, @@ -7243,7 +7243,7 @@ Bitcoin.Util = { else return false; } catch (e) { - console.log(e); + console.error(e); } }, @@ -8625,11 +8625,11 @@ Bitcoin.Util = { return new Promise((resolve, reject) => { this.startUpFunctions[fname]().then(result => { this.callStartUpFunction.completed += 1 - console.log(`${result}\nCompleted ${this.callStartUpFunction.completed}/${this.callStartUpFunction.total} Startup functions`) + reactor.dispatchEvent("startUpSuccessLog",`${result}\nCompleted ${this.callStartUpFunction.completed}/${this.callStartUpFunction.total} Startup functions`) resolve(true) }).catch(error => { this.callStartUpFunction.failed += 1 - console.error(`${error}\nFailed ${this.callStartUpFunction.failed}/${this.callStartUpFunction.total} Startup functions`) + reactor.dispatchEvent("startUpErrorLog",`${error}\nFailed ${this.callStartUpFunction.failed}/${this.callStartUpFunction.total} Startup functions`) reject(false) }) }) @@ -8699,6 +8699,12 @@ Bitcoin.Util = { } } + reactor.registerEvent("startUpSuccessLog"); + reactor.addEventListener("startUpSuccessLog", log => console.log(log)) + + reactor.registerEvent("startUpSuccessLog"); + reactor.addEventListener("startUpErrorLog", log => console.error(log)) + function onLoadStartUp() { //addStartUpFunction('Sample', Promised Function) From efbb6fa9e299a5667b38ef3f11c8e5c61e08a0ce Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 5 Jan 2020 20:44:09 +0530 Subject: [PATCH 039/289] bug fix --- standard_Operations.html | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/standard_Operations.html b/standard_Operations.html index a8b887e..7e85968 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -8447,6 +8447,7 @@ Bitcoin.Util = { } From 2bf166ffd16765a9553b42c47bc2e73cc3df4367 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 31 Jan 2020 20:22:35 +0530 Subject: [PATCH 043/289] bug fix: floSupernode module --- standard_Operations.html | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/standard_Operations.html b/standard_Operations.html index e073766..1a2a1e1 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -7638,16 +7638,17 @@ Bitcoin.Util = { sendDataToSN(data, snfloID){ return new Promise((resolve, reject) => { - console.log(snfloID) var websocket = new WebSocket("wss://" + floGlobals.supernodes[snfloID].uri + "/ws"); websocket.onmessage = (evt => { if(evt.data == '$+'){ websocket.send(data); resolve(`Data sent to supernode : ${snfloID}`); }else if(evt.data == '$-'){ - this.kBucket.getNextSupernode(snfloID) - .then(nextNode => this.sendDataToSN(data, nextNode[0])) - .catch(error => reject(error)) + this.kBucket.getNextSupernode(snfloID).then(nextNode => { + this.sendDataToSN(data, nextNode[0]) + .then(result => resolve(result)) + .catch(error => reject(error)) + }).catch(error => reject(error)) }else{ console.log(evt.data) reject(evt.data) @@ -7655,9 +7656,11 @@ Bitcoin.Util = { websocket.close(); }) websocket.onerror = (evt) => { - this.kBucket.getNextSupernode(snfloID) - .then(nextNode => this.sendDataToSN(data, nextNode[0])) - .catch(error => reject(error)) + this.kBucket.getNextSupernode(snfloID).then(nextNode => { + this.sendDataToSN(data, nextNode[0]) + .then(result => resolve(result)) + .catch(error => reject(error)) + }).catch(error => reject(error)) }; }) }, @@ -7682,9 +7685,11 @@ Bitcoin.Util = { if(evt.data == '$+'){ websocket.send(`?${request}`); }else if(evt.data == '$-'){ - this.kBucket.getNextSupernode(snfloID) - .then(nextNode => this.requestDataFromSN(request, nextNode[0])) - .catch(error => reject(error)) + this.kBucket.getNextSupernode(snfloID).then(nextNode => { + this.requestDataFromSN(request, nextNode[0]) + .then(result => resolve(result)) + .catch(error => reject(error)) + }).catch(error => reject(error)) websocket.close() }else{ resolve(evt.data); @@ -7692,9 +7697,11 @@ Bitcoin.Util = { } }) websocket.onerror = (evt) => { - this.kBucket.getNextSupernode(snfloID) - .then(nextNode => this.requestDataFromSN(request, nextNode[0])) - .catch(error => reject(error)) + this.kBucket.getNextSupernode(snfloID).then(nextNode => { + this.requestDataFromSN(request, nextNode[0]) + .then(result => resolve(result)) + .catch(error => reject(error)) + }).catch(error => reject(error)) }; }) }, From cdeab33c2018d693442f4c290fa61e7ad879d43a Mon Sep 17 00:00:00 2001 From: sairajzero Date: Mon, 3 Feb 2020 18:43:29 +0530 Subject: [PATCH 044/289] Login as guest feature Entering a empty string for private Key now automatically generated a random key and logins as guest --- standard_Operations.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/standard_Operations.html b/standard_Operations.html index 1a2a1e1..d3470db 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -8600,7 +8600,7 @@ Bitcoin.Util = { try{ var privKey = floDapps.util.privKeyInput(); if(!privKey) - return reject("Empty Private Key") + privKey = floCrypto.generateNewID().privKey var floID = floCrypto.getFloIDfromPubkeyHex(floCrypto.getPubKeyHex(privKey)) console.log(floID) }catch(error){ From 7a6a2dc9ea6e0589408db45096d36f4c20a7ff62 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 6 Feb 2020 13:38:09 +0530 Subject: [PATCH 045/289] Custom privKeyInput is made promisified privKeyInput now uses given key when resolved and generates random key when rejected --- standard_Operations.html | 57 ++++++++++++++++++++++++---------------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/standard_Operations.html b/standard_Operations.html index d3470db..3652b9d 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -8490,8 +8490,13 @@ Bitcoin.Util = { }, privKeyInput: function(){ - var privKey = prompt("Enter Private Key: ") - return privKey + return new Promise((resolve, reject) => { + var privKey = prompt("Enter Private Key: ") + if(privKey === null) + reject(null) + else + resolve(privKey) + }) }, startUpFunctions:{ @@ -8597,27 +8602,33 @@ Bitcoin.Util = { .then(result => resolve(result)) .catch(error => reject(error)) }else{ - try{ - var privKey = floDapps.util.privKeyInput(); - if(!privKey) - privKey = floCrypto.generateNewID().privKey - var floID = floCrypto.getFloIDfromPubkeyHex(floCrypto.getPubKeyHex(privKey)) - console.log(floID) - }catch(error){ - console.error(error) - return reject("Invalid Private Key") - } - var threshold = floCrypto.randInt(10,20) - writeSharesToIDB(floCrypto.createShamirsSecretShares(privKey, threshold, threshold)).then(resultIndexes =>{ - //store index keys in localStorage - localStorage.setItem(`${floGlobals.application}#privKey`, JSON.stringify(resultIndexes)) - //also add a dummy privatekey to the IDB - var randomPrivKey = floCrypto.generateNewID().privKey - var randomThreshold = floCrypto.randInt(10,20) - writeSharesToIDB(floCrypto.createShamirsSecretShares(randomPrivKey, randomThreshold, randomThreshold)) - //resolve private Key - resolve(privKey) - }).catch(error => reject(error)) + var privKey; + floDapps.util.privKeyInput().then(result => { + try{ + if(!result) + return reject("Empty Private Key") + var floID = floCrypto.getFloIDfromPubkeyHex(floCrypto.getPubKeyHex(result)) + console.log(floID) + }catch(error){ + console.error(error) + return reject("Invalid Private Key") + } + }).catch(error => { + console.log(error, "Generating Random Keys") + privKey = floCrypto.generateNewID().privKey + }).finally(_ => { + var threshold = floCrypto.randInt(10,20) + writeSharesToIDB(floCrypto.createShamirsSecretShares(privKey, threshold, threshold)).then(resultIndexes =>{ + //store index keys in localStorage + localStorage.setItem(`${floGlobals.application}#privKey`, JSON.stringify(resultIndexes)) + //also add a dummy privatekey to the IDB + var randomPrivKey = floCrypto.generateNewID().privKey + var randomThreshold = floCrypto.randInt(10,20) + writeSharesToIDB(floCrypto.createShamirsSecretShares(randomPrivKey, randomThreshold, randomThreshold)) + //resolve private Key + resolve(privKey) + }).catch(error => reject(error)) + }) } }) } From c3a51f44a7c9ad38476fbb4d6443a7cd54b409ed Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 6 Feb 2020 14:56:12 +0530 Subject: [PATCH 046/289] bug fix --- standard_Operations.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/standard_Operations.html b/standard_Operations.html index 3652b9d..07725d5 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -8608,7 +8608,7 @@ Bitcoin.Util = { if(!result) return reject("Empty Private Key") var floID = floCrypto.getFloIDfromPubkeyHex(floCrypto.getPubKeyHex(result)) - console.log(floID) + privKey = result }catch(error){ console.error(error) return reject("Invalid Private Key") From 86ea714139df968911e9424740013e3f2df3480d Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 16 Feb 2020 02:34:58 +0530 Subject: [PATCH 047/289] adding manage subAdmin to floDapps floDapps.manageSubAdmins() allows the user to add and/or remove subadmin list via blockchain *Requires Admin Privatekey of the app --- standard_Operations.html | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/standard_Operations.html b/standard_Operations.html index 07725d5..54c8909 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -8696,6 +8696,26 @@ Bitcoin.Util = { this.util.appObs = appObs }, + manageSubAdmins(adminPrivKey, addList, rmList){ + return new Promise((resolve, reject) => { + if(!Array.isArray(addList)) addList = undefined; + if(!Array.isArray(rmList)) rmList = undefined; + var floData = { + [floGlobals.application] : { + addSubAdmin : addList, + removeSubAdmin: rmList, + } + } + var floID = floCrypto.getFloIDfromPubkeyHex(floCrypto.getPubKeyHex(adminPrivKey)) + if(floID != floGlobals.adminID) + reject('Access Denied for Admin privilege') + else + floBlockchainAPI.writeData(floID, JSON.stringify(floData), adminPrivKey) + .then(result => resolve(['Updated SubAdmin List', result])) + .catch(error => reject(error)) + }) + }, + clearCredentials: function(){ var indexArr = localStorage.getItem(`${floGlobals.application}#privKey`) if(!indexArr) From d6c4b4882e3b1b7b32962941f55b713198dca53a Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 16 Feb 2020 02:36:35 +0530 Subject: [PATCH 048/289] changing TEST_MODE adminID --- standard_Operations.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/standard_Operations.html b/standard_Operations.html index 54c8909..96b1fe7 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -16,7 +16,7 @@ FLO: ['https://explorer.mediciland.com/', 'https://livenet.flocha.in/', 'https://flosight.duckdns.org/', 'http://livenet-explorer.floexperiments.com/'], FLO_TEST: ['https://testnet-flosight.duckdns.org/', 'https://testnet.flocha.in/'] }, - adminID: "FMeiptdJNtYQEtzyYAVNP8fjsDJ1i4EPfE", + adminID: "FKAEdnPfjXLHSYwrXQu377ugN4tXU7VGdf", sendAmt: 0.001, fee: 0.0005, From 47ca6a802e6c6ecf6eab04cb92f542d30469f544 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 16 Feb 2020 02:38:51 +0530 Subject: [PATCH 049/289] moving onloadStartup to a seperate script tag --- standard_Operations.html | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/standard_Operations.html b/standard_Operations.html index 96b1fe7..b89f82c 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -8752,7 +8752,8 @@ Bitcoin.Util = { reactor.registerEvent("startUpErrorLog"); reactor.addEventListener("startUpErrorLog", log => console.error(log)) - + + @@ -7017,1342 +7019,1373 @@ Bitcoin.Util = { @@ -4932,12 +4931,12 @@ if (typeof Crypto == "undefined" || !Crypto.util) { floDataCount = this.floData.length; //flochange -- creating unique data character count logic for floData. This string is prefixed before actual floData string in Raw Transaction - if (floDataCount <= 16) { + if (floDataCount < 16) { floDataCountString = floDataCount.toString(16); floDataCountString = "0"+ floDataCountString; } else if (floDataCount < 253) { floDataCountString = floDataCount.toString(16); - } else if (floDataCount <= 1023) { + } else if (floDataCount <= 1040) { floDataCountAdjusted = (floDataCount - 253) + parseInt("0xfd00fd"); floDataCountStringAdjusted = floDataCountAdjusted.toString(16); floDataCountString = floDataCountStringAdjusted.substr(0,2)+ floDataCountStringAdjusted.substr(4,2)+ floDataCountStringAdjusted.substr(2,2); @@ -6739,27 +6738,22 @@ Bitcoin.Util = { addedDiff(original, updatedObj) returns only the values added to the updated object deletedDiff(original, updatedObj) returns only the values deleted in the updated object updatedDiff(original, updatedObj) returns only the values that have been changed in the updated object - findDifference(original, updatedObj) returns an object with the added, deleted and updated differences - mergeRecurcive(original, diff) this will get you a new object that will merge all the changes between the old object and the new object + findDiff(original, updatedObj) returns an object with the added, deleted and updated differences + mergeRecursive(original, diff) returns a new object that will merge difference to old object + mergeDiff(original, allDiff) returns a new object from original object merged with all differences (allDiff is returned object of findDiff) */ (function(){ const isDate = d => d instanceof Date; const isEmpty = o => Object.keys(o).length === 0; const isObject = o => o != null && typeof o === 'object'; - const properObject = o => isObject(o) && !o.hasOwnProperty ? { ...o } : o; - - + const properObject = o => isObject(o) && !o.hasOwnProperty ? { ...o } : o; const getLargerArray = (l, r) => l.length > r.length ? l : r; - + const preserve = (diff, left, right) => { - if (!isObject(diff)) return diff; - return Object.keys(diff).reduce((acc, key) => { - const leftArray = left[key]; const rightArray = right[key]; - if (Array.isArray(leftArray) && Array.isArray(rightArray)) { const array = [...getLargerArray(leftArray, rightArray)]; return { @@ -6769,13 +6763,11 @@ Bitcoin.Util = { acc2[index] = preserve(diff[key][index], leftArray[index], rightArray[index]); // diff recurse and check for nested arrays return acc2; } - delete acc2[index]; // no diff aka empty return acc2; }, array) }; } - return { ...acc, [key]: diff[key] @@ -6783,31 +6775,21 @@ Bitcoin.Util = { }, {}); }; - const updatedDiff = (lhs, rhs) => { - if (lhs === rhs) return {}; - if (!isObject(lhs) || !isObject(rhs)) return rhs; - const l = properObject(lhs); const r = properObject(rhs); - if (isDate(l) || isDate(r)) { if (l.valueOf() == r.valueOf()) return {}; return r; } - return Object.keys(r).reduce((acc, key) => { - if (l.hasOwnProperty(key)) { const difference = updatedDiff(l[key], r[key]); - if (isObject(difference) && isEmpty(difference) && !isDate(difference)) return acc; - return { ...acc, [key]: difference }; } - return acc; }, {}); }; @@ -6815,123 +6797,90 @@ Bitcoin.Util = { const diff = (lhs, rhs) => { if (lhs === rhs) return {}; // equal return no diff - if (!isObject(lhs) || !isObject(rhs)) return rhs; // return updated rhs - const l = properObject(lhs); const r = properObject(rhs); - const deletedValues = Object.keys(l).reduce((acc, key) => { return r.hasOwnProperty(key) ? acc : { ...acc, [key]: null }; }, {}); - if (isDate(l) || isDate(r)) { if (l.valueOf() == r.valueOf()) return {}; return r; } - return Object.keys(r).reduce((acc, key) => { if (!l.hasOwnProperty(key)) return { ...acc, [key]: r[key] }; // return added r key - const difference = diff(l[key], r[key]); - if (isObject(difference) && isEmpty(difference) && !isDate(difference)) return acc; // return no diff - return { ...acc, [key]: difference }; // return updated key }, deletedValues); }; const addedDiff = (lhs, rhs) => { - if (lhs === rhs || !isObject(lhs) || !isObject(rhs)) return {}; - const l = properObject(lhs); const r = properObject(rhs); - return Object.keys(r).reduce((acc, key) => { if (l.hasOwnProperty(key)) { const difference = addedDiff(l[key], r[key]); - if (isObject(difference) && isEmpty(difference)) return acc; - return { ...acc, [key]: difference }; } - return { ...acc, [key]: r[key] }; }, {}); }; - const arrayDiff = (lhs, rhs) => { if (lhs === rhs) return {}; // equal return no diff - if (!isObject(lhs) || !isObject(rhs)) return rhs; // return updated rhs - const l = properObject(lhs); const r = properObject(rhs); - const deletedValues = Object.keys(l).reduce((acc, key) => { return r.hasOwnProperty(key) ? acc : { ...acc, [key]: null }; }, {}); - if (isDate(l) || isDate(r)) { if (l.valueOf() == r.valueOf()) return {}; return r; } - if (Array.isArray(r) && Array.isArray(l)) { const deletedValues = l.reduce((acc, item, index) => { return r.hasOwnProperty(index) ? acc.concat(item) : acc.concat(null); }, []); - return r.reduce((acc, rightItem, index) => { if (!deletedValues.hasOwnProperty(index)) { return acc.concat(rightItem); } - const leftItem = l[index]; const difference = diff(rightItem, leftItem); - if (isObject(difference) && isEmpty(difference) && !isDate(difference)) { delete acc[index]; return acc; // return no diff } - return acc.slice(0, index).concat(rightItem).concat(acc.slice(index + 1)); // return updated key }, deletedValues); } return Object.keys(r).reduce((acc, key) => { if (!l.hasOwnProperty(key)) return { ...acc, [key]: r[key] }; // return added r key - const difference = diff(l[key], r[key]); - if (isObject(difference) && isEmpty(difference) && !isDate(difference)) return acc; // return no diff - return { ...acc, [key]: difference }; // return updated key }, deletedValues); }; const deletedDiff = (lhs, rhs) => { if (lhs === rhs || !isObject(lhs) || !isObject(rhs)) return {}; - const l = properObject(lhs); const r = properObject(rhs); - return Object.keys(l).reduce((acc, key) => { if (r.hasOwnProperty(key)) { const difference = deletedDiff(l[key], r[key]); - if (isObject(difference) && isEmpty(difference)) return acc; - return { ...acc, [key]: difference }; } - return { ...acc, [key]: null }; }, {}); }; - - window.findDifference = (lhs, rhs) => ({ + window.findDiff = (lhs, rhs) => ({ added: addedDiff(lhs, rhs), deleted: deletedDiff(lhs, rhs), updated: updatedDiff(lhs, rhs), @@ -6940,22 +6889,17 @@ Bitcoin.Util = { const mergeRecursive = (obj1, obj2) => { for (var p in obj2) { try { - if(obj2[p].constructor == Object) { + if(obj2[p].constructor == Object) obj1[p] = mergeRecursive(obj1[p], obj2[p]); - } // Property in destination object set; update its value. else if (Ext.isArray(obj2[p])) { // obj1[p] = []; - if (obj2[p].length < 1) { + if (obj2[p].length < 1) obj1[p] = obj2[p]; - } - else { + else obj1[p] = mergeRecursive(obj1[p], obj2[p]); - } - - }else{ + }else obj1[p] = obj2[p]; - } } catch (e) { // Property in destination object not set; create it and set its value. obj1[p] = obj2[p]; @@ -6964,19 +6908,6 @@ Bitcoin.Util = { return obj1; } - /* - var test = { - foo : { - bar : { - baz : null - } - }, - bar : 1 - }; - cleanse(test); - - Rohit: Added a small fix for object being entered as Array*/ - const cleanse = (obj) => { Object.keys(obj).forEach(key => { var value = obj[key]; @@ -6984,34 +6915,28 @@ Bitcoin.Util = { // Recurse... cleanse(value); // ...and remove if now "empty" (NOTE: insert your definition of "empty" here) - if (!Object.keys(value).length) { - delete obj[key] - } - } - else if (value === null) { - // null, remove it - delete obj[key]; - + //if (!Object.keys(value).length) + // delete obj[key]; } + else if (value === null) + delete obj[key];// null, remove it }); - - if(obj.constructor.toString().indexOf("Array") != -1) {obj = obj.filter(function (el) { - return el != null; - });} - - return obj; + if(obj.constructor.toString().indexOf("Array") != -1) {obj = obj.filter(function (el) { + return el != null; + });} + return obj; } - /*obj is original object or array, diff is the output of findDifference */ - window.mergeDifference = (obj,diff) => { + /*obj is original object or array, diff is the output of findDiff */ + window.mergeDiff = (obj, diff) => { if(Object.keys(diff.updated).length !== 0) - obj = mergeRecursive(obj,diff.updated) + obj = mergeRecursive(obj, diff.updated) if(Object.keys(diff.deleted).length !== 0){ - obj = mergeRecursive(obj,diff.deleted) + obj = mergeRecursive(obj, diff.deleted) obj = cleanse(obj) } if(Object.keys(diff.added).length !== 0) - obj = mergeRecursive(obj,diff.added) + obj = mergeRecursive(obj, diff.added) return obj } })(); @@ -7125,7 +7050,7 @@ Bitcoin.Util = { }, //generate a random String within length (options : alphaNumeric chars only) - randString: function (length, alphaNumeric = false) { + randString: function (length, alphaNumeric = true) { var result = ''; if (alphaNumeric) var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; @@ -7217,22 +7142,24 @@ Bitcoin.Util = { //Returns public-key from private-key getPubKeyHex: function (privateKeyHex) { - if(!privateKeyHex) + if (!privateKeyHex) return null; var key = new Bitcoin.ECKey(privateKeyHex); - if (key.priv == null) + if (key.priv == null) return null; key.setCompressed(true); - var pubkeyHex = key.getPubKeyHex(); - return pubkeyHex; + return key.getPubKeyHex(); }, - //Returns flo-ID from public-key - getFloIDfromPubkeyHex: function (pubkeyHex) { + //Returns flo-ID from public-key or private-key + getFloID: function (keyHex) { + if (!keyHex) + return null; try { - var key = new Bitcoin.ECKey().setPub(pubkeyHex); - var floID = key.getBitcoinAddress(); - return floID; + var key = new Bitcoin.ECKey(keyHex); + if (key.priv == null) + key.setPub(keyHex); + return key.getBitcoinAddress(); } catch (e) { return null; } @@ -7240,6 +7167,8 @@ Bitcoin.Util = { //Verify the private-key for the given public-key or flo-ID verifyPrivKey: function (privateKeyHex, pubKey_floID, isfloID = true) { + if (!privateKeyHex || !pubKey_floID) + return false; try { var key = new Bitcoin.ECKey(privateKeyHex); if (key.priv == null) @@ -7258,6 +7187,8 @@ Bitcoin.Util = { //Check if the given Address is valid or not validateAddr: function (inpAddr) { + if (!inpAddr) + return false; try { var addr = new Bitcoin.Address(inpAddr); return true; @@ -7502,8 +7433,7 @@ Bitcoin.Util = { if (!key) invalids.InvalidSenderPrivKeys.push(key); else { - let floID = floCrypto.getFloIDfromPubkeyHex(floCrypto - .getPubKeyHex(key)); + let floID = floCrypto.getFloID(key); senders[floID] = { wif: key } @@ -7522,12 +7452,11 @@ Bitcoin.Util = { invalids.InvalidSenderPrivKeys.push(key); else { if (typeof senderPrivKeys[key] !== 'number' || senderPrivKeys[ - key] <= 0) + key] <= 0) invalids.InvalidSenderAmountFor.push(key) else inputVal += senderPrivKeys[key]; - let floID = floCrypto.getFloIDfromPubkeyHex(floCrypto.getPubKeyHex( - key)); + let floID = floCrypto.getFloID(key); senders[floID] = { wif: key, coins: senderPrivKeys[key] @@ -7738,643 +7667,6 @@ Bitcoin.Util = { } } - - - - - - - - - - - + @@ -9312,19 +9325,5 @@ Bitcoin.Util = { } } - From b5532444fb47e0d5c2d9040a22ed23204a89d22f Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sat, 2 Jan 2021 19:11:15 +0530 Subject: [PATCH 133/289] floCloudAPI_v2.0.2d | floDapps_v2.0.1b floCloudAPI_v2.0.2d - Fixed bug: syntax error in requestObjectData - Added closeRequest: closes the active live requests floDapps_v2.0.1b - minor improvements and alignment. - Fixed: deleteAppData deletes the lastTx data of the adminID. --- standard_Operations.html | 347 +++++++++++++++++++-------------------- 1 file changed, 165 insertions(+), 182 deletions(-) diff --git a/standard_Operations.html b/standard_Operations.html index 519f53d..1491c7c 100644 --- a/standard_Operations.html +++ b/standard_Operations.html @@ -38,7 +38,7 @@ //floDapps.addStartUpFunction('Sample', Promised Function) //floDapps.setAppObjectStores({sampleObs1:{}, sampleObs2:{options{autoIncrement:true, keyPath:'SampleKey'}, Indexes:{sampleIndex:{}}}}) - //floDapps.setCustomPrivKeyInput( () => { FUNCTION BODY *must return private key* } ) + //floDapps.setCustomPrivKeyInput( () => { FUNCTION BODY *must resolve private key* } ) floDapps.launchStartUp().then(result => { console.log(result) @@ -7925,7 +7925,7 @@ Bitcoin.Util = { } } - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + floDapps.launchStartUp().then(result => { + console.log(result) + alert(`Welcome FLO_ID: ${myFloID}`) + //App functions.... + }).catch(error => console.error(error)) + } + TEST_MODE - (use console) - - - - - - - - + (use console) - + + \ No newline at end of file From f27c8c4f0313ec95394dca2a3a9e10b43bf27017 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 31 Mar 2022 21:54:51 +0530 Subject: [PATCH 185/289] Bug fixes - Renamed standard_Operations.html to index.html - Fixed some minor bugs in floCloudAPI - Added: floCrypto.validateFloID (alias for floCrypto.validateAddr) --- floCloudAPI.js | 15 ++++++++------- floCrypto.js | 4 ++-- standard_Operations.html => index.html | 0 3 files changed, 10 insertions(+), 9 deletions(-) rename standard_Operations.html => index.html (100%) diff --git a/floCloudAPI.js b/floCloudAPI.js index 4f3777a..3758337 100644 --- a/floCloudAPI.js +++ b/floCloudAPI.js @@ -1,9 +1,9 @@ -(function(EXPORTS) { //floCloudAPI v2.2.0 +(function(EXPORTS) { //floCloudAPI v2.2.0a /* FLO Cloud operations to send/request application data*/ 'use strict'; const floCloudAPI = EXPORTS; - var Kbucket; + var kBucket; const K_Bucket = floCloudAPI.K_Bucket = function(masterID, nodeList) { const decodeID = floID => { @@ -102,7 +102,7 @@ return new Promise((resolve, reject) => { try { nodeList = nodeList || Object.keys(floGlobals.supernodes); - Kbucket = new K_Bucket(SNStorageID, nodeList); + kBucket = new K_Bucket(SNStorageID, nodeList); resolve('Cloud init successful'); } catch (error) { reject(error); @@ -110,8 +110,8 @@ }) } - Object.defineProperty(floCloudAPI, 'Kbucket', { - get: () => Kbucket + Object.defineProperty(floCloudAPI, 'kBucket', { + get: () => kBucket }); const _inactive = new Set(); @@ -252,7 +252,8 @@ let randID = floCrypto.randString(5); node.send(JSON.stringify(request)); node.onmessage = (evt) => { - let d = e = null; + let d = null, + e = null; try { d = filterData(JSON.parse(evt.data)); } catch (error) { @@ -314,7 +315,7 @@ break; case "UPDATE": if (dataSet[vc].message.diff) - floGlobals.appObjects[objectName] = mergeDiff(floGlobals.appObjects[objectName], dataSet[vc].message.diff); + floGlobals.appObjects[objectName] = diff.merge(floGlobals.appObjects[objectName], dataSet[vc].message.diff); } floGlobals.lastVC[objectName] = vc; } diff --git a/floCrypto.js b/floCrypto.js index 96d38ca..4ab4d5c 100644 --- a/floCrypto.js +++ b/floCrypto.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCrypto v2.3.0 +(function(EXPORTS) { //floCrypto v2.3.0a /* FLO Crypto Operators */ 'use strict'; const floCrypto = EXPORTS; @@ -203,7 +203,7 @@ } //Check if the given Address is valid or not - floCrypto.validateAddr = function(inpAddr) { + floCrypto.validateFloID = floCrypto.validateAddr = function(inpAddr) { if (!inpAddr) return false; try { diff --git a/standard_Operations.html b/index.html similarity index 100% rename from standard_Operations.html rename to index.html From 5bb0ee85886fb832d107124a0ca69c15ec9d375f Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 31 Mar 2022 22:25:22 +0530 Subject: [PATCH 186/289] Update lib.js - Added require-support for BuildKBucket - BuildKBucket now works with and without `new` - Renamed instance name to KBucket --- lib.js | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/lib.js b/lib.js index 8eb3710..8d53321 100644 --- a/lib.js +++ b/lib.js @@ -1,5 +1,4 @@ -//lib v1.2.1 -(function(GLOBAL) { +(function(GLOBAL) { //lib v1.2.2 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -6590,10 +6589,22 @@ //kbucket.js (function() { + const getRandomValues = function(buf) { + if (typeof require === 'function') { + var bytes = require('crypto').randomBytes(buf.length); + buf.set(bytes) + return buf; + } else if (GLOBAL.crypto && GLOBAL.crypto.getRandomValues) + return GLOBAL.crypto.getRandomValues(buf); + else + return null; + } // Kademlia DHT K-bucket implementation as a binary tree. // by 'Tristan Slominski' under 'MIT License' - GLOBAL.BuildKBucket = function BuildKBucket(options = {}) { - this.localNodeId = options.localNodeId || window.crypto.getRandomValues(new Uint8Array(20)) + GLOBAL.BuildKBucket = function KBucket(options = {}) { + if (!(this instanceof KBucket)) + return new KBucket(options); + this.localNodeId = options.localNodeId || getRandomValues(new Uint8Array(20)) this.numberOfNodesPerKBucket = options.numberOfNodesPerKBucket || 20 this.numberOfNodesToPing = options.numberOfNodesToPing || 3 this.distance = options.distance || this.distance From 4b7f6184a3edd3259de08d6a46f8b4f8fa3abec5 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sat, 2 Apr 2022 02:06:44 +0530 Subject: [PATCH 187/289] Bug fix: floDapps - Fixed: setCustomPrivKeyInput not working - Added semicolon at the end of all stdop files --- compactIDB.js | 2 +- floCloudAPI.js | 2 +- floDapps.js | 27 +++++++++++++-------------- 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/compactIDB.js b/compactIDB.js index ab4c3c0..624db0a 100644 --- a/compactIDB.js +++ b/compactIDB.js @@ -256,4 +256,4 @@ } -})(window.compactIDB = {}) \ No newline at end of file +})(window.compactIDB = {}); \ No newline at end of file diff --git a/floCloudAPI.js b/floCloudAPI.js index 3758337..512c8ae 100644 --- a/floCloudAPI.js +++ b/floCloudAPI.js @@ -917,4 +917,4 @@ })(); -})('object' === typeof module ? module.exports : window.floCloudAPI = {}) \ No newline at end of file +})('object' === typeof module ? module.exports : window.floCloudAPI = {}); \ No newline at end of file diff --git a/floDapps.js b/floDapps.js index 18d818d..6e3ecbd 100644 --- a/floDapps.js +++ b/floDapps.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floDapps v2.2.0 +(function(EXPORTS) { //floDapps v2.2.0a /* General functions for FLO Dapps*/ //'use strict'; const floDapps = EXPORTS; @@ -146,16 +146,15 @@ }) }); - function getCredentials() { + var keyInput = type => new Promise((resolve, reject) => { + let inputVal = prompt(`Enter ${type}: `) + if (inputVal === null) + reject(null) + else + resolve(inputVal) + }); - const inputFn = getCredentials.privKeyInput || - (type => new Promise((resolve, reject) => { - let inputVal = prompt(`Enter ${type}: `) - if (inputVal === null) - reject(null) - else - resolve(inputVal) - })); + function getCredentials() { const readSharesFromIDB = indexArr => new Promise((resolve, reject) => { var promises = [] @@ -195,7 +194,7 @@ .catch(error => reject(error)) } else { var privKey; - inputFn("PRIVATE_KEY").then(result => { + keyInput("PRIVATE_KEY").then(result => { if (!result) return reject("Empty Private Key") var floID = floCrypto.getFloID(result) @@ -229,7 +228,7 @@ if (key.length == 52) resolve(key) else { - inputFn("PIN/Password").then(pwd => { + keyInput("PIN/Password").then(pwd => { try { let privKey = Crypto.AES.decrypt(key, pwd); resolve(privKey) @@ -327,7 +326,7 @@ floDapps.setCustomStartupLogger = fn => fn instanceof Function ? startUpLog = fn : false; - floDapps.setCustomPrivKeyInput = fn => fn instanceof Function ? customFn = fn : false; + floDapps.setCustomPrivKeyInput = fn => fn instanceof Function ? keyInput = fn : false; floDapps.setAppObjectStores = appObs => initIndexedDB.appObs = appObs; @@ -600,4 +599,4 @@ .catch(error => reject(error)) }).catch(error => reject(error)) }); -})('object' === typeof module ? module.exports : window.floDapps = {}) \ No newline at end of file +})('object' === typeof module ? module.exports : window.floDapps = {}); \ No newline at end of file From ca243bf0e40b5e3937a1c4c786f3b2f9c24d93ad Mon Sep 17 00:00:00 2001 From: Sai Raj <39055732+sairajzero@users.noreply.github.com> Date: Sun, 3 Apr 2022 19:40:01 +0530 Subject: [PATCH 188/289] Update lib.js Adding default cryptocoin as FLO --- lib.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib.js b/lib.js index 8d53321..e718943 100644 --- a/lib.js +++ b/lib.js @@ -4,7 +4,7 @@ * All credits for these codes belong to their respective creators, moderators and owners. * For more info (including license and terms of use), please visit respective source. */ - GLOBAL.cryptocoin = floGlobals.blockchain; + GLOBAL.cryptocoin = floGlobals.blockchain || 'FLO'; //Crypto.js (function() { @@ -6784,4 +6784,4 @@ })(); -})(typeof global !== "undefined" ? global : window); \ No newline at end of file +})(typeof global !== "undefined" ? global : window); From 94f90807f7e74f35464e664f342e31818df5673c Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 3 Apr 2022 20:15:58 +0530 Subject: [PATCH 189/289] Update lib.js - Added support when floGlobals is undefined --- lib.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib.js b/lib.js index e718943..80afa89 100644 --- a/lib.js +++ b/lib.js @@ -1,10 +1,10 @@ -(function(GLOBAL) { //lib v1.2.2 +(function(GLOBAL) { //lib v1.2.2a 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. * For more info (including license and terms of use), please visit respective source. */ - GLOBAL.cryptocoin = floGlobals.blockchain || 'FLO'; + GLOBAL.cryptocoin = (typeof floGlobals === 'undefined' ? null : floGlobals.blockchain) || 'FLO'; //Crypto.js (function() { @@ -6784,4 +6784,4 @@ })(); -})(typeof global !== "undefined" ? global : window); +})(typeof global !== "undefined" ? global : window); \ No newline at end of file From 99368151d5015b51b7a147d74a1d202d2b1c7cf4 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Mon, 16 May 2022 18:46:22 +0530 Subject: [PATCH 190/289] Adding floTokenAPI - Token Operator to send/receive tokens via blockchain using token system API floBlockchainAPI v2.3.1 - Added options parameter to writeData . Options can have the following properties: . strict_utxo : passes strict_utxo parameter to sendTx (Default: true) . sendAmt : amount of FLO to send (Default: floGlobals.sendAmt) --- floBlockchainAPI.js | 10 ++++---- floTokenAPI.js | 56 +++++++++++++++++++++++++++++++++++++++++++++ index.html | 5 +++- 3 files changed, 66 insertions(+), 5 deletions(-) create mode 100644 floTokenAPI.js diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 8d3d857..f13f6d5 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floBlockchainAPI v2.3.0 +(function(EXPORTS) { //floBlockchainAPI v2.3.1 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -45,7 +45,7 @@ }); //Promised function to get data from API - const promisedAPI = floBlockchainAPI.promisedAPI = function(apicall) { + const promisedAPI = floBlockchainAPI.promisedAPI = floBlockchainAPI.fetch = function(apicall) { return new Promise((resolve, reject) => { //console.log(apicall); fetch_api(apicall) @@ -126,11 +126,13 @@ } //Write Data into blockchain - floBlockchainAPI.writeData = function(senderAddr, data, privKey, receiverAddr = floGlobals.adminID, strict_utxo = true) { + floBlockchainAPI.writeData = function(senderAddr, data, privKey, receiverAddr = floGlobals.adminID, options = {}) { + let strict_utxo = options.strict_utxo === false ? false : true, + sendAmt = isNaN(options.sendAmt) ? floGlobals.sendAmt : options.sendAmt; return new Promise((resolve, reject) => { if (typeof data != "string") data = JSON.stringify(data); - sendTx(senderAddr, receiverAddr, floGlobals.sendAmt, privKey, data, strict_utxo) + sendTx(senderAddr, receiverAddr, sendAmt, privKey, data, strict_utxo) .then(txid => resolve(txid)) .catch(error => reject(error)); }); diff --git a/floTokenAPI.js b/floTokenAPI.js new file mode 100644 index 0000000..500c3a5 --- /dev/null +++ b/floTokenAPI.js @@ -0,0 +1,56 @@ +(function(EXPORTS) { //floTokenAPI v1.0.1 + /* Token Operator to send/receive tokens via blockchain using API calls*/ + 'use strict'; + const tokenAPI = EXPORTS; + + const fetch_api = tokenAPI.fetch = function(apicall) { + return new Promise((resolve, reject) => { + console.log(floGlobals.tokenURL + apicall); + fetch(floGlobals.tokenURL + apicall).then(response => { + if (response.ok) + response.json().then(data => resolve(data)); + else + reject(response) + }).catch(error => reject(error)) + }) + } + + const getBalance = tokenAPI.getBalance = function(floID, token = floGlobals.currency) { + return new Promise((resolve, reject) => { + fetch_api(`api/v1.0/getFloAddressBalance?token=${token}&floAddress=${floID}`) + .then(result => resolve(result.balance || 0)) + .catch(error => reject(error)) + }) + } + + tokenAPI.getTx = function(txID) { + return new Promise((resolve, reject) => { + fetch_api(`api/v1.0/getTransactionDetails/${txID}`).then(res => { + if (res.result === "error") + reject(res.description); + else if (!res.parsedFloData) + reject("Data piece (parsedFloData) missing"); + else if (!res.transactionDetails) + reject("Data piece (transactionDetails) missing"); + else + resolve(res); + }).catch(error => reject(error)) + }) + } + + tokenAPI.sendToken = function(privKey, amount, receiverID, message = "", token = floGlobals.currency, options = {}) { + return new Promise((resolve, reject) => { + let senderID = floCrypto.getFloID(privKey); + if (typeof amount !== "number" || amount <= 0) + return reject("Invalid amount"); + getBalance(senderID, token).then(bal => { + if (amount > bal) + return reject(`Insufficient ${token}# balance`); + floBlockchainAPI.writeData(senderID, `send ${amount} ${token}# ${message}`, privKey, receiverID, options) + .then(txid => resolve(txid)) + .catch(error => reject(error)) + }).catch(error => reject(error)) + }); + } + +})('object' === typeof module ? module.exports : window.floTokenAPI = {}); \ No newline at end of file diff --git a/index.html b/index.html index eced94e..567a097 100644 --- a/index.html +++ b/index.html @@ -10,7 +10,7 @@ //Required for all blockchain: "FLO", - //Required for blockchain API operators + //Required for blockchain API operations apiURL: { FLO: ['https://livenet.flocha.in/', 'https://flosight.duckdns.org/'], FLO_TEST: ['https://testnet-flosight.duckdns.org/', 'https://testnet.flocha.in/'] @@ -19,6 +19,9 @@ sendAmt: 0.001, fee: 0.0005, + //Required for token API operations + tokenURL: "https://ranchimallflo.duckdns.org/", + //Required for Supernode operations SNStorageID: "FNaN9McoBAEFUjkRmNQRYLmBF8SpS7Tgfk", supernodes: {}, //each supnernode must be stored as floID : {uri:,pubKey:} From 8603cde17e995929712564aca29bb1ce77943869 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Mon, 16 May 2022 21:20:21 +0530 Subject: [PATCH 191/289] Moving all defaults/containers to resp. modules - Removed default values from floGlobals - Default values are now in their respective modules - The following properties of floGlobals can be use to override the default values of respective modules: apiURL, sendAmt, fee, tokenURL, currency, SNStorageID - Default/current values can be obtained from each module with getter properties - Some current values can be set with setter properties - The containers for appObjects, generalData, lastVC are now in floCloudAPI module. Also automatically adds get/set properties for them in floGlobals. Thus can be accessed from floGlobals as before --- floBlockchainAPI.js | 72 ++++++++++++++++++++----- floCloudAPI.js | 125 +++++++++++++++++++++++++++++--------------- floDapps.js | 11 ++-- floTokenAPI.js | 27 ++++++++-- index.html | 25 +-------- 5 files changed, 171 insertions(+), 89 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index f13f6d5..80e1edf 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,9 +1,52 @@ -(function(EXPORTS) { //floBlockchainAPI v2.3.1 +(function(EXPORTS) { //floBlockchainAPI v2.3.2 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; - const serverList = floGlobals.apiURL[floGlobals.blockchain].slice(0); + const DEFAULT = { + blockchain: floGlobals.blockchain, + apiURL: { + FLO: ['https://livenet.flocha.in/', 'https://flosight.duckdns.org/'], + FLO_TEST: ['https://testnet-flosight.duckdns.org', 'https://testnet.flocha.in/'] + }, + sendAmt: 0.001, + fee: 0.0005, + receiverID: floGlobals.adminID + }; + + Object.defineProperties(floBlockchainAPI, { + sendAmt: { + get: () => DEFAULT.sendAmt, + set: amt => !isNaN(amt) ? DEFAULT.sendAmt = amt : null + }, + fee: { + get: () => DEFAULT.fee, + set: fee => !isNaN(fee) ? DEFAULT.fee = fee : null + }, + defaultReceiver: { + get: () => DEFAULT.receiverID, + set: floID => DEFAULT.receiverID = floID + }, + blockchain: { + get: () => DEFAULT.blockchain + } + }); + + if (floGlobals.sendAmt) floBlockchainAPI.sendAmt = floGlobals.sendAmt; + if (floGlobals.fee) floBlockchainAPI.fee = floGlobals.fee; + + Object.defineProperties(floGlobals, { + sendAmt: { + get: () => DEFAULT.sendAmt, + set: amt => !isNaN(amt) ? DEFAULT.sendAmt = amt : null + }, + fee: { + get: () => DEFAULT.fee, + set: fee => !isNaN(fee) ? DEFAULT.fee = fee : null + } + }); + + const serverList = Array.from(floGlobals.apiURL && floGlobals.apiURL[DEFAULT.blockchain] ? floGlobals.apiURL[DEFAULT.blockchain] : DEFAULT.apiURL[DEFAULT.blockchain]); var curPos = floCrypto.randInt(0, serverList - 1); function fetch_retry(apicall, rm_flosight) { @@ -40,8 +83,13 @@ }) } - Object.defineProperty(floBlockchainAPI, 'current_server', { - get: () => serverList[curPos] + Object.defineProperties(floBlockchainAPI, { + serverList: { + get: () => Array.from(serverList) + }, + current_server: { + get: () => serverList[curPos] + } }); //Promised function to get data from API @@ -95,7 +143,7 @@ //form/construct the transaction data var trx = bitjs.transaction(); var utxoAmt = 0.0; - var fee = floGlobals.fee; + var fee = DEFAULT.fee; for (var i = utxos.length - 1; (i >= 0) && (utxoAmt < sendAmt + fee); i--) { //use only utxos with confirmations (strict_utxo mode) @@ -126,9 +174,9 @@ } //Write Data into blockchain - floBlockchainAPI.writeData = function(senderAddr, data, privKey, receiverAddr = floGlobals.adminID, options = {}) { + floBlockchainAPI.writeData = function(senderAddr, data, privKey, receiverAddr = DEFAULT.receiverID, options = {}) { let strict_utxo = options.strict_utxo === false ? false : true, - sendAmt = isNaN(options.sendAmt) ? floGlobals.sendAmt : options.sendAmt; + sendAmt = isNaN(options.sendAmt) ? DEFAULT.sendAmt : options.sendAmt; return new Promise((resolve, reject) => { if (typeof data != "string") data = JSON.stringify(data); @@ -149,7 +197,7 @@ return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); var trx = bitjs.transaction(); var utxoAmt = 0.0; - var fee = floGlobals.fee; + var fee = DEFAULT.fee; promisedAPI(`api/addr/${floID}/utxo`).then(utxos => { for (var i = utxos.length - 1; i >= 0; i--) if (utxos[i].confirmations) { @@ -173,13 +221,13 @@ * @param {boolean} preserveRatio (optional) preserve ratio or equal contribution * @return {Promise} */ - floBlockchainAPI.writeDataMultiple = function(senderPrivKeys, data, receivers = [floGlobals.adminID], preserveRatio = true) { + floBlockchainAPI.writeDataMultiple = function(senderPrivKeys, data, receivers = [DEFAULT.receiverID], preserveRatio = true) { return new Promise((resolve, reject) => { if (!Array.isArray(senderPrivKeys)) return reject("Invalid senderPrivKeys: SenderPrivKeys must be Array"); if (!preserveRatio) { let tmp = {}; - let amount = (floGlobals.sendAmt * receivers.length) / senderPrivKeys.length; + let amount = (DEFAULT.sendAmt * receivers.length) / senderPrivKeys.length; senderPrivKeys.forEach(key => tmp[key] = amount); senderPrivKeys = tmp; } @@ -187,7 +235,7 @@ return reject("Invalid receivers: Receivers must be Array"); else { let tmp = {}; - let amount = floGlobals.sendAmt; + let amount = DEFAULT.sendAmt; receivers.forEach(floID => tmp[floID] = amount); receivers = tmp } @@ -290,7 +338,7 @@ promises.push(getBalance(floID)); Promise.all(promises).then(results => { let totalBalance = 0, - totalFee = floGlobals.fee, + totalFee = DEFAULT.fee, balance = {}; //Divide fee among sender if not for preserveRatio if (!preserveRatio) diff --git a/floCloudAPI.js b/floCloudAPI.js index 512c8ae..ca31378 100644 --- a/floCloudAPI.js +++ b/floCloudAPI.js @@ -1,8 +1,47 @@ -(function(EXPORTS) { //floCloudAPI v2.2.0a +(function(EXPORTS) { //floCloudAPI v2.3.0 /* FLO Cloud operations to send/request application data*/ 'use strict'; const floCloudAPI = EXPORTS; + const DEFAULT = { + SNStorageID: floGlobals.SNStorageID || "FNaN9McoBAEFUjkRmNQRYLmBF8SpS7Tgfk", + adminID: floGlobals.adminID, + application: floGlobals.application + }; + + Object.defineProperties(floCloudAPI, { + SNStorageID: { + get: () => DEFAULT.SNStorageID + }, + adminID: { + get: () => DEFAULT.adminID + }, + application: { + get: () => DEFAULT.application + } + }); + + var appObjects, generalData, lastVC; + Object.defineProperties(floGlobals, { + appObjects: { + get: () => appObjects, + set: obj => appObjects = obj + }, + generalData: { + get: () => generalData, + set: data => generalData = data + }, + lastVC: { + get: () => lastVC, + set: vc => lastVC = vc + } + }); + + var supernodes = {}; //each supnernode must be stored as floID : {uri:,pubKey:} + Object.defineProperty(floCloudAPI, 'nodes', { + get: () => JSON.parse(JSON.stringify(supernodes)) + }); + var kBucket; const K_Bucket = floCloudAPI.K_Bucket = function(masterID, nodeList) { @@ -98,11 +137,11 @@ } } - floCloudAPI.init = function startCloudProcess(SNStorageID = floGlobals.SNStorageID, nodeList = null) { + floCloudAPI.init = function startCloudProcess(nodes) { return new Promise((resolve, reject) => { try { - nodeList = nodeList || Object.keys(floGlobals.supernodes); - kBucket = new K_Bucket(SNStorageID, nodeList); + supernodes = nodes; + kBucket = new K_Bucket(DEFAULT.SNStorageID, Object.keys(supernodes)); resolve('Cloud init successful'); } catch (error) { reject(error); @@ -118,11 +157,11 @@ function ws_connect(snID) { return new Promise((resolve, reject) => { - if (!(snID in floGlobals.supernodes)) + if (!(snID in supernodes)) return reject(`${snID} is not a supernode`) if (_inactive.has(snID)) return reject(`${snID} is not active`) - var wsConn = new WebSocket("wss://" + floGlobals.supernodes[snID].uri + "/"); + var wsConn = new WebSocket("wss://" + supernodes[snID].uri + "/"); wsConn.onopen = evt => resolve(wsConn); wsConn.onerror = evt => { _inactive.add(snID) @@ -135,7 +174,7 @@ return new Promise((resolve, reject) => { if (_inactive.size === kBucket.list.length) return reject('Cloud offline'); - if (!(snID in floGlobals.supernodes)) + if (!(snID in supernodes)) snID = kBucket.closestNode(snID); ws_connect(snID) .then(node => resolve(node)) @@ -155,7 +194,7 @@ return new Promise((resolve, reject) => { if (_inactive.has(snID)) return reject(`${snID} is not active`); - let fetcher, sn_url = "https://" + floGlobals.supernodes[snID].uri; + let fetcher, sn_url = "https://" + supernodes[snID].uri; if (typeof data === "string") fetcher = fetch(sn_url + "?" + data); else if (typeof data === "object" && data.method === "POST") @@ -173,7 +212,7 @@ return new Promise((resolve, reject) => { if (_inactive.size === kBucket.list.length) return reject('Cloud offline'); - if (!(snID in floGlobals.supernodes)) + if (!(snID in supernodes)) snID = kBucket.closestNode(snID); fetch_API(snID, data) .then(result => resolve(result)) @@ -289,8 +328,8 @@ const filterKey = util.filterKey = function(type, options) { return type + (options.comment ? ':' + options.comment : '') + - '|' + (options.group || options.receiverID || floGlobals.adminID) + - '|' + (options.application || floGlobals.application); + '|' + (options.group || options.receiverID || DEFAULT.adminID) + + '|' + (options.application || DEFAULT.application); } const lastCommit = {}; @@ -298,7 +337,7 @@ value: objName => JSON.parse(lastCommit[objName]) }); Object.defineProperty(lastCommit, 'set', { - value: objName => lastCommit[objName] = JSON.stringify(floGlobals.appObjects[objName]) + value: objName => lastCommit[objName] = JSON.stringify(appObjects[objName]) }); function updateObject(objectName, dataSet) { @@ -306,22 +345,22 @@ console.log(dataSet) let vcList = Object.keys(dataSet).sort(); for (let vc of vcList) { - if (vc < floGlobals.lastVC[objectName] || dataSet[vc].type !== objectName) + if (vc < lastVC[objectName] || dataSet[vc].type !== objectName) continue; switch (dataSet[vc].comment) { case "RESET": if (dataSet[vc].message.reset) - floGlobals.appObjects[objectName] = dataSet[vc].message.reset; + appObjects[objectName] = dataSet[vc].message.reset; break; case "UPDATE": if (dataSet[vc].message.diff) - floGlobals.appObjects[objectName] = diff.merge(floGlobals.appObjects[objectName], dataSet[vc].message.diff); + appObjects[objectName] = diff.merge(appObjects[objectName], dataSet[vc].message.diff); } - floGlobals.lastVC[objectName] = vc; + lastVC[objectName] = vc; } lastCommit.set(objectName); - compactIDB.writeData("appObjects", floGlobals.appObjects[objectName], objectName); - compactIDB.writeData("lastVC", floGlobals.lastVC[objectName], objectName); + compactIDB.writeData("appObjects", appObjects[objectName], objectName); + compactIDB.writeData("lastVC", lastVC[objectName], objectName); } catch (error) { console.error(error) } @@ -330,15 +369,15 @@ function storeGeneral(fk, dataSet) { try { console.log(dataSet) - if (typeof floGlobals.generalData[fk] !== "object") - floGlobals.generalData[fk] = {} + if (typeof generalData[fk] !== "object") + generalData[fk] = {} for (let vc in dataSet) { - floGlobals.generalData[fk][vc] = dataSet[vc]; - if (dataSet[vc].log_time > floGlobals.lastVC[fk]) - floGlobals.lastVC[fk] = dataSet[vc].log_time; + generalData[fk][vc] = dataSet[vc]; + if (dataSet[vc].log_time > lastVC[fk]) + lastVC[fk] = dataSet[vc].log_time; } - compactIDB.writeData("lastVC", floGlobals.lastVC[fk], fk) - compactIDB.writeData("generalData", floGlobals.generalData[fk], fk) + compactIDB.writeData("lastVC", lastVC[fk], fk) + compactIDB.writeData("generalData", generalData[fk], fk) } catch (error) { console.error(error) } @@ -359,14 +398,14 @@ let callback = options.callback instanceof Function ? options.callback : (d, e) => console.debug(d, e); var request = { floID: myFloID, - application: options.application || floGlobals.application, + application: options.application || DEFAULT.application, time: Date.now(), status: true, pubKey: myPubKey } let hashcontent = ["time", "application", "floID"].map(d => request[d]).join("|"); request.sign = floCrypto.signData(hashcontent, myPrivKey); - liveRequest(options.refID || floGlobals.adminID, request, callback) + liveRequest(options.refID || DEFAULT.adminID, request, callback) .then(result => resolve(result)) .catch(error => reject(error)) }) @@ -380,10 +419,10 @@ let callback = options.callback instanceof Function ? options.callback : (d, e) => console.debug(d, e); let request = { status: false, - application: options.application || floGlobals.application, + application: options.application || DEFAULT.application, trackList: trackList } - liveRequest(options.refID || floGlobals.adminID, request, callback) + liveRequest(options.refID || DEFAULT.adminID, request, callback) .then(result => resolve(result)) .catch(error => reject(error)) }) @@ -394,11 +433,11 @@ return new Promise((resolve, reject) => { var data = { senderID: myFloID, - receiverID: options.receiverID || floGlobals.adminID, + receiverID: options.receiverID || DEFAULT.adminID, pubKey: myPubKey, message: encodeMessage(message), time: Date.now(), - application: options.application || floGlobals.application, + application: options.application || DEFAULT.application, type: type, comment: options.comment || "" } @@ -415,9 +454,9 @@ const requestApplicationData = floCloudAPI.requestApplicationData = function(type, options = {}) { return new Promise((resolve, reject) => { var request = { - receiverID: options.receiverID || floGlobals.adminID, + receiverID: options.receiverID || DEFAULT.adminID, senderID: options.senderID || undefined, - application: options.application || floGlobals.application, + application: options.application || DEFAULT.application, type: type, comment: options.comment || undefined, lowerVectorClock: options.lowerVectorClock || undefined, @@ -451,7 +490,7 @@ pubKey: myPubKey, time: Date.now(), delete: (Array.isArray(vectorClocks) ? vectorClocks : [vectorClocks]), - application: options.application || floGlobals.application + application: options.application || DEFAULT.application } let hashcontent = ["time", "application", "delete"] .map(d => delreq[d]).join("|") @@ -517,7 +556,7 @@ if (!floGlobals.subAdmins.includes(myFloID)) return reject("Only subAdmins can tag data") var request = { - receiverID: options.receiverID || floGlobals.adminID, + receiverID: options.receiverID || DEFAULT.adminID, requestorID: myFloID, pubKey: myPubKey, time: Date.now(), @@ -536,7 +575,7 @@ floCloudAPI.noteApplicationData = function(vectorClock, note, options = {}) { return new Promise((resolve, reject) => { var request = { - receiverID: options.receiverID || floGlobals.adminID, + receiverID: options.receiverID || DEFAULT.adminID, requestorID: myFloID, pubKey: myPubKey, time: Date.now(), @@ -569,8 +608,8 @@ floCloudAPI.requestGeneralData = function(type, options = {}) { return new Promise((resolve, reject) => { var fk = filterKey(type, options) - floGlobals.lastVC[fk] = parseInt(floGlobals.lastVC[fk]) || 0; - options.afterTime = options.afterTime || floGlobals.lastVC[fk]; + lastVC[fk] = parseInt(lastVC[fk]) || 0; + options.afterTime = options.afterTime || lastVC[fk]; if (options.callback instanceof Function) { let new_options = Object.create(options) new_options.callback = (d, e) => { @@ -592,7 +631,7 @@ //request an object data from supernode cloud floCloudAPI.requestObjectData = function(objectName, options = {}) { return new Promise((resolve, reject) => { - options.lowerVectorClock = options.lowerVectorClock || floGlobals.lastVC[objectName] + 1; + options.lowerVectorClock = options.lowerVectorClock || lastVC[objectName] + 1; options.senderID = [false, null].includes(options.senderID) ? null : options.senderID || floGlobals.subAdmins; options.mostRecent = true; @@ -609,7 +648,7 @@ requestApplicationData(objectName, options).then(dataSet => { updateObject(objectName, objectifier(dataSet)); delete options.comment; - options.lowerVectorClock = floGlobals.lastVC[objectName] + 1; + options.lowerVectorClock = lastVC[objectName] + 1; delete options.mostRecent; if (callback) { let new_options = Object.create(options); @@ -620,7 +659,7 @@ } else { requestApplicationData(objectName, options).then(dataSet => { updateObject(objectName, objectifier(dataSet)) - resolve(floGlobals.appObjects[objectName]) + resolve(appObjects[objectName]) }).catch(error => reject(error)) } }).catch(error => reject(error)) @@ -644,7 +683,7 @@ floCloudAPI.resetObjectData = function(objectName, options = {}) { return new Promise((resolve, reject) => { let message = { - reset: floGlobals.appObjects[objectName] + reset: appObjects[objectName] } options.comment = 'RESET'; sendApplicationData(message, objectName, options).then(result => { @@ -658,7 +697,7 @@ floCloudAPI.updateObjectData = function(objectName, options = {}) { return new Promise((resolve, reject) => { let message = { - diff: diff.find(lastCommit.get(objectName), floGlobals.appObjects[ + diff: diff.find(lastCommit.get(objectName), appObjects[ objectName]) } options.comment = 'UPDATE'; diff --git a/floDapps.js b/floDapps.js index 6e3ecbd..0e92708 100644 --- a/floDapps.js +++ b/floDapps.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floDapps v2.2.0a +(function(EXPORTS) { //floDapps v2.2.1 /* General functions for FLO Dapps*/ //'use strict'; const floDapps = EXPORTS; @@ -72,8 +72,8 @@ startUpFunctions.push(function readSupernodeListFromAPI() { return new Promise((resolve, reject) => { - compactIDB.readData("lastTx", floGlobals.SNStorageID, "floDapps").then(lastTx => { - floBlockchainAPI.readData(floGlobals.SNStorageID, { + compactIDB.readData("lastTx", floCloudAPI.SNStorageID, "floDapps").then(lastTx => { + floBlockchainAPI.readData(floCloudAPI.SNStorageID, { ignoreOld: lastTx, sentOnly: true, pattern: "SuperNodeStorage" @@ -85,10 +85,9 @@ for (sn in content.newNodes) compactIDB.writeData("supernodes", content.newNodes[sn], sn, "floDapps"); } - compactIDB.writeData("lastTx", result.totalTxs, floGlobals.SNStorageID, "floDapps"); + compactIDB.writeData("lastTx", result.totalTxs, floCloudAPI.SNStorageID, "floDapps"); compactIDB.readAllData("supernodes", "floDapps").then(result => { - floGlobals.supernodes = result; - floCloudAPI.init() + floCloudAPI.init(result) .then(result => resolve("Loaded Supernode list\n" + result)) .catch(error => reject(error)) }) diff --git a/floTokenAPI.js b/floTokenAPI.js index 500c3a5..8a5f953 100644 --- a/floTokenAPI.js +++ b/floTokenAPI.js @@ -1,12 +1,29 @@ -(function(EXPORTS) { //floTokenAPI v1.0.1 +(function(EXPORTS) { //floTokenAPI v1.0.2 /* Token Operator to send/receive tokens via blockchain using API calls*/ 'use strict'; const tokenAPI = EXPORTS; + const DEFAULT = { + apiURL: floGlobals.tokenURL || "https://ranchimallflo.duckdns.org/", + currency: "rupee" + } + + Object.defineProperties(tokenAPI, { + URL: { + get: () => DEFAULT.apiURL + }, + currency: { + get: () => DEFAULT.currency, + set: currency => DEFAULT.currency = currency + } + }); + + if (floGlobals.currency) tokenAPI.currency = floGlobals.currency; + const fetch_api = tokenAPI.fetch = function(apicall) { return new Promise((resolve, reject) => { - console.log(floGlobals.tokenURL + apicall); - fetch(floGlobals.tokenURL + apicall).then(response => { + console.log(DEFAULT.apiURL + apicall); + fetch(DEFAULT.apiURL + apicall).then(response => { if (response.ok) response.json().then(data => resolve(data)); else @@ -15,7 +32,7 @@ }) } - const getBalance = tokenAPI.getBalance = function(floID, token = floGlobals.currency) { + const getBalance = tokenAPI.getBalance = function(floID, token = DEFAULT.currency) { return new Promise((resolve, reject) => { fetch_api(`api/v1.0/getFloAddressBalance?token=${token}&floAddress=${floID}`) .then(result => resolve(result.balance || 0)) @@ -38,7 +55,7 @@ }) } - tokenAPI.sendToken = function(privKey, amount, receiverID, message = "", token = floGlobals.currency, options = {}) { + tokenAPI.sendToken = function(privKey, amount, receiverID, message = "", token = DEFAULT.currency, options = {}) { return new Promise((resolve, reject) => { let senderID = floCrypto.getFloID(privKey); if (typeof amount !== "number" || amount <= 0) diff --git a/index.html b/index.html index 567a097..af9daca 100644 --- a/index.html +++ b/index.html @@ -6,37 +6,16 @@ + From 5d7d3bdb536b621956e137965e78f12caf39ec8b Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sat, 21 May 2022 22:19:54 +0530 Subject: [PATCH 192/289] floBlockchainAPI v2.3.2a sendTx: - check total balance before processing utxos - reject "Insufficient FLO: Some UTXOs are unconfirmed" when balance is there but some utxo are used/unconfimed --- floBlockchainAPI.js | 90 +++++++++++++++++++++++---------------------- index.html | 1 - 2 files changed, 47 insertions(+), 44 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 80e1edf..ffe3b53 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floBlockchainAPI v2.3.2 +(function(EXPORTS) { //floBlockchainAPI v2.3.2a /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -125,48 +125,52 @@ else if (typeof sendAmt !== 'number' || sendAmt <= 0) return reject(`Invalid sendAmt : ${sendAmt}`); - //get unconfirmed tx list - promisedAPI(`api/addr/${senderAddr}`).then(result => { - readTxs(senderAddr, 0, result.unconfirmedTxApperances).then(result => { - let unconfirmedSpent = {}; - for (let tx of result.items) - if (tx.confirmations == 0) - for (let vin of tx.vin) - if (vin.addr === senderAddr) { - if (Array.isArray(unconfirmedSpent[vin.txid])) - unconfirmedSpent[vin.txid].push(vin.vout); - else - unconfirmedSpent[vin.txid] = [vin.vout]; - } - //get utxos list - promisedAPI(`api/addr/${senderAddr}/utxo`).then(utxos => { - //form/construct the transaction data - var trx = bitjs.transaction(); - var utxoAmt = 0.0; - var fee = DEFAULT.fee; - for (var i = utxos.length - 1; - (i >= 0) && (utxoAmt < sendAmt + fee); i--) { - //use only utxos with confirmations (strict_utxo mode) - if (utxos[i].confirmations || !strict_utxo) { - if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout)) - continue; //A transaction has already used the utxo, but is unconfirmed. - trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); - utxoAmt += utxos[i].amount; - }; - } - if (utxoAmt < sendAmt + fee) - reject("Insufficient FLO balance!"); - else { - trx.addoutput(receiverAddr, sendAmt); - var change = utxoAmt - sendAmt - fee; - if (change > 0) - trx.addoutput(senderAddr, change); - trx.addflodata(floData.replace(/\n/g, ' ')); - var signedTxHash = trx.sign(privKey, 1); - broadcastTx(signedTxHash) - .then(txid => resolve(txid)) - .catch(error => reject(error)) - } + getBalance(senderAddr).then(balance => { + var fee = DEFAULT.fee; + if (balance < sendAmt + fee) + return reject("Insufficient FLO balance!"); + //get unconfirmed tx list + promisedAPI(`api/addr/${senderAddr}`).then(result => { + readTxs(senderAddr, 0, result.unconfirmedTxApperances).then(result => { + let unconfirmedSpent = {}; + for (let tx of result.items) + if (tx.confirmations == 0) + for (let vin of tx.vin) + if (vin.addr === senderAddr) { + if (Array.isArray(unconfirmedSpent[vin.txid])) + unconfirmedSpent[vin.txid].push(vin.vout); + else + unconfirmedSpent[vin.txid] = [vin.vout]; + } + //get utxos list + promisedAPI(`api/addr/${senderAddr}/utxo`).then(utxos => { + //form/construct the transaction data + var trx = bitjs.transaction(); + var utxoAmt = 0.0; + for (var i = utxos.length - 1; + (i >= 0) && (utxoAmt < sendAmt + fee); i--) { + //use only utxos with confirmations (strict_utxo mode) + if (utxos[i].confirmations || !strict_utxo) { + if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout)) + continue; //A transaction has already used the utxo, but is unconfirmed. + trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); + utxoAmt += utxos[i].amount; + }; + } + if (utxoAmt < sendAmt + fee) + reject("Insufficient FLO: Some UTXOs are unconfirmed"); + else { + trx.addoutput(receiverAddr, sendAmt); + var change = utxoAmt - sendAmt - fee; + if (change > 0) + trx.addoutput(senderAddr, change); + trx.addflodata(floData.replace(/\n/g, ' ')); + var signedTxHash = trx.sign(privKey, 1); + broadcastTx(signedTxHash) + .then(txid => resolve(txid)) + .catch(error => reject(error)) + } + }).catch(error => reject(error)) }).catch(error => reject(error)) }).catch(error => reject(error)) }).catch(error => reject(error)) diff --git a/index.html b/index.html index af9daca..03ee1ba 100644 --- a/index.html +++ b/index.html @@ -8,7 +8,6 @@ const floGlobals = { blockchain: "FLO", adminID: "FKAEdnPfjXLHSYwrXQu377ugN4tXU7VGdf", - fee: 0.01, application: "TEST_MODE", } From 0683bf73182e57dbb16c75d019de0655345d489a Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 24 May 2022 01:32:23 +0530 Subject: [PATCH 193/289] floTokenAPI v1.0.3 - getAllTxs: get all transactions of the given floID and token - util.parseTxData: parse the txData resolved by getTx and getAllTxs --- floTokenAPI.js | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/floTokenAPI.js b/floTokenAPI.js index 8a5f953..894f0c0 100644 --- a/floTokenAPI.js +++ b/floTokenAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floTokenAPI v1.0.2 +(function(EXPORTS) { //floTokenAPI v1.0.3 /* Token Operator to send/receive tokens via blockchain using API calls*/ 'use strict'; const tokenAPI = EXPORTS; @@ -70,4 +70,26 @@ }); } + tokenAPI.getAllTxs = function(floID, token = DEFAULT.currency) { + return new Promise((resolve, reject) => { + fetch_api(`api/v1.0/getFloAddressTransactions?token=${token}&floAddress=${floID}`) + .then(result => resolve(result)) + .catch(error => reject(error)) + }) + } + + const util = tokenAPI.util = {}; + + util.parseTxData = function(txData) { + let parsedData = {}; + for (let p in txData.parsedFloData) + parsedData[p] = txData.parsedFloData[p]; + parsedData.sender = txData.transactionDetails.vin[0].addr; + for (let vout of txData.transactionDetails.vout) + if (vout.scriptPubKey.addresses[0] !== parsedData.sender) + parsedData.receiver = vout.scriptPubKey.addresses[0]; + parsedData.time = txData.transactionDetails.time; + return parsedData; + } + })('object' === typeof module ? module.exports : window.floTokenAPI = {}); \ No newline at end of file From 960aa1f52d1758bdab6688db794efce85ca06914 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 24 May 2022 02:25:44 +0530 Subject: [PATCH 194/289] floBlockchainAPI v2.3.3 - If API is called when serverList is empty, reset the list and try again once --- floBlockchainAPI.js | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index ffe3b53..fcc73b9 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floBlockchainAPI v2.3.2a +(function(EXPORTS) { //floBlockchainAPI v2.3.3 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -46,7 +46,9 @@ } }); - const serverList = Array.from(floGlobals.apiURL && floGlobals.apiURL[DEFAULT.blockchain] ? floGlobals.apiURL[DEFAULT.blockchain] : DEFAULT.apiURL[DEFAULT.blockchain]); + const allServerList = new Set(floGlobals.apiURL && floGlobals.apiURL[DEFAULT.blockchain] ? floGlobals.apiURL[DEFAULT.blockchain] : DEFAULT.apiURL[DEFAULT.blockchain]); + + var serverList = Array.from(allServerList); var curPos = floCrypto.randInt(0, serverList - 1); function fetch_retry(apicall, rm_flosight) { @@ -54,17 +56,24 @@ let i = serverList.indexOf(rm_flosight) if (i != -1) serverList.splice(i, 1); curPos = floCrypto.randInt(0, serverList.length - 1); - fetch_api(apicall) + fetch_api(apicall, false) .then(result => resolve(result)) .catch(error => reject(error)); }) } - function fetch_api(apicall) { + function fetch_api(apicall, ic = true) { return new Promise((resolve, reject) => { - if (serverList.length === 0) - reject("No floSight server working"); - else { + if (serverList.length === 0) { + if (ic) { + serverList = Array.from(allServerList); + curPos = floCrypto.randInt(0, serverList.length - 1); + fetch_api(apicall, false) + .then(result => resolve(result)) + .catch(error => reject(error)); + } else + reject("No floSight server working"); + } else { let flosight = serverList[curPos]; fetch(flosight + apicall).then(response => { if (response.ok) From 29e20de25b0f44b0012a38b45a0cdadea054bded Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 24 May 2022 19:41:45 +0530 Subject: [PATCH 195/289] floTokenAPI v1.0.3a check if amount is not NaN before sendToken --- floTokenAPI.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/floTokenAPI.js b/floTokenAPI.js index 894f0c0..a87876f 100644 --- a/floTokenAPI.js +++ b/floTokenAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floTokenAPI v1.0.3 +(function(EXPORTS) { //floTokenAPI v1.0.3a /* Token Operator to send/receive tokens via blockchain using API calls*/ 'use strict'; const tokenAPI = EXPORTS; @@ -58,7 +58,7 @@ tokenAPI.sendToken = function(privKey, amount, receiverID, message = "", token = DEFAULT.currency, options = {}) { return new Promise((resolve, reject) => { let senderID = floCrypto.getFloID(privKey); - if (typeof amount !== "number" || amount <= 0) + if (typeof amount !== "number" || isNaN(amount) || amount <= 0) return reject("Invalid amount"); getBalance(senderID, token).then(bal => { if (amount > bal) From 9435592c8bb36d85dfd297ab993f45ebb2b65abd Mon Sep 17 00:00:00 2001 From: sairajzero Date: Wed, 25 May 2022 02:45:50 +0530 Subject: [PATCH 196/289] floTokenAPI v1.0.3b - floGlobals.currency serves as getter and setter for DEFAULT.currency in tokenAPI module --- floTokenAPI.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/floTokenAPI.js b/floTokenAPI.js index a87876f..7378f43 100644 --- a/floTokenAPI.js +++ b/floTokenAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floTokenAPI v1.0.3a +(function(EXPORTS) { //floTokenAPI v1.0.3b /* Token Operator to send/receive tokens via blockchain using API calls*/ 'use strict'; const tokenAPI = EXPORTS; @@ -20,6 +20,13 @@ if (floGlobals.currency) tokenAPI.currency = floGlobals.currency; + Object.defineProperties(floGlobals, { + currency: { + get: () => DEFAULT.currency, + set: currency => DEFAULT.currency = currency + } + }); + const fetch_api = tokenAPI.fetch = function(apicall) { return new Promise((resolve, reject) => { console.log(DEFAULT.apiURL + apicall); From 151ea8f751eccfcc89b98d5e3e4c732995f4c937 Mon Sep 17 00:00:00 2001 From: Sai Raj <39055732+sairajzero@users.noreply.github.com> Date: Fri, 1 Jul 2022 21:55:45 +0530 Subject: [PATCH 197/289] Update README.md --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index ed6f998..536a71a 100644 --- a/README.md +++ b/README.md @@ -455,9 +455,6 @@ Note: If passed as Array, then ratio of the balance of the senders are preserved 2. dbName - Name of the database (optional, uses defaultDB if not specified) * Resolves: data (Object) | Rejects: error -## FLO Supernode module -This module contains functions that interact with the supernode to send and retrive data in the backend. Use floClouldAPI operations to send and receive data for application. - ## FLO Cloud API operations `floCloudAPI` operations can interact with floSupernode cloud to send and retrieve data for applications. floCloudAPI uses floSupernode module for backend interactions. FLO Cloud API functions are promisified and resolves the data or status. From cfc36b80cdc201b96874f55af2a0a37c800f06a5 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sat, 16 Jul 2022 03:30:03 +0530 Subject: [PATCH 198/289] Secure private key using capsule --- floCloudAPI.js | 95 ++++++++++++++------ floDapps.js | 235 +++++++++++++++++++++++++++++++++---------------- index.html | 3 +- 3 files changed, 229 insertions(+), 104 deletions(-) diff --git a/floCloudAPI.js b/floCloudAPI.js index ca31378..e06ba60 100644 --- a/floCloudAPI.js +++ b/floCloudAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCloudAPI v2.3.0 +(function(EXPORTS) { //floCloudAPI v2.4.0 /* FLO Cloud operations to send/request application data*/ 'use strict'; const floCloudAPI = EXPORTS; @@ -6,9 +6,32 @@ const DEFAULT = { SNStorageID: floGlobals.SNStorageID || "FNaN9McoBAEFUjkRmNQRYLmBF8SpS7Tgfk", adminID: floGlobals.adminID, - application: floGlobals.application + application: floGlobals.application, + callback: (d, e) => console.debug(d, e) }; + var user_id, user_public, user_private; + const user = { + get id() { + if (!user_id) + throw "User not set"; + return user_id; + }, + get public() { + if (!user_public) + throw "User not set"; + return user_public; + }, + sign(msg) { + if (!user_private) + throw "User not set"; + return floCrypto.signData(msg, user_private); + }, + clear() { + user_id = user_public = user_private = undefined; + } + } + Object.defineProperties(floCloudAPI, { SNStorageID: { get: () => DEFAULT.SNStorageID @@ -18,6 +41,21 @@ }, application: { get: () => DEFAULT.application + }, + user: { + set: priv => { + if (!priv) + user_id = user_public = user_private = undefined; + else { + user_public = floCrypto.getPubKeyHex(priv); + user_id = floCrypto.getFloID(user_public); + if (!user_public || !user_id || !floCrypto.verifyPrivKey(priv, user_id)) + user_id = user_public = user_private = undefined; + else + user_private = priv; + } + }, + get: () => user } }); @@ -392,19 +430,19 @@ })); } - //set status as online for myFloID + //set status as online for user_id floCloudAPI.setStatus = function(options = {}) { return new Promise((resolve, reject) => { - let callback = options.callback instanceof Function ? options.callback : (d, e) => console.debug(d, e); + let callback = options.callback instanceof Function ? options.callback : DEFAULT.callback; var request = { - floID: myFloID, + floID: user.id, application: options.application || DEFAULT.application, time: Date.now(), status: true, - pubKey: myPubKey + pubKey: user.public } let hashcontent = ["time", "application", "floID"].map(d => request[d]).join("|"); - request.sign = floCrypto.signData(hashcontent, myPrivKey); + request.sign = user.sign(hashcontent); liveRequest(options.refID || DEFAULT.adminID, request, callback) .then(result => resolve(result)) .catch(error => reject(error)) @@ -416,7 +454,7 @@ return new Promise((resolve, reject) => { if (!Array.isArray(trackList)) trackList = [trackList]; - let callback = options.callback instanceof Function ? options.callback : (d, e) => console.debug(d, e); + let callback = options.callback instanceof Function ? options.callback : DEFAULT.callback; let request = { status: false, application: options.application || DEFAULT.application, @@ -432,9 +470,9 @@ const sendApplicationData = floCloudAPI.sendApplicationData = function(message, type, options = {}) { return new Promise((resolve, reject) => { var data = { - senderID: myFloID, + senderID: user.id, receiverID: options.receiverID || DEFAULT.adminID, - pubKey: myPubKey, + pubKey: user.public, message: encodeMessage(message), time: Date.now(), application: options.application || DEFAULT.application, @@ -443,7 +481,7 @@ } let hashcontent = ["receiverID", "time", "application", "type", "message", "comment"] .map(d => data[d]).join("|") - data.sign = floCrypto.signData(hashcontent, myPrivKey); + data.sign = user.sign(hashcontent); singleRequest(data.receiverID, data) .then(result => resolve(result)) .catch(error => reject(error)) @@ -482,19 +520,20 @@ }) } - //(NEEDS UPDATE) delete data from supernode cloud (received only) + /*(NEEDS UPDATE) + //delete data from supernode cloud (received only) floCloudAPI.deleteApplicationData = function(vectorClocks, options = {}) { return new Promise((resolve, reject) => { var delreq = { - requestorID: myFloID, - pubKey: myPubKey, + requestorID: user.id, + pubKey: user.public, time: Date.now(), delete: (Array.isArray(vectorClocks) ? vectorClocks : [vectorClocks]), application: options.application || DEFAULT.application } let hashcontent = ["time", "application", "delete"] .map(d => delreq[d]).join("|") - delreq.sign = floCrypto.signData(hashcontent, myPrivKey) + delreq.sign = user.sign(hashcontent) singleRequest(delreq.requestorID, delreq).then(result => { let success = [], failed = []; @@ -507,8 +546,9 @@ }).catch(error => reject(error)) }) } - - //(NEEDS UPDATE) edit comment of data in supernode cloud (mutable comments only) + */ + /*(NEEDS UPDATE) + //edit comment of data in supernode cloud (mutable comments only) floCloudAPI.editApplicationData = function(vectorClock, newComment, oldData, options = {}) { return new Promise((resolve, reject) => { let p0 @@ -523,12 +563,12 @@ } }) p0.then(d => { - if (d.senderID != myFloID) + if (d.senderID != user.id) return reject("Invalid requestorID") else if (!d.comment.startsWith("EDIT:")) return reject("Data immutable") let data = { - requestorID: myFloID, + requestorID: user.id, receiverID: d.receiverID, time: Date.now(), application: d.application, @@ -542,29 +582,30 @@ "comment" ] .map(x => d[x]).join("|") - data.edit.sign = floCrypto.signData(hashcontent, myPrivKey) + data.edit.sign = user.sign(hashcontent) singleRequest(data.receiverID, data) .then(result => resolve("Data comment updated")) .catch(error => reject(error)) }) }) } + */ //tag data in supernode cloud (subAdmin access only) floCloudAPI.tagApplicationData = function(vectorClock, tag, options = {}) { return new Promise((resolve, reject) => { - if (!floGlobals.subAdmins.includes(myFloID)) + if (!floGlobals.subAdmins.includes(user.id)) return reject("Only subAdmins can tag data") var request = { receiverID: options.receiverID || DEFAULT.adminID, - requestorID: myFloID, - pubKey: myPubKey, + requestorID: user.id, + pubKey: user.public, time: Date.now(), vectorClock: vectorClock, tag: tag, } let hashcontent = ["time", "vectorClock", 'tag'].map(d => request[d]).join("|"); - request.sign = floCrypto.signData(hashcontent, myPrivKey); + request.sign = user.sign(hashcontent); singleRequest(request.receiverID, request) .then(result => resolve(result)) .catch(error => reject(error)) @@ -576,14 +617,14 @@ return new Promise((resolve, reject) => { var request = { receiverID: options.receiverID || DEFAULT.adminID, - requestorID: myFloID, - pubKey: myPubKey, + requestorID: user.id, + pubKey: user.public, time: Date.now(), vectorClock: vectorClock, note: note, } let hashcontent = ["time", "vectorClock", 'note'].map(d => request[d]).join("|"); - request.sign = floCrypto.signData(hashcontent, myPrivKey); + request.sign = user.sign(hashcontent); singleRequest(request.receiverID, request) .then(result => resolve(result)) .catch(error => reject(error)) diff --git a/floDapps.js b/floDapps.js index 0e92708..08e3dd4 100644 --- a/floDapps.js +++ b/floDapps.js @@ -1,8 +1,88 @@ -(function(EXPORTS) { //floDapps v2.2.1 +(function(EXPORTS) { //floDapps v2.3.0 /* General functions for FLO Dapps*/ - //'use strict'; + 'use strict'; const floDapps = EXPORTS; + const DEFAULT = { + get root() { + return "floDapps" + }, + application: floGlobals.application, + adminID: floGlobals.adminID + }; + + var raw_user_private; //private variable inside capsule + const raw_user = { + get private() { + if (!raw_user_private) + throw "User not logged in"; + return raw_user_private; + } + } + + var user_id, user_public, user_private; + const user = floDapps.user = { + get id() { + if (!user_id) + throw "User not logged in"; + return user_id; + }, + get public() { + if (!user_public) + throw "User not logged in"; + return user_public; + }, + get private() { + if (!user_private) + throw "User not logged in"; + else if (user_private instanceof Function) + return user_private(); + else + return user_private; + }, + get db_name() { + return "floDapps#" + user.id; + }, + clear() { + user_id = user_public = user_private = undefined; + raw_user_private = undefined; + delete user.contacts; + delete user.pubKeys; + delete user.messages; + } + }; + + Object.defineProperties(window, { + myFloID: { + get: () => user.id + }, + myPubKey: { + get: () => user.public + }, + myPrivKey: { + get: () => user.private + } + }); + + var subAdmins, settings + Object.defineProperties(floGlobals, { + subAdmins: { + get: () => subAdmins + }, + settings: { + get: () => settings + }, + contacts: { + get: () => user.contacts + }, + pubKeys: { + get: () => user.pubKeys + }, + messages: { + get: () => user.messages + } + }) + function initIndexedDB() { return new Promise((resolve, reject) => { var obs_g = { @@ -32,37 +112,37 @@ if (!(o in obs_a)) obs_a[o] = initIndexedDB.appObs[o] Promise.all([ - compactIDB.initDB(floGlobals.application, obs_a), - compactIDB.initDB("floDapps", obs_g) + compactIDB.initDB(DEFAULT.application, obs_a), + compactIDB.initDB(DEFAULT.root, obs_g) ]).then(result => { - compactIDB.setDefaultDB(floGlobals.application) + compactIDB.setDefaultDB(DEFAULT.application) resolve("IndexedDB App Storage Initated Successfully") }).catch(error => reject(error)); }) } - function initUserDB(floID) { + function initUserDB() { return new Promise((resolve, reject) => { var obs = { contacts: {}, pubKeys: {}, messages: {} } - compactIDB.initDB(`floDapps#${floID}`, obs).then(result => { + compactIDB.initDB(user.db_name, obs).then(result => { resolve("UserDB Initated Successfully") }).catch(error => reject('Init userDB failed')); }) } - function loadUserDB(floID) { + function loadUserDB() { return new Promise((resolve, reject) => { var loadData = ["contacts", "pubKeys", "messages"] var promises = [] for (var i = 0; i < loadData.length; i++) - promises[i] = compactIDB.readAllData(loadData[i], `floDapps#${floID}`) + promises[i] = compactIDB.readAllData(loadData[i], user.db_name) Promise.all(promises).then(results => { for (var i = 0; i < loadData.length; i++) - floGlobals[loadData[i]] = results[i] + user[loadData[i]] = results[i] resolve("Loaded Data from userDB") }).catch(error => reject('Load userDB failed')) }) @@ -72,7 +152,7 @@ startUpFunctions.push(function readSupernodeListFromAPI() { return new Promise((resolve, reject) => { - compactIDB.readData("lastTx", floCloudAPI.SNStorageID, "floDapps").then(lastTx => { + compactIDB.readData("lastTx", floCloudAPI.SNStorageID, DEFAULT.root).then(lastTx => { floBlockchainAPI.readData(floCloudAPI.SNStorageID, { ignoreOld: lastTx, sentOnly: true, @@ -81,12 +161,12 @@ for (var i = result.data.length - 1; i >= 0; i--) { var content = JSON.parse(result.data[i]).SuperNodeStorage; for (sn in content.removeNodes) - compactIDB.removeData("supernodes", sn, "floDapps"); + compactIDB.removeData("supernodes", sn, DEFAULT.root); for (sn in content.newNodes) - compactIDB.writeData("supernodes", content.newNodes[sn], sn, "floDapps"); + compactIDB.writeData("supernodes", content.newNodes[sn], sn, DEFAULT.root); } - compactIDB.writeData("lastTx", result.totalTxs, floCloudAPI.SNStorageID, "floDapps"); - compactIDB.readAllData("supernodes", "floDapps").then(result => { + compactIDB.writeData("lastTx", result.totalTxs, floCloudAPI.SNStorageID, DEFAULT.root); + compactIDB.readAllData("supernodes", DEFAULT.root).then(result => { floCloudAPI.init(result) .then(result => resolve("Loaded Supernode list\n" + result)) .catch(error => reject(error)) @@ -98,14 +178,14 @@ startUpFunctions.push(function readAppConfigFromAPI() { return new Promise((resolve, reject) => { - compactIDB.readData("lastTx", `${floGlobals.application}|${floGlobals.adminID}`, "floDapps").then(lastTx => { - floBlockchainAPI.readData(floGlobals.adminID, { + compactIDB.readData("lastTx", `${DEFAULT.application}|${DEFAULT.adminID}`, DEFAULT.root).then(lastTx => { + floBlockchainAPI.readData(DEFAULT.adminID, { ignoreOld: lastTx, sentOnly: true, - pattern: floGlobals.application + pattern: DEFAULT.application }).then(result => { for (var i = result.data.length - 1; i >= 0; i--) { - var content = JSON.parse(result.data[i])[floGlobals.application]; + var content = JSON.parse(result.data[i])[DEFAULT.application]; if (!content || typeof content !== "object") continue; if (Array.isArray(content.removeSubAdmin)) @@ -118,11 +198,11 @@ for (let l in content.settings) compactIDB.writeData("settings", content.settings[l], l) } - compactIDB.writeData("lastTx", result.totalTxs, `${floGlobals.application}|${floGlobals.adminID}`, "floDapps"); + compactIDB.writeData("lastTx", result.totalTxs, `${DEFAULT.application}|${DEFAULT.adminID}`, DEFAULT.root); compactIDB.readAllData("subAdmins").then(result => { - floGlobals.subAdmins = Object.keys(result); + subAdmins = Object.keys(result); compactIDB.readAllData("settings").then(result => { - floGlobals.settings = result; + settings = result; resolve("Read app configuration from blockchain"); }) }) @@ -153,7 +233,7 @@ resolve(inputVal) }); - function getCredentials() { + function getCredentials(invisible_key) { const readSharesFromIDB = indexArr => new Promise((resolve, reject) => { var promises = [] @@ -186,7 +266,7 @@ }); const getPrivateKeyCredentials = () => new Promise((resolve, reject) => { - var indexArr = localStorage.getItem(`${floGlobals.application}#privKey`) + var indexArr = localStorage.getItem(`${DEFAULT.application}#privKey`) if (indexArr) { readSharesFromIDB(JSON.parse(indexArr)) .then(result => resolve(result)) @@ -210,7 +290,7 @@ var shares = floCrypto.createShamirsSecretShares(privKey, threshold, threshold) writeSharesToIDB(shares).then(resultIndexes => { //store index keys in localStorage - localStorage.setItem(`${floGlobals.application}#privKey`, JSON.stringify(resultIndexes)) + localStorage.setItem(`${DEFAULT.application}#privKey`, JSON.stringify(resultIndexes)) //also add a dummy privatekey to the IDB var randomPrivKey = floCrypto.generateNewID().privKey var randomThreshold = floCrypto.randInt(10, 20) @@ -242,9 +322,13 @@ getPrivateKeyCredentials().then(key => { checkIfPinRequired(key).then(privKey => { try { - myPrivKey = privKey - myPubKey = floCrypto.getPubKeyHex(myPrivKey) - myFloID = floCrypto.getFloID(myPubKey) + user_public = floCrypto.getPubKeyHex(privKey); + user_id = floCrypto.getFloID(privKey); + floCloudAPI.user = privKey; //Set user for floCloudAPI + if (!invisible_key) + user_private = privKey; + else + user_private = () => checkIfPinRequired(key); resolve('Login Credentials loaded successful') } catch (error) { console.log(error) @@ -289,7 +373,7 @@ }) }); - floDapps.launchStartUp = function() { + floDapps.launchStartUp = function(options = {}) { return new Promise((resolve, reject) => { initIndexedDB().then(log => { console.log(log) @@ -304,9 +388,9 @@ }) }); let p2 = new Promise((res, rej) => { - callAndLog(getCredentials()).then(r => { - callAndLog(initUserDB(myFloID)).then(r => { - callAndLog(loadUserDB(myFloID)) + callAndLog(getCredentials(options.invisible_key)).then(r => { + callAndLog(initUserDB()).then(r => { + callAndLog(loadUserDB()) .then(r => res(true)) .catch(e => rej(false)) }).catch(e => rej(false)) @@ -333,8 +417,8 @@ return new Promise((resolve, reject) => { if (!floCrypto.validateAddr(floID)) return reject("Invalid floID!") - compactIDB.writeData("contacts", name, floID, `floDapps#${myFloID}`).then(result => { - floGlobals.contacts[floID] = name; + compactIDB.writeData("contacts", name, floID, user.db_name).then(result => { + user.contacts[floID] = name; resolve("Contact stored") }).catch(error => reject(error)) }); @@ -342,14 +426,14 @@ floDapps.storePubKey = function(floID, pubKey) { return new Promise((resolve, reject) => { - if (floID in floGlobals.pubKeys) + if (floID in user.pubKeys) return resolve("pubKey already stored") if (!floCrypto.validateAddr(floID)) return reject("Invalid floID!") if (floCrypto.getFloID(pubKey) != floID) return reject("Incorrect pubKey") - compactIDB.writeData("pubKeys", pubKey, floID, `floDapps#${myFloID}`).then(result => { - floGlobals.pubKeys[floID] = pubKey; + compactIDB.writeData("pubKeys", pubKey, floID, user.db_name).then(result => { + user.pubKeys[floID] = pubKey; resolve("pubKey stored") }).catch(error => reject(error)) }); @@ -359,11 +443,11 @@ return new Promise((resolve, reject) => { let options = { receiverID: floID, - application: "floDapps", - comment: floGlobals.application + application: DEFAULT.root, + comment: DEFAULT.application } - if (floID in floGlobals.pubKeys) - message = floCrypto.encryptData(JSON.stringify(message), floGlobals.pubKeys[floID]) + if (floID in user.pubKeys) + message = floCrypto.encryptData(JSON.stringify(message), user.pubKeys[floID]) floCloudAPI.sendApplicationData(message, "Message", options) .then(result => resolve(result)) .catch(error => reject(error)) @@ -372,20 +456,21 @@ floDapps.requestInbox = function(callback) { return new Promise((resolve, reject) => { - let lastVC = Object.keys(floGlobals.messages).sort().pop() + let lastVC = Object.keys(user.messages).sort().pop() let options = { - receiverID: myFloID, - application: "floDapps", + receiverID: user.id, + application: DEFAULT.root, lowerVectorClock: lastVC + 1 } + let privKey = raw_user.private; options.callback = (d, e) => { for (let v in d) { try { if (d[v].message instanceof Object && "secret" in d[v].message) - d[v].message = floCrypto.decryptData(d[v].message, myPrivKey) + d[v].message = floCrypto.decryptData(d[v].message, privKey) } catch (error) {} - compactIDB.writeData("messages", d[v], v, `floDapps#${myFloID}`) - floGlobals.messages[v] = d[v] + compactIDB.writeData("messages", d[v], v, user.db_name) + user.messages[v] = d[v] } if (callback instanceof Function) callback(d, e) @@ -404,14 +489,14 @@ if (!addList && !rmList && !settings) return reject("No configuration change") var floData = { - [floGlobals.application]: { + [DEFAULT.application]: { addSubAdmin: addList, removeSubAdmin: rmList, settings: settings } } var floID = floCrypto.getFloID(adminPrivKey) - if (floID != floGlobals.adminID) + if (floID != DEFAULT.adminID) reject('Access Denied for Admin privilege') else floBlockchainAPI.writeData(floID, JSON.stringify(floData), adminPrivKey) @@ -422,9 +507,9 @@ const clearCredentials = floDapps.clearCredentials = function() { return new Promise((resolve, reject) => { - compactIDB.clearData('credentials', floGlobals.application).then(result => { - localStorage.removeItem(`${floGlobals.application}#privKey`) - myPrivKey = myPubKey = myFloID = undefined; + compactIDB.clearData('credentials', DEFAULT.application).then(result => { + localStorage.removeItem(`${DEFAULT.application}#privKey`); + user.clear(); resolve("privKey credentials deleted!") }).catch(error => reject(error)) }) @@ -433,7 +518,7 @@ floDapps.deleteUserData = function(credentials = false) { return new Promise((resolve, reject) => { let p = [] - p.push(compactIDB.deleteDB(`floDapps#${myFloID}`)) + p.push(compactIDB.deleteDB(user.db_name)) if (credentials) p.push(clearCredentials()) Promise.all(p) @@ -444,10 +529,10 @@ floDapps.deleteAppData = function() { return new Promise((resolve, reject) => { - compactIDB.deleteDB(floGlobals.application).then(result => { - localStorage.removeItem(`${floGlobals.application}#privKey`) - myPrivKey = myPubKey = myFloID = undefined; - compactIDB.removeData('lastTx', `${floGlobals.application}|${floGlobals.adminID}`, 'floDapps') + compactIDB.deleteDB(DEFAULT.application).then(result => { + localStorage.removeItem(`${DEFAULT.application}#privKey`) + user.clear(); + compactIDB.removeData('lastTx', `${DEFAULT.application}|${DEFAULT.adminID}`, DEFAULT.root) .then(result => resolve("App database(local) deleted")) .catch(error => reject(error)) }).catch(error => reject(error)) @@ -455,17 +540,17 @@ } floDapps.securePrivKey = function(pwd) { - return new Promise((resolve, reject) => { - let indexArr = localStorage.getItem(`${floGlobals.application}#privKey`) + return new Promise(async (resolve, reject) => { + let indexArr = localStorage.getItem(`${DEFAULT.application}#privKey`) if (!indexArr) return reject("PrivKey not found"); indexArr = JSON.parse(indexArr) - let encryptedKey = Crypto.AES.encrypt(myPrivKey, pwd); + let encryptedKey = Crypto.AES.encrypt(await user.private, pwd); let threshold = indexArr.length; let shares = floCrypto.createShamirsSecretShares(encryptedKey, threshold, threshold) let promises = []; let overwriteFn = (share, index) => - compactIDB.writeData("credentials", share, index, floGlobals.application); + compactIDB.writeData("credentials", share, index, DEFAULT.application); for (var i = 0; i < threshold; i++) promises.push(overwriteFn(shares[i], indexArr[i])); Promise.all(promises) @@ -494,7 +579,7 @@ }) } return new Promise((resolve, reject) => { - var indexArr = localStorage.getItem(`${floGlobals.application}#privKey`) + var indexArr = localStorage.getItem(`${DEFAULT.application}#privKey`) console.info(indexArr) if (!indexArr) reject('No login credentials found') @@ -535,7 +620,7 @@ filteredResult[d] = JSON.parse(JSON.stringify(floGlobals.generalData[fk][d])) } if (options.decrypt) { - let decryptionKey = (options.decrypt === true) ? myPrivKey : options.decrypt; + let decryptionKey = (options.decrypt === true) ? raw_user.private : options.decrypt; if (!Array.isArray(decryptionKey)) decryptionKey = [decryptionKey]; for (let f in filteredResult) { @@ -561,14 +646,14 @@ syncData.oldDevice = () => new Promise((resolve, reject) => { let sync = { - contacts: floGlobals.contacts, - pubKeys: floGlobals.pubKeys, - messages: floGlobals.messages + contacts: user.contacts, + pubKeys: user.pubKeys, + messages: user.messages } - let message = Crypto.AES.encrypt(JSON.stringify(sync), myPrivKey) + let message = Crypto.AES.encrypt(JSON.stringify(sync), raw_user.private) let options = { - receiverID: myFloID, - application: "floDapps" + receiverID: user.id, + application: DEFAULT.root } floCloudAPI.sendApplicationData(message, "syncData", options) .then(result => resolve(result)) @@ -577,20 +662,20 @@ syncData.newDevice = () => new Promise((resolve, reject) => { var options = { - receiverID: myFloID, - senderID: myFloID, - application: "floDapps", + receiverID: user.id, + senderID: user.id, + application: DEFAULT.root, mostRecent: true, } floCloudAPI.requestApplicationData("syncData", options).then(response => { let vc = Object.keys(response).sort().pop() - let sync = JSON.parse(Crypto.AES.decrypt(response[vc].message, myPrivKey)) + let sync = JSON.parse(Crypto.AES.decrypt(response[vc].message, raw_user.private)) let promises = [] - let store = (key, val, obs) => promises.push(compactIDB.writeData(obs, val, key, `floDapps#${floID}`)); + let store = (key, val, obs) => promises.push(compactIDB.writeData(obs, val, key, user.db_name)); ["contacts", "pubKeys", "messages"].forEach(c => { for (let i in sync[c]) { store(i, sync[c][i], c) - floGlobals[c][i] = sync[c][i] + user[c][i] = sync[c][i] } }) Promise.all(promises) diff --git a/index.html b/index.html index 03ee1ba..c1999d7 100644 --- a/index.html +++ b/index.html @@ -24,8 +24,7 @@ //floDapps.addStartUpFunction('Sample', Promised Function) //floDapps.setAppObjectStores({sampleObs1:{}, sampleObs2:{options{autoIncrement:true, keyPath:'SampleKey'}, Indexes:{sampleIndex:{}}}}) //floDapps.setCustomPrivKeyInput( () => { FUNCTION BODY *must resolve private key* } ) - - floDapps.launchStartUp().then(result => { + floDapps.launchStartUp( /*{invisible_key: true}*/ ).then(result => { console.log(result) alert(`Welcome FLO_ID: ${myFloID}`) //App functions.... From 5ab0bc36f010fc9537826954c2677d69ccd8f515 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sat, 16 Jul 2022 03:32:44 +0530 Subject: [PATCH 199/289] Update floCrypto.js - Removing explicit use of BigInteger in signing(/verify-sign) data --- floCrypto.js | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/floCrypto.js b/floCrypto.js index 4ab4d5c..7be6c5a 100644 --- a/floCrypto.js +++ b/floCrypto.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCrypto v2.3.0a +(function(EXPORTS) { //floCrypto v2.3.1 /* FLO Crypto Operators */ 'use strict'; const floCrypto = EXPORTS; @@ -121,12 +121,8 @@ //Sign data using private-key floCrypto.signData = function(data, privateKeyHex) { var key = new Bitcoin.ECKey(privateKeyHex); - key.setCompressed(true); - var privateKeyArr = key.getBitcoinPrivateKeyByteArray(); - var privateKey = BigInteger.fromByteArrayUnsigned(privateKeyArr); var messageHash = Crypto.SHA256(data); - var messageHashBigInteger = new BigInteger(messageHash); - var messageSign = Bitcoin.ECDSA.sign(messageHashBigInteger, key.priv); + var messageSign = Bitcoin.ECDSA.sign(messageHash, key.priv); var sighex = Crypto.util.bytesToHex(messageSign); return sighex; } @@ -134,11 +130,9 @@ //Verify signatue of the data using public-key floCrypto.verifySign = function(data, signatureHex, publicKeyHex) { var msgHash = Crypto.SHA256(data); - var messageHashBigInteger = new BigInteger(msgHash); var sigBytes = Crypto.util.hexToBytes(signatureHex); - var signature = Bitcoin.ECDSA.parseSig(sigBytes); var publicKeyPoint = ecparams.getCurve().decodePointHex(publicKeyHex); - var verify = Bitcoin.ECDSA.verifyRaw(messageHashBigInteger, signature.r, signature.s, publicKeyPoint); + var verify = Bitcoin.ECDSA.verify(msgHash, sigBytes, publicKeyPoint); return verify; } From b80bd43313397af1c92669c0dc656ba281cab5ac Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 17 Jul 2022 17:02:27 +0530 Subject: [PATCH 200/289] floDapps, floCloudAPI: Secure private key - Store AES-encrypted private key in memory. (exploring memory of browser will not have raw private key) - floDapps lock/unlock (in user): locks or unlock the private key (ie, lock= Password required, unlock= password not required in returning private key) - floDapps.launchStartUp now accepts options object - to lock the private key on startup, pass {lock_key: true} in options objects of launchStartUp --- floCloudAPI.js | 19 +++++++++++-------- floDapps.js | 33 ++++++++++++++++++++++----------- index.html | 2 +- 3 files changed, 34 insertions(+), 20 deletions(-) diff --git a/floCloudAPI.js b/floCloudAPI.js index e06ba60..9501ed9 100644 --- a/floCloudAPI.js +++ b/floCloudAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCloudAPI v2.4.0 +(function(EXPORTS) { //floCloudAPI v2.4.1 /* FLO Cloud operations to send/request application data*/ 'use strict'; const floCloudAPI = EXPORTS; @@ -10,7 +10,7 @@ callback: (d, e) => console.debug(d, e) }; - var user_id, user_public, user_private; + var user_id, user_public, user_private, aes_key; const user = { get id() { if (!user_id) @@ -25,10 +25,10 @@ sign(msg) { if (!user_private) throw "User not set"; - return floCrypto.signData(msg, user_private); + return floCrypto.signData(msg, Crypto.AES.decrypt(user_private, aes_key)); }, clear() { - user_id = user_public = user_private = undefined; + user_id = user_public = user_private = aes_key = undefined; } } @@ -45,14 +45,17 @@ user: { set: priv => { if (!priv) - user_id = user_public = user_private = undefined; + user_id = user_public = user_private = aes_key = undefined; else { user_public = floCrypto.getPubKeyHex(priv); user_id = floCrypto.getFloID(user_public); if (!user_public || !user_id || !floCrypto.verifyPrivKey(priv, user_id)) - user_id = user_public = user_private = undefined; - else - user_private = priv; + user_id = user_public = user_private = aes_key = undefined; + else { + let n = floCrypto.randInt(12, 20); + aes_key = floCrypto.randString(n); + user_private = Crypto.AES.encrypt(priv, aes_key); + } } }, get: () => user diff --git a/floDapps.js b/floDapps.js index 08e3dd4..157b37d 100644 --- a/floDapps.js +++ b/floDapps.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floDapps v2.3.0 +(function(EXPORTS) { //floDapps v2.3.1 /* General functions for FLO Dapps*/ 'use strict'; const floDapps = EXPORTS; @@ -11,12 +11,12 @@ adminID: floGlobals.adminID }; - var raw_user_private; //private variable inside capsule + var user_priv_raw, aes_key, user_priv_wrap; //private variable inside capsule const raw_user = { get private() { - if (!raw_user_private) + if (!user_priv_raw) throw "User not logged in"; - return raw_user_private; + return Crypto.AES.decrypt(user_priv_raw, aes_key); } } @@ -38,14 +38,21 @@ else if (user_private instanceof Function) return user_private(); else - return user_private; + return Crypto.AES.decrypt(user_private, aes_key); }, get db_name() { return "floDapps#" + user.id; }, + lock() { + user_private = user_priv_wrap; + }, + async unlock() { + if (await user.private === raw_user.private) + user_private = user_priv_raw; + }, clear() { user_id = user_public = user_private = undefined; - raw_user_private = undefined; + user_priv_raw = aes_key = undefined; delete user.contacts; delete user.pubKeys; delete user.messages; @@ -233,7 +240,7 @@ resolve(inputVal) }); - function getCredentials(invisible_key) { + function getCredentials(lock_key) { const readSharesFromIDB = indexArr => new Promise((resolve, reject) => { var promises = [] @@ -325,10 +332,14 @@ user_public = floCrypto.getPubKeyHex(privKey); user_id = floCrypto.getFloID(privKey); floCloudAPI.user = privKey; //Set user for floCloudAPI - if (!invisible_key) - user_private = privKey; + user_priv_wrap = () => checkIfPinRequired(key); + let n = floCrypto.randInt(12, 20); + aes_key = floCrypto.randString(n); + user_priv_raw = Crypto.AES.encrypt(privKey, aes_key); + if (!lock_key) + user_private = user_priv_raw; else - user_private = () => checkIfPinRequired(key); + user_private = user_priv_wrap; resolve('Login Credentials loaded successful') } catch (error) { console.log(error) @@ -388,7 +399,7 @@ }) }); let p2 = new Promise((res, rej) => { - callAndLog(getCredentials(options.invisible_key)).then(r => { + callAndLog(getCredentials(options.lock_key)).then(r => { callAndLog(initUserDB()).then(r => { callAndLog(loadUserDB()) .then(r => res(true)) diff --git a/index.html b/index.html index c1999d7..cef876c 100644 --- a/index.html +++ b/index.html @@ -24,7 +24,7 @@ //floDapps.addStartUpFunction('Sample', Promised Function) //floDapps.setAppObjectStores({sampleObs1:{}, sampleObs2:{options{autoIncrement:true, keyPath:'SampleKey'}, Indexes:{sampleIndex:{}}}}) //floDapps.setCustomPrivKeyInput( () => { FUNCTION BODY *must resolve private key* } ) - floDapps.launchStartUp( /*{invisible_key: true}*/ ).then(result => { + floDapps.launchStartUp( /*{lock_key: true}*/ ).then(result => { console.log(result) alert(`Welcome FLO_ID: ${myFloID}`) //App functions.... From fcc5f3ce4e6248b06d641a41b6a6e5f8f79f03a5 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 17 Jul 2022 17:04:03 +0530 Subject: [PATCH 201/289] Edit library to accept WIF of other versions --- .gitignore | 1 + lib.js | 17 ++++++++++------- 2 files changed, 11 insertions(+), 7 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..168b657 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.tmp* \ No newline at end of file diff --git a/lib.js b/lib.js index 80afa89..c6684f7 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function(GLOBAL) { //lib v1.2.2a +(function(GLOBAL) { //lib v1.2.3 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -5016,12 +5016,12 @@ * * Returns the address as a base58-encoded string in the standardized format. */ - Bitcoin.Address.prototype.toString = function() { + Bitcoin.Address.prototype.toString = function(version = null) { // Get a copy of the hash var hash = this.hash.slice(0); // Version - hash.unshift(this.version); + hash.unshift(version !== null ? version : this.version); var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { @@ -5130,7 +5130,7 @@ } var Q; - if (pubkey instanceof ec.PointFp) { + if (pubkey instanceof EllipticCurve.PointFp) { Q = pubkey; } else if (Bitcoin.Util.isArray(pubkey)) { Q = EllipticCurve.PointFp.decodeFrom(ecparams.getCurve(), pubkey); @@ -5444,9 +5444,8 @@ var bytes = null; try { - // This part is edited for FLO. FLO WIF are always compressed WIF. FLO WIF (private key) starts with R for mainnet and c for testnet. - if (((GLOBAL.cryptocoin == "FLO") && /^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(input)) || - ((GLOBAL.cryptocoin == "FLO_TEST") && /^c[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(input))) { + // This part is edited for FLO. FLO WIF are always compressed WIF (length of 52). + if ((/^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{52}$/.test(input))) { bytes = ECKey.decodeCompressedWalletImportFormat(input); this.compressed = true; } else if (ECKey.isHexFormat(input)) { @@ -5673,9 +5672,11 @@ } var version = hash.shift(); + /* if (version != ECKey.privateKeyPrefix) { throw "Version " + version + " not supported!"; } + */ return hash; }; @@ -5697,9 +5698,11 @@ throw "Checksum validation failed!"; } var version = hash.shift(); + /* if (version != ECKey.privateKeyPrefix) { throw "Version " + version + " not supported!"; } + */ hash.pop(); return hash; }; From 0a74e393ed9c10f0a4cd8755d4e3cec0675e088c Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 19 Jul 2022 21:21:06 +0530 Subject: [PATCH 202/289] floCrypto v2.3.2: validate any address floCrypto.validateAddr: validate any blockchain address - Parameters: 1. address - address to validate 2. std - checks for legacy version (optional, default=true) (true: allow any, array: list of versions, value: one version only, false: allow none) 3. bech - checks for bech version (optional, default=false) (true: allow any, array: list of versions, value: one version only, false: allow none) - For validating only floID, use floCrypto.validateFloID(floID) --- README.md | 12 ++++++++++-- floBlockchainAPI.js | 10 +++++----- floCrypto.js | 46 ++++++++++++++++++++++++++++++++++++++++----- floDapps.js | 8 ++++---- 4 files changed, 60 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 536a71a..da60c69 100644 --- a/README.md +++ b/README.md @@ -216,9 +216,17 @@ In addition, we have these system variables outside FLO Globals but used globall 3. isfloID - boolean value (true: compare as flo ID, false: compare as public key) (optional, default is true) * Returns : boolen (true or false) +#### Validate Address + floCrypto.validateAddr(address, *std, *bech) +`validateAddr` check if the given Address (any blockchain) is valid or not +1. address - address to validate +2. std - checks for legacy version (optional, default=true) (true: allow any, array: list of versions, value: one version only, false: allow none) +3. bech - checks for bech version (optional, default=false) (true: allow any, array: list of versions, value: one version only, false: allow none) [requires additional library: [btc_api](https://ranchimall.github.io/btc-webwallet/lib_btc.js)] +* Returns : boolen (true or false) + #### Validate FLO ID - floCrypto.validateAddr(floID) -`validateAddr` check if the given Address is valid or not + floCrypto.validateFloID(floID) +`validateFloID` check if the given floID is valid or not 1. floID - flo ID to validate * Returns : boolen (true or false) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index fcc73b9..8cf3a79 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floBlockchainAPI v2.3.3 +(function(EXPORTS) { //floBlockchainAPI v2.3.3a /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -125,9 +125,9 @@ return new Promise((resolve, reject) => { if (!floCrypto.validateASCII(floData)) return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); - else if (!floCrypto.validateAddr(senderAddr)) + else if (!floCrypto.validateFloID(senderAddr)) return reject(`Invalid address : ${senderAddr}`); - else if (!floCrypto.validateAddr(receiverAddr)) + else if (!floCrypto.validateFloID(receiverAddr)) return reject(`Invalid address : ${receiverAddr}`); else if (privKey.length < 1 || !floCrypto.verifyPrivKey(privKey, senderAddr)) return reject("Invalid Private key!"); @@ -202,7 +202,7 @@ //merge all UTXOs of a given floID into a single UTXO floBlockchainAPI.mergeUTXOs = function(floID, privKey, floData = '') { return new Promise((resolve, reject) => { - if (!floCrypto.validateAddr(floID)) + if (!floCrypto.validateFloID(floID)) return reject(`Invalid floID`); if (!floCrypto.verifyPrivKey(privKey, floID)) return reject("Invalid Private Key"); @@ -326,7 +326,7 @@ } //Validate the receiver IDs and receive amount for (let floID in receivers) { - if (!floCrypto.validateAddr(floID)) + if (!floCrypto.validateFloID(floID)) invalids.InvalidReceiverIDs.push(floID); if (typeof receivers[floID] !== 'number' || receivers[floID] <= 0) invalids.InvalidReceiveAmountFor.push(floID); diff --git a/floCrypto.js b/floCrypto.js index 7be6c5a..1c47628 100644 --- a/floCrypto.js +++ b/floCrypto.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCrypto v2.3.1 +(function(EXPORTS) { //floCrypto v2.3.2 /* FLO Crypto Operators */ 'use strict'; const floCrypto = EXPORTS; @@ -196,18 +196,54 @@ } } - //Check if the given Address is valid or not - floCrypto.validateFloID = floCrypto.validateAddr = function(inpAddr) { - if (!inpAddr) + //Check if the given flo-id is valid or not + floCrypto.validateFloID = function(floID) { + if (!floID) return false; try { - let addr = new Bitcoin.Address(inpAddr); + let addr = new Bitcoin.Address(floID); return true; } catch { return false; } } + //Check if the given address (any blockchain) is valid or not + floCrypto.validateAddr = function(address, std = true, bech = false) { + if (address.length == 34) { //legacy or segwit encoding + if (std === false) + return false; + let decode = bitjs.Base58.decode(address); + var raw = decode.slice(0, decode.length - 4), + checksum = decode.slice(decode.length - 4); + var hash = Crypto.SHA256(Crypto.SHA256(raw, { + asBytes: true + }), { + asBytes: true + }); + if (hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3]) + return false; + else if (std === true || (!Array.isArray(std) && std === raw[0]) || (Array.isArray(std) && std.includes(raw[0]))) + return true; + else + return false; + } else if (address.length == 42 || address.length == 62) { //bech encoding + if (bech === false) + return false; + else if (typeof btc_api !== "object") + throw "btc_api library missing (lib_btc.js)"; + let decode = coinjs.bech32_decode(address); + if (!decode) + return false; + var raw = decode.data; + if (bech === true || (!Array.isArray(bech) && bech === raw[0]) || (Array.isArray(bech) && bech.includes(raw[0]))) + return true; + else + return false; + } else //unknown length + return false; + } + //Split the str using shamir's Secret and Returns the shares floCrypto.createShamirsSecretShares = function(str, total_shares, threshold_limit) { try { diff --git a/floDapps.js b/floDapps.js index 157b37d..e25ecf0 100644 --- a/floDapps.js +++ b/floDapps.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floDapps v2.3.1 +(function(EXPORTS) { //floDapps v2.3.1a /* General functions for FLO Dapps*/ 'use strict'; const floDapps = EXPORTS; @@ -284,7 +284,7 @@ if (!result) return reject("Empty Private Key") var floID = floCrypto.getFloID(result) - if (!floID || !floCrypto.validateAddr(floID)) + if (!floID || !floCrypto.validateFloID(floID)) return reject("Invalid Private Key") privKey = result; }).catch(error => { @@ -426,7 +426,7 @@ floDapps.storeContact = function(floID, name) { return new Promise((resolve, reject) => { - if (!floCrypto.validateAddr(floID)) + if (!floCrypto.validateFloID(floID)) return reject("Invalid floID!") compactIDB.writeData("contacts", name, floID, user.db_name).then(result => { user.contacts[floID] = name; @@ -439,7 +439,7 @@ return new Promise((resolve, reject) => { if (floID in user.pubKeys) return resolve("pubKey already stored") - if (!floCrypto.validateAddr(floID)) + if (!floCrypto.validateFloID(floID)) return reject("Invalid floID!") if (floCrypto.getFloID(pubKey) != floID) return reject("Incorrect pubKey") From fa3d790c6c3bacccc0c4fb088e76b5ae2867619a Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 24 Jul 2022 02:29:04 +0530 Subject: [PATCH 203/289] floDapps v2.3.2: lock privkey by default - Removed the options for launchStartUp - private-key is on lock mode by default - Added utility functions that uses private-key without entering password in .user .sign(message): signs message .decrypt(data): decrypts ciphertext in asymmetric .encipher(message): encrypts message in symmetric .decipher(data): decrypts ciphertext in symmetric --- floDapps.js | 25 +++++++++++++++++-------- index.html | 2 +- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/floDapps.js b/floDapps.js index e25ecf0..e5e2d6d 100644 --- a/floDapps.js +++ b/floDapps.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floDapps v2.3.1a +(function(EXPORTS) { //floDapps v2.3.2 /* General functions for FLO Dapps*/ 'use strict'; const floDapps = EXPORTS; @@ -40,6 +40,18 @@ else return Crypto.AES.decrypt(user_private, aes_key); }, + sign(message) { + return floCrypto.signData(message, raw_user.private); + }, + decrypt(data) { + return floCrypto.decryptData(data, raw_user.private); + }, + encipher(message) { + return Crypto.AES.encrypt(message, raw_user.private); + }, + decipher(data) { + return Crypto.AES.decrypt(data, raw_user.private); + }, get db_name() { return "floDapps#" + user.id; }, @@ -240,7 +252,7 @@ resolve(inputVal) }); - function getCredentials(lock_key) { + function getCredentials() { const readSharesFromIDB = indexArr => new Promise((resolve, reject) => { var promises = [] @@ -336,10 +348,7 @@ let n = floCrypto.randInt(12, 20); aes_key = floCrypto.randString(n); user_priv_raw = Crypto.AES.encrypt(privKey, aes_key); - if (!lock_key) - user_private = user_priv_raw; - else - user_private = user_priv_wrap; + user_private = user_priv_wrap; resolve('Login Credentials loaded successful') } catch (error) { console.log(error) @@ -384,7 +393,7 @@ }) }); - floDapps.launchStartUp = function(options = {}) { + floDapps.launchStartUp = function() { return new Promise((resolve, reject) => { initIndexedDB().then(log => { console.log(log) @@ -399,7 +408,7 @@ }) }); let p2 = new Promise((res, rej) => { - callAndLog(getCredentials(options.lock_key)).then(r => { + callAndLog(getCredentials()).then(r => { callAndLog(initUserDB()).then(r => { callAndLog(loadUserDB()) .then(r => res(true)) diff --git a/index.html b/index.html index cef876c..2b60d9d 100644 --- a/index.html +++ b/index.html @@ -24,7 +24,7 @@ //floDapps.addStartUpFunction('Sample', Promised Function) //floDapps.setAppObjectStores({sampleObs1:{}, sampleObs2:{options{autoIncrement:true, keyPath:'SampleKey'}, Indexes:{sampleIndex:{}}}}) //floDapps.setCustomPrivKeyInput( () => { FUNCTION BODY *must resolve private key* } ) - floDapps.launchStartUp( /*{lock_key: true}*/ ).then(result => { + floDapps.launchStartUp().then(result => { console.log(result) alert(`Welcome FLO_ID: ${myFloID}`) //App functions.... From 0526a1f29f0a609bbbbec19f2cdea3f014722d9d Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 24 Jul 2022 02:34:02 +0530 Subject: [PATCH 204/289] floCloudAPI v2.4.2: cross-blockchain receiverID - Accept any blockchain ID as receiverID and automatically convert it into floID --- floCloudAPI.js | 57 ++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 51 insertions(+), 6 deletions(-) diff --git a/floCloudAPI.js b/floCloudAPI.js index 9501ed9..3a06e0b 100644 --- a/floCloudAPI.js +++ b/floCloudAPI.js @@ -1,9 +1,10 @@ -(function(EXPORTS) { //floCloudAPI v2.4.1 +(function(EXPORTS) { //floCloudAPI v2.4.2 /* FLO Cloud operations to send/request application data*/ 'use strict'; const floCloudAPI = EXPORTS; const DEFAULT = { + blockchainPrefix: 0x23, //Prefix version for FLO blockchain SNStorageID: floGlobals.SNStorageID || "FNaN9McoBAEFUjkRmNQRYLmBF8SpS7Tgfk", adminID: floGlobals.adminID, application: floGlobals.application, @@ -369,10 +370,54 @@ const filterKey = util.filterKey = function(type, options) { return type + (options.comment ? ':' + options.comment : '') + - '|' + (options.group || options.receiverID || DEFAULT.adminID) + + '|' + (options.group || toFloID(options.receiverID) || DEFAULT.adminID) + '|' + (options.application || DEFAULT.application); } + const toFloID = util.toFloID = function(address) { + if (!address) + return; + var bytes; + if (address.length == 34) { //legacy encoding + let decode = bitjs.Base58.decode(address); + bytes = decode.slice(0, decode.length - 4); + let checksum = decode.slice(decode.length - 4), + hash = Crypto.SHA256(Crypto.SHA256(bytes, { + asBytes: true + }), { + asBytes: true + }); + hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3] ? + bytes = undefined : bytes.shift(); + } else if (address.length == 42 || address.length == 62) { //bech encoding + if (!(coinjs instanceof Object)) + throw "library missing (lib_btc.js)"; + let decode = coinjs.bech32_decode(address); + if (decode) { + bytes = decode.data; + bytes.shift(); + bytes = coinjs.bech32_convert(bytes, 5, 8, false); + if (address.length == 62) //for long bech, aggregate once more to get 160 bit + bytes = coinjs.bech32_convert(bytes, 5, 8, false); + } + } else if (address.length == 66) { //public key hex + bytes = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(address), { + asBytes: true + })); + } + if (!bytes) + throw "Invalid address: " + address; + else { + bytes.unshift(DEFAULT.blockchainPrefix); + let hash = Crypto.SHA256(Crypto.SHA256(bytes, { + asBytes: true + }), { + asBytes: true + }); + return bitjs.Base58.encode(bytes.concat(hash.slice(0, 4))); + } + } + const lastCommit = {}; Object.defineProperty(lastCommit, 'get', { value: objName => JSON.parse(lastCommit[objName]) @@ -474,7 +519,7 @@ return new Promise((resolve, reject) => { var data = { senderID: user.id, - receiverID: options.receiverID || DEFAULT.adminID, + receiverID: toFloID(options.receiverID) || DEFAULT.adminID, pubKey: user.public, message: encodeMessage(message), time: Date.now(), @@ -495,7 +540,7 @@ const requestApplicationData = floCloudAPI.requestApplicationData = function(type, options = {}) { return new Promise((resolve, reject) => { var request = { - receiverID: options.receiverID || DEFAULT.adminID, + receiverID: toFloID(options.receiverID) || DEFAULT.adminID, senderID: options.senderID || undefined, application: options.application || DEFAULT.application, type: type, @@ -600,7 +645,7 @@ if (!floGlobals.subAdmins.includes(user.id)) return reject("Only subAdmins can tag data") var request = { - receiverID: options.receiverID || DEFAULT.adminID, + receiverID: toFloID(options.receiverID) || DEFAULT.adminID, requestorID: user.id, pubKey: user.public, time: Date.now(), @@ -619,7 +664,7 @@ floCloudAPI.noteApplicationData = function(vectorClock, note, options = {}) { return new Promise((resolve, reject) => { var request = { - receiverID: options.receiverID || DEFAULT.adminID, + receiverID: toFloID(options.receiverID) || DEFAULT.adminID, requestorID: user.id, pubKey: user.public, time: Date.now(), From 8a211be84919ee772a9c4137ffc5dcc23a17a549 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 24 Jul 2022 20:33:45 +0530 Subject: [PATCH 205/289] Adding btcOperator module --- btcOperator.js | 324 ++++++ floCrypto.js | 4 +- lib.js | 2558 +++++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 2881 insertions(+), 5 deletions(-) create mode 100644 btcOperator.js diff --git a/btcOperator.js b/btcOperator.js new file mode 100644 index 0000000..f79cdb5 --- /dev/null +++ b/btcOperator.js @@ -0,0 +1,324 @@ +(function(EXPORTS) { //btcOperator v1.0.6 + /* BTC Crypto and API Operator */ + const btcOperator = EXPORTS; + + //This library uses API provided by chain.so (https://chain.so/) + const URL = "https://chain.so/api/v2/"; + + const fetch_api = btcOperator.fetch = function(api) { + return new Promise((resolve, reject) => { + console.debug(URL + api); + fetch(URL + api).then(response => { + response.json() + .then(result => result.status === "success" ? resolve(result) : reject(result)) + .catch(error => reject(error)) + }).catch(error => reject(error)) + }) + }; + + const broadcast = btcOperator.broadcast = rawtx => new Promise((resolve, reject) => { + $.ajax({ + type: "POST", + url: URL + "send_tx/BTC/", + data: { + "tx_hex": rawtx + }, + dataType: "json", + error: e => reject(e.responseJSON), + success: r => r.status === "success" ? resolve(r.data) : reject(r) + }) + }); + + Object.defineProperties(btcOperator, { + newKeys: { + get: () => { + let r = coinjs.newKeys(); + r.segwitAddress = coinjs.segwitAddress(r.pubkey).address; + r.bech32Address = coinjs.bech32Address(r.pubkey).address; + return r; + } + }, + pubkey: { + value: key => key.length >= 66 ? key : (key.length == 64 ? coinjs.newPubkey(key) : coinjs.wif2pubkey(key).pubkey) + }, + address: { + value: (key, prefix = undefined) => coinjs.pubkey2address(btcOperator.pubkey(key), prefix) + }, + segwitAddress: { + value: key => coinjs.segwitAddress(btcOperator.pubkey(key)).address + }, + bech32Address: { + value: key => coinjs.bech32Address(btcOperator.pubkey(key)).address + } + }); + + coinjs.compressed = true; + + const verifyKey = btcOperator.verifyKey = function(addr, key) { + if (!addr || !key) + return undefined; + switch (coinjs.addressDecode(addr).type) { + case "standard": + return btcOperator.address(key) === addr; + case "multisig": + return btcOperator.segwitAddress(key) === addr; + case "bech32": + return btcOperator.bech32Address(key) === addr; + default: + return null; + } + } + + const validateAddress = btcOperator.validateAddress = function(addr) { + if (!addr) + return undefined; + let type = coinjs.addressDecode(addr).type; + if (["standard", "multisig", "bech32"].includes(type)) + return type; + else + return false; + } + + //convert from one blockchain to another blockchain (target version) + btcOperator.convert = {}; + + btcOperator.convert.wif = function(source_wif, target_version = coinjs.priv) { + let keyHex = decodeLegacy(source_wif).hex; + if (!keyHex || keyHex.length < 66 || !/01$/.test(keyHex)) + return null; + else + return encodeLegacy(keyHex, target_version); + } + + btcOperator.convert.legacy2legacy = function(source_addr, target_version = coinjs.pub) { + let rawHex = decodeLegacy(source_addr).hex; + if (!rawHex) + return null; + else + return encodeLegacy(rawHex, target_version); + } + + btcOperator.convert.legacy2bech = function(source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) { + let rawHex = decodeLegacy(source_addr).hex; + if (!rawHex) + return null; + else + return encodeBech32(rawHex, target_version, target_hrp); + } + + btcOperator.convert.bech2bech = function(source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) { + let rawHex = decodeBech32(source_addr).hex; + if (!rawHex) + return null; + else + return encodeBech32(rawHex, target_version, target_hrp); + } + + btcOperator.convert.bech2legacy = function(source_addr, target_version = coinjs.pub) { + let rawHex = decodeBech32(source_addr).hex; + if (!rawHex) + return null; + else + return encodeLegacy(rawHex, target_version); + } + + function decodeLegacy(source) { + var decode = coinjs.base58decode(source); + var raw = decode.slice(0, decode.length - 4), + checksum = decode.slice(decode.length - 4); + var hash = Crypto.SHA256(Crypto.SHA256(raw, { + asBytes: true + }), { + asBytes: true + }); + if (hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3]) + return null; + let version = raw.shift(); + return { + version: version, + hex: Crypto.util.bytesToHex(raw) + } + } + + function encodeLegacy(hex, version) { + var bytes = Crypto.util.hexToBytes(hex); + bytes.unshift(version); + var hash = Crypto.SHA256(Crypto.SHA256(bytes, { + asBytes: true + }), { + asBytes: true + }); + var checksum = hash.slice(0, 4); + return coinjs.base58encode(bytes.concat(checksum)); + } + + function decodeBech32(source) { + let decode = coinjs.bech32_decode(source); + if (!decode) + return null; + var raw = decode.data; + let version = raw.shift(); + raw = coinjs.bech32_convert(raw, 5, 8, false); + return { + hrp: decode.hrp, + version: version, + hex: Crypto.util.bytesToHex(raw) + } + } + + function encodeBech32(hex, version, hrp) { + var bytes = Crypto.util.hexToBytes(hex); + bytes = coinjs.bech32_convert(bytes, 8, 5, true); + bytes.unshift(version) + return coinjs.bech32_encode(hrp, bytes); + } + + //BTC blockchain APIs + + btcOperator.getBalance = addr => new Promise((resolve, reject) => { + fetch_api(`get_address_balance/BTC/${addr}`) + .then(result => resolve(parseFloat(result.data.confirmed_balance))) + .catch(error => reject(error)) + }); + + function _redeemScript(addr, key) { + let decode = coinjs.addressDecode(addr); + switch (decode.type) { + case "standard": + return false; + case "multisig": + return coinjs.segwitAddress(btcOperator.pubkey(key)).redeemscript; + case "bech32": + return decode.redeemscript; + default: + return null; + } + } + + function addUTXOs(tx, senders, redeemScripts, required_amount, n = 0) { + return new Promise((resolve, reject) => { + required_amount = parseFloat(required_amount.toFixed(8)); + if (required_amount <= 0 || n >= senders.length) + return resolve(required_amount); + let addr = senders[n], + rs = redeemScripts[n]; + fetch_api(`get_tx_unspent/BTC/${addr}`).then(result => { + let utxos = result.data.txs; + console.debug("add-utxo", addr, rs, required_amount, utxos); + for (let i = 0; i < utxos.length && required_amount > 0; i++) { + if (!utxos[i].confirmations) //ignore unconfirmed utxo + continue; + required_amount -= parseFloat(utxos[i].value); + var script; + if (rs) { //redeemScript for segwit/bech32 + let s = coinjs.script(); + s.writeBytes(Crypto.util.hexToBytes(rs)); + s.writeOp(0); + s.writeBytes(coinjs.numToBytes((utxos[i].value * 100000000).toFixed(0), 8)); + script = Crypto.util.bytesToHex(s.buffer); + } else //legacy script + script = utxos[i].script_hex; + tx.addinput(utxos[i].txid, utxos[i].output_no, script, 0xfffffffd /*sequence*/ ); //0xfffffffd for Replace-by-fee + } + addUTXOs(tx, senders, redeemScripts, required_amount, n + 1) + .then(result => resolve(result)) + .catch(error => reject(error)) + }).catch(error => reject(error)) + }) + } + + btcOperator.sendTx = function(senders, privkeys, receivers, amounts, fee, change_addr = null) { + return new Promise((resolve, reject) => { + //Add values into array (if single values are passed) + if (!Array.isArray(senders)) + senders = [senders]; + if (!Array.isArray(privkeys)) + privkeys = [privkeys]; + if (!Array.isArray(receivers)) + receivers = [receivers]; + if (!Array.isArray(amounts)) + amounts = [amounts]; + + let invalids = []; + //validate tx-input parameters + if (senders.length != privkeys.length) + return reject("Array length for senders and privkeys should be equal"); + const redeemScripts = [], + wif_keys = []; + for (let i in senders) { + if (!verifyKey(senders[i], privkeys[i])) //verify private-key + invalids.push(senders[i]); + if (privkeys[i].length === 64) //convert Hex to WIF if needed + privkeys[i] = coinjs.privkey2wif(privkeys[i]); + let rs = _redeemScript(senders[i], privkeys[i]); //get redeem-script (segwit/bech32) + redeemScripts.push(rs); + rs === false ? wif_keys.unshift(privkeys[i]) : wif_keys.push(privkeys[i]); //sorting private-keys (wif) + } + if (invalids.length) + return reject("Invalid keys:" + invalids); + if (typeof fee !== "number" || fee <= 0) + return reject("Invalid fee:" + fee); + + //validate tx-output parameters + if (receivers.length != amounts.length) + return reject("Array length for receivers and amounts should be equal"); + let total_amount = 0; + for (let i in receivers) + if (!validateAddress(receivers[i])) + invalids.push(receivers[i]); + if (invalids.length) + return reject("Invalid receivers:" + invalids); + for (let i in amounts) { + if (typeof amounts[i] !== "number" || amounts[i] <= 0) + invalids.push(amounts[i]); + else + total_amount += amounts[i]; + } + if (invalids.length) + return reject("Invalid amounts:" + invalids); + if (change_addr && !validateAddress(change_addr)) + return reject("Invalid change_address:" + change_addr); + + //create transaction + var tx = coinjs.transaction(); + total_amount = parseFloat(total_amount.toFixed(8)); + addUTXOs(tx, senders, redeemScripts, total_amount + fee).then(result => { + if (result > 0) + return reject("Insufficient Balance"); + for (let i in receivers) + tx.addoutput(receivers[i], amounts[i]); + let change = parseFloat(Math.abs(result).toFixed(8)); + if (change > 0) + tx.addoutput(change_addr || senders[0], change); + console.debug("amounts (total, fee, change):", total_amount, fee, change); + console.debug("Unsigned:", tx.serialize()); + new Set(wif_keys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/ ))); //Sign the tx using private key WIF + + console.debug("Signed:", tx.serialize()); + debugger; + broadcast(tx.serialize()) + .then(result => resolve(result)) + .catch(error => reject(error)); + }).catch(error => reject(error)) + }) + }; + + btcOperator.getTx = txid => new Promise((resolve, reject) => { + fetch_api(`get_tx/BTC/${txid}`) + .then(result => resolve(result.data)) + .catch(error => reject(error)) + }); + + btcOperator.getAddressData = addr => new Promise((resolve, reject) => { + fetch_api(`address/BTC/${addr}`) + .then(result => resolve(result.data)) + .catch(error => reject(error)) + }); + + btcOperator.getBlock = block => new Promise((resolve, reject) => { + fetch_api(`get_block/BTC/${block}`) + .then(result => resolve(result.data)) + .catch(error => reject(error)) + }); + +})('object' === typeof module ? module.exports : window.btcOperator = {}); \ No newline at end of file diff --git a/floCrypto.js b/floCrypto.js index 1c47628..064c060 100644 --- a/floCrypto.js +++ b/floCrypto.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCrypto v2.3.2 +(function(EXPORTS) { //floCrypto v2.3.2a /* FLO Crypto Operators */ 'use strict'; const floCrypto = EXPORTS; @@ -230,8 +230,6 @@ } else if (address.length == 42 || address.length == 62) { //bech encoding if (bech === false) return false; - else if (typeof btc_api !== "object") - throw "btc_api library missing (lib_btc.js)"; let decode = coinjs.bech32_decode(address); if (!decode) return false; diff --git a/lib.js b/lib.js index c6684f7..a7e41fe 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function(GLOBAL) { //lib v1.2.3 +(function(GLOBAL) { //lib v1.3.0 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -6017,6 +6017,2561 @@ })("secp256k1"); })(); + //sha512.js + (function() { + /* + A JavaScript implementation of the SHA family of hashes, as defined in FIPS + PUB 180-2 as well as the corresponding HMAC implementation as defined in + FIPS PUB 198a + + Copyright Brian Turek 2008-2012 + Distributed under the BSD License + See http://caligatio.github.com/jsSHA/ for more information + + Several functions taken from Paul Johnson + */ + function n(a) { + throw a; + } + var q = null; + + function s(a, b) { + this.a = a; + this.b = b + } + + function u(a, b) { + var d = [], + h = (1 << b) - 1, + f = a.length * b, + g; + for (g = 0; g < f; g += b) d[g >>> 5] |= (a.charCodeAt(g / b) & h) << 32 - b - g % 32; + return { + value: d, + binLen: f + } + } + + function x(a) { + var b = [], + d = a.length, + h, f; + 0 !== d % 2 && n("String of HEX type must be in byte increments"); + for (h = 0; h < d; h += 2) f = parseInt(a.substr(h, 2), 16), isNaN(f) && n("String of HEX type contains invalid characters"), b[h >>> 3] |= f << 24 - 4 * (h % 8); + return { + value: b, + binLen: 4 * d + } + } + + function B(a) { + var b = [], + d = 0, + h, f, g, k, m; - 1 === a.search(/^[a-zA-Z0-9=+\/]+$/) && n("Invalid character in base-64 string"); + h = a.indexOf("="); + a = a.replace(/\=/g, ""); - 1 !== h && h < a.length && n("Invalid '=' found in base-64 string"); + for (f = 0; f < a.length; f += 4) { + m = a.substr(f, 4); + for (g = k = 0; g < m.length; g += 1) h = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(m[g]), k |= h << 18 - 6 * g; + for (g = 0; g < m.length - 1; g += 1) b[d >> 2] |= (k >>> 16 - 8 * g & 255) << 24 - 8 * (d % 4), d += 1 + } + return { + value: b, + binLen: 8 * d + } + } + + function E(a, b) { + var d = "", + h = 4 * a.length, + f, g; + for (f = 0; f < h; f += 1) g = a[f >>> 2] >>> 8 * (3 - f % 4), d += "0123456789abcdef".charAt(g >>> 4 & 15) + "0123456789abcdef".charAt(g & 15); + return b.outputUpper ? d.toUpperCase() : d + } + + function F(a, b) { + var d = "", + h = 4 * a.length, + f, g, k; + for (f = 0; f < h; f += 3) { + k = (a[f >>> 2] >>> 8 * (3 - f % 4) & 255) << 16 | (a[f + 1 >>> 2] >>> 8 * (3 - (f + 1) % 4) & 255) << 8 | a[f + 2 >>> 2] >>> 8 * (3 - (f + 2) % 4) & 255; + for (g = 0; 4 > g; g += 1) d = 8 * f + 6 * g <= 32 * a.length ? d + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(k >>> 6 * (3 - g) & 63) : d + b.b64Pad + } + return d + } + + function G(a) { + var b = { + outputUpper: !1, + b64Pad: "=" + }; + try { + a.hasOwnProperty("outputUpper") && (b.outputUpper = a.outputUpper), a.hasOwnProperty("b64Pad") && (b.b64Pad = a.b64Pad) + } catch (d) {} + "boolean" !== typeof b.outputUpper && n("Invalid outputUpper formatting option"); + "string" !== typeof b.b64Pad && n("Invalid b64Pad formatting option"); + return b + } + + function H(a, b) { + var d = q, + d = new s(a.a, a.b); + return d = 32 >= b ? new s(d.a >>> b | d.b << 32 - b & 4294967295, d.b >>> b | d.a << 32 - b & 4294967295) : new s(d.b >>> b - 32 | d.a << 64 - b & 4294967295, d.a >>> b - 32 | d.b << 64 - b & 4294967295) + } + + function I(a, b) { + var d = q; + return d = 32 >= b ? new s(a.a >>> b, a.b >>> b | a.a << 32 - b & 4294967295) : new s(0, a.a >>> b - 32) + } + + function J(a, b, d) { + return new s(a.a & b.a ^ ~a.a & d.a, a.b & b.b ^ ~a.b & d.b) + } + + function U(a, b, d) { + return new s(a.a & b.a ^ a.a & d.a ^ b.a & d.a, a.b & b.b ^ a.b & d.b ^ b.b & d.b) + } + + function V(a) { + var b = H(a, 28), + d = H(a, 34); + a = H(a, 39); + return new s(b.a ^ d.a ^ a.a, b.b ^ d.b ^ a.b) + } + + function W(a) { + var b = H(a, 14), + d = H(a, 18); + a = H(a, 41); + return new s(b.a ^ d.a ^ a.a, b.b ^ d.b ^ a.b) + } + + function X(a) { + var b = H(a, 1), + d = H(a, 8); + a = I(a, 7); + return new s(b.a ^ d.a ^ a.a, b.b ^ d.b ^ a.b) + } + + function Y(a) { + var b = H(a, 19), + d = H(a, 61); + a = I(a, 6); + return new s(b.a ^ d.a ^ a.a, b.b ^ d.b ^ a.b) + } + + function Z(a, b) { + var d, h, f; + d = (a.b & 65535) + (b.b & 65535); + h = (a.b >>> 16) + (b.b >>> 16) + (d >>> 16); + f = (h & 65535) << 16 | d & 65535; + d = (a.a & 65535) + (b.a & 65535) + (h >>> 16); + h = (a.a >>> 16) + (b.a >>> 16) + (d >>> 16); + return new s((h & 65535) << 16 | d & 65535, f) + } + + function aa(a, b, d, h) { + var f, g, k; + f = (a.b & 65535) + (b.b & 65535) + (d.b & 65535) + (h.b & 65535); + g = (a.b >>> 16) + (b.b >>> 16) + (d.b >>> 16) + (h.b >>> 16) + (f >>> 16); + k = (g & 65535) << 16 | f & 65535; + f = (a.a & 65535) + (b.a & 65535) + (d.a & 65535) + (h.a & 65535) + (g >>> 16); + g = (a.a >>> 16) + (b.a >>> 16) + (d.a >>> 16) + (h.a >>> 16) + (f >>> 16); + return new s((g & 65535) << 16 | f & 65535, k) + } + + function ba(a, b, d, h, f) { + var g, k, m; + g = (a.b & 65535) + (b.b & 65535) + (d.b & 65535) + (h.b & 65535) + (f.b & 65535); + k = (a.b >>> 16) + (b.b >>> 16) + (d.b >>> 16) + (h.b >>> 16) + (f.b >>> 16) + (g >>> 16); + m = (k & 65535) << 16 | g & 65535; + g = (a.a & 65535) + (b.a & 65535) + (d.a & 65535) + (h.a & 65535) + (f.a & 65535) + (k >>> 16); + k = (a.a >>> 16) + (b.a >>> 16) + (d.a >>> 16) + (h.a >>> 16) + (f.a >>> 16) + (g >>> 16); + return new s((k & 65535) << 16 | g & 65535, m) + } + + function $(a, b, d) { + var h, f, g, k, m, j, A, C, K, e, L, v, l, M, t, p, y, z, r, N, O, P, Q, R, c, S, w = [], + T, D; + "SHA-384" === d || "SHA-512" === d ? (L = 80, h = (b + 128 >>> 10 << 5) + 31, M = 32, t = 2, c = s, p = Z, y = aa, z = ba, r = X, N = Y, O = V, P = W, R = U, Q = J, S = [new c(1116352408, 3609767458), new c(1899447441, 602891725), new c(3049323471, 3964484399), new c(3921009573, 2173295548), new c(961987163, 4081628472), new c(1508970993, 3053834265), new c(2453635748, 2937671579), new c(2870763221, 3664609560), new c(3624381080, 2734883394), new c(310598401, 1164996542), new c(607225278, 1323610764), + new c(1426881987, 3590304994), new c(1925078388, 4068182383), new c(2162078206, 991336113), new c(2614888103, 633803317), new c(3248222580, 3479774868), new c(3835390401, 2666613458), new c(4022224774, 944711139), new c(264347078, 2341262773), new c(604807628, 2007800933), new c(770255983, 1495990901), new c(1249150122, 1856431235), new c(1555081692, 3175218132), new c(1996064986, 2198950837), new c(2554220882, 3999719339), new c(2821834349, 766784016), new c(2952996808, 2566594879), new c(3210313671, 3203337956), new c(3336571891, + 1034457026), new c(3584528711, 2466948901), new c(113926993, 3758326383), new c(338241895, 168717936), new c(666307205, 1188179964), new c(773529912, 1546045734), new c(1294757372, 1522805485), new c(1396182291, 2643833823), new c(1695183700, 2343527390), new c(1986661051, 1014477480), new c(2177026350, 1206759142), new c(2456956037, 344077627), new c(2730485921, 1290863460), new c(2820302411, 3158454273), new c(3259730800, 3505952657), new c(3345764771, 106217008), new c(3516065817, 3606008344), new c(3600352804, 1432725776), new c(4094571909, + 1467031594), new c(275423344, 851169720), new c(430227734, 3100823752), new c(506948616, 1363258195), new c(659060556, 3750685593), new c(883997877, 3785050280), new c(958139571, 3318307427), new c(1322822218, 3812723403), new c(1537002063, 2003034995), new c(1747873779, 3602036899), new c(1955562222, 1575990012), new c(2024104815, 1125592928), new c(2227730452, 2716904306), new c(2361852424, 442776044), new c(2428436474, 593698344), new c(2756734187, 3733110249), new c(3204031479, 2999351573), new c(3329325298, 3815920427), new c(3391569614, + 3928383900), new c(3515267271, 566280711), new c(3940187606, 3454069534), new c(4118630271, 4000239992), new c(116418474, 1914138554), new c(174292421, 2731055270), new c(289380356, 3203993006), new c(460393269, 320620315), new c(685471733, 587496836), new c(852142971, 1086792851), new c(1017036298, 365543100), new c(1126000580, 2618297676), new c(1288033470, 3409855158), new c(1501505948, 4234509866), new c(1607167915, 987167468), new c(1816402316, 1246189591) + ], e = "SHA-384" === d ? [new c(3418070365, 3238371032), new c(1654270250, 914150663), + new c(2438529370, 812702999), new c(355462360, 4144912697), new c(1731405415, 4290775857), new c(41048885895, 1750603025), new c(3675008525, 1694076839), new c(1203062813, 3204075428) + ] : [new c(1779033703, 4089235720), new c(3144134277, 2227873595), new c(1013904242, 4271175723), new c(2773480762, 1595750129), new c(1359893119, 2917565137), new c(2600822924, 725511199), new c(528734635, 4215389547), new c(1541459225, 327033209)]) : n("Unexpected error in SHA-2 implementation"); + a[b >>> 5] |= 128 << 24 - b % 32; + a[h] = b; + T = a.length; + for (v = 0; v < + T; v += M) { + b = e[0]; + h = e[1]; + f = e[2]; + g = e[3]; + k = e[4]; + m = e[5]; + j = e[6]; + A = e[7]; + for (l = 0; l < L; l += 1) w[l] = 16 > l ? new c(a[l * t + v], a[l * t + v + 1]) : y(N(w[l - 2]), w[l - 7], r(w[l - 15]), w[l - 16]), C = z(A, P(k), Q(k, m, j), S[l], w[l]), K = p(O(b), R(b, h, f)), A = j, j = m, m = k, k = p(g, C), g = f, f = h, h = b, b = p(C, K); + e[0] = p(b, e[0]); + e[1] = p(h, e[1]); + e[2] = p(f, e[2]); + e[3] = p(g, e[3]); + e[4] = p(k, e[4]); + e[5] = p(m, e[5]); + e[6] = p(j, e[6]); + e[7] = p(A, e[7]) + } + "SHA-384" === d ? D = [e[0].a, e[0].b, e[1].a, e[1].b, e[2].a, e[2].b, e[3].a, e[3].b, e[4].a, e[4].b, e[5].a, e[5].b] : "SHA-512" === d ? D = [e[0].a, e[0].b, + e[1].a, e[1].b, e[2].a, e[2].b, e[3].a, e[3].b, e[4].a, e[4].b, e[5].a, e[5].b, e[6].a, e[6].b, e[7].a, e[7].b + ] : n("Unexpected error in SHA-2 implementation"); + return D + } + GLOBAL.jsSHA = function(a, b, d) { + var h = q, + f = q, + g = 0, + k = [0], + m = 0, + j = q, + m = "undefined" !== typeof d ? d : 8; + 8 === m || 16 === m || n("charSize must be 8 or 16"); + "HEX" === b ? (0 !== a.length % 2 && n("srcString of HEX type must be in byte increments"), j = x(a), g = j.binLen, k = j.value) : "ASCII" === b || "TEXT" === b ? (j = u(a, m), g = j.binLen, k = j.value) : "B64" === b ? (j = B(a), g = j.binLen, k = j.value) : n("inputFormat must be HEX, TEXT, ASCII, or B64"); + this.getHash = function(a, b, d) { + var e = q, + m = k.slice(), + j = ""; + switch (b) { + case "HEX": + e = E; + break; + case "B64": + e = F; + break; + default: + n("format must be HEX or B64") + } + "SHA-384" === + a ? (q === h && (h = $(m, g, a)), j = e(h, G(d))) : "SHA-512" === a ? (q === f && (f = $(m, g, a)), j = e(f, G(d))) : n("Chosen SHA variant is not supported"); + return j + }; + this.getHMAC = function(a, b, d, e, f) { + var h, l, j, t, p, y = [], + z = [], + r = q; + switch (e) { + case "HEX": + h = E; + break; + case "B64": + h = F; + break; + default: + n("outputFormat must be HEX or B64") + } + "SHA-384" === d ? (j = 128, p = 384) : "SHA-512" === d ? (j = 128, p = 512) : n("Chosen SHA variant is not supported"); + "HEX" === b ? (r = x(a), t = r.binLen, l = r.value) : "ASCII" === b || "TEXT" === b ? (r = u(a, m), t = r.binLen, l = r.value) : "B64" === b ? (r = B(a), + t = r.binLen, l = r.value) : n("inputFormat must be HEX, TEXT, ASCII, or B64"); + a = 8 * j; + b = j / 4 - 1; + j < t / 8 ? (l = $(l, t, d), l[b] &= 4294967040) : j > t / 8 && (l[b] &= 4294967040); + for (j = 0; j <= b; j += 1) y[j] = l[j] ^ 909522486, z[j] = l[j] ^ 1549556828; + d = $(z.concat($(y.concat(k), a + g, d)), a + p, d); + return h(d, G(f)) + } + }; + })(); + + //coin.js + (function() { + /* + Coinjs 0.01 beta by OutCast3k{at}gmail.com + A bitcoin framework. + http://github.com/OutCast3k/coinjs or http://coinb.in/coinjs + */ + var coinjs = GLOBAL.coinjs = function() {}; + + /* public vars */ + coinjs.pub = 0x00; + coinjs.priv = 0x80; + coinjs.multisig = 0x05; + coinjs.hdkey = { + 'prv': 0x0488ade4, + 'pub': 0x0488b21e + }; + coinjs.bech32 = { + 'charset': 'qpzry9x8gf2tvdw0s3jn54khce6mua7l', + 'version': 0, + 'hrp': 'bc' + }; + + coinjs.compressed = false; + + /* other vars */ + coinjs.developer = '33tht1bKDgZVxb39MnZsWa8oxHXHvUYE4G'; //bitcoin + + /* bit(coinb.in) api vars */ + coinjs.hostname = ((document.location.hostname.split(".")[(document.location.hostname.split(".")).length - 1]) == 'onion') ? 'coinbin3ravkwb24f7rmxx6w3snkjw45jhs5lxbh3yfeg3vpt6janwqd.onion' : 'coinb.in'; + coinjs.host = ('https:' == document.location.protocol ? 'https://' : 'http://') + coinjs.hostname + '/api/'; + coinjs.uid = '1'; + coinjs.key = '12345678901234567890123456789012'; + + /* start of address functions */ + + /* generate a private and public keypair, with address and WIF address */ + coinjs.newKeys = function(input) { + var privkey = (input) ? Crypto.SHA256(input) : this.newPrivkey(); + var pubkey = this.newPubkey(privkey); + return { + 'privkey': privkey, + 'pubkey': pubkey, + 'address': this.pubkey2address(pubkey), + 'wif': this.privkey2wif(privkey), + 'compressed': this.compressed + }; + } + + /* generate a new random private key */ + coinjs.newPrivkey = function() { + var x = GLOBAL.location; + x += (GLOBAL.screen.height * GLOBAL.screen.width * GLOBAL.screen.colorDepth); + x += coinjs.random(64); + x += (GLOBAL.screen.availHeight * GLOBAL.screen.availWidth * GLOBAL.screen.pixelDepth); + x += navigator.language; + x += GLOBAL.history.length; + x += coinjs.random(64); + x += navigator.userAgent; + x += 'coinb.in'; + x += (Crypto.util.randomBytes(64)).join(""); + x += x.length; + var dateObj = new Date(); + x += dateObj.getTimezoneOffset(); + x += coinjs.random(64); + x += (document.getElementById("entropybucket")) ? document.getElementById("entropybucket").innerHTML : ''; + x += x + '' + x; + var r = x; + for (i = 0; i < (x).length / 25; i++) { + r = Crypto.SHA256(r.concat(x)); + } + var checkrBigInt = new BigInteger(r); + var orderBigInt = new BigInteger("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); + while (checkrBigInt.compareTo(orderBigInt) >= 0 || checkrBigInt.equals(BigInteger.ZERO) || checkrBigInt.equals(BigInteger.ONE)) { + r = Crypto.SHA256(r.concat(x)); + checkrBigInt = new BigInteger(r); + } + return r; + } + + /* generate a public key from a private key */ + coinjs.newPubkey = function(hash) { + var privateKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(hash)); + var curve = EllipticCurve.getSECCurveByName("secp256k1"); + + var curvePt = curve.getG().multiply(privateKeyBigInt); + var x = curvePt.getX().toBigInteger(); + var y = curvePt.getY().toBigInteger(); + + var publicKeyBytes = EllipticCurve.integerToBytes(x, 32); + publicKeyBytes = publicKeyBytes.concat(EllipticCurve.integerToBytes(y, 32)); + publicKeyBytes.unshift(0x04); + + if (coinjs.compressed == true) { + var publicKeyBytesCompressed = EllipticCurve.integerToBytes(x, 32) + if (y.isEven()) { + publicKeyBytesCompressed.unshift(0x02) + } else { + publicKeyBytesCompressed.unshift(0x03) + } + return Crypto.util.bytesToHex(publicKeyBytesCompressed); + } else { + return Crypto.util.bytesToHex(publicKeyBytes); + } + } + + /* provide a public key and return address */ + coinjs.pubkey2address = function(h, byte) { + var r = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(h), { + asBytes: true + })); + r.unshift(byte || coinjs.pub); + var hash = Crypto.SHA256(Crypto.SHA256(r, { + asBytes: true + }), { + asBytes: true + }); + var checksum = hash.slice(0, 4); + return coinjs.base58encode(r.concat(checksum)); + } + + /* provide a scripthash and return address */ + coinjs.scripthash2address = function(h) { + var x = Crypto.util.hexToBytes(h); + x.unshift(coinjs.pub); + var r = x; + r = Crypto.SHA256(Crypto.SHA256(r, { + asBytes: true + }), { + asBytes: true + }); + var checksum = r.slice(0, 4); + return coinjs.base58encode(x.concat(checksum)); + } + + /* new multisig address, provide the pubkeys AND required signatures to release the funds */ + coinjs.pubkeys2MultisigAddress = function(pubkeys, required) { + var s = coinjs.script(); + s.writeOp(81 + (required * 1) - 1); //OP_1 + for (var i = 0; i < pubkeys.length; ++i) { + s.writeBytes(Crypto.util.hexToBytes(pubkeys[i])); + } + s.writeOp(81 + pubkeys.length - 1); //OP_1 + s.writeOp(174); //OP_CHECKMULTISIG + var x = ripemd160(Crypto.SHA256(s.buffer, { + asBytes: true + }), { + asBytes: true + }); + x.unshift(coinjs.multisig); + var r = x; + r = Crypto.SHA256(Crypto.SHA256(r, { + asBytes: true + }), { + asBytes: true + }); + var checksum = r.slice(0, 4); + var redeemScript = Crypto.util.bytesToHex(s.buffer); + var address = coinjs.base58encode(x.concat(checksum)); + + if (s.buffer.length > 520) { // too large + address = 'invalid'; + redeemScript = 'invalid'; + } + + return { + 'address': address, + 'redeemScript': redeemScript, + 'size': s.buffer.length + }; + } + + /* new time locked address, provide the pubkey and time necessary to unlock the funds. + when time is greater than 500000000, it should be a unix timestamp (seconds since epoch), + otherwise it should be the block height required before this transaction can be released. + + may throw a string on failure! + */ + coinjs.simpleHodlAddress = function(pubkey, checklocktimeverify) { + + if (checklocktimeverify < 0) { + throw "Parameter for OP_CHECKLOCKTIMEVERIFY is negative."; + } + + var s = coinjs.script(); + if (checklocktimeverify <= 16 && checklocktimeverify >= 1) { + s.writeOp(0x50 + checklocktimeverify); //OP_1 to OP_16 for minimal encoding + } else { + s.writeBytes(coinjs.numToScriptNumBytes(checklocktimeverify)); + } + s.writeOp(177); //OP_CHECKLOCKTIMEVERIFY + s.writeOp(117); //OP_DROP + s.writeBytes(Crypto.util.hexToBytes(pubkey)); + s.writeOp(172); //OP_CHECKSIG + + var x = ripemd160(Crypto.SHA256(s.buffer, { + asBytes: true + }), { + asBytes: true + }); + x.unshift(coinjs.multisig); + var r = x; + r = Crypto.SHA256(Crypto.SHA256(r, { + asBytes: true + }), { + asBytes: true + }); + var checksum = r.slice(0, 4); + var redeemScript = Crypto.util.bytesToHex(s.buffer); + var address = coinjs.base58encode(x.concat(checksum)); + + return { + 'address': address, + 'redeemScript': redeemScript + }; + } + + /* create a new segwit address */ + coinjs.segwitAddress = function(pubkey) { + var keyhash = [0x00, 0x14].concat(ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubkey), { + asBytes: true + }), { + asBytes: true + })); + var x = ripemd160(Crypto.SHA256(keyhash, { + asBytes: true + }), { + asBytes: true + }); + x.unshift(coinjs.multisig); + var r = x; + r = Crypto.SHA256(Crypto.SHA256(r, { + asBytes: true + }), { + asBytes: true + }); + var checksum = r.slice(0, 4); + var address = coinjs.base58encode(x.concat(checksum)); + + return { + 'address': address, + 'type': 'segwit', + 'redeemscript': Crypto.util.bytesToHex(keyhash) + }; + } + + /* create a new segwit bech32 encoded address */ + coinjs.bech32Address = function(pubkey) { + var program = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubkey), { + asBytes: true + }), { + asBytes: true + }); + var address = coinjs.bech32_encode(coinjs.bech32.hrp, [coinjs.bech32.version].concat(coinjs.bech32_convert(program, 8, 5, true))); + return { + 'address': address, + 'type': 'bech32', + 'redeemscript': Crypto.util.bytesToHex(program) + }; + } + + /* extract the redeemscript from a bech32 address */ + coinjs.bech32redeemscript = function(address) { + var r = false; + var decode = coinjs.bech32_decode(address); + if (decode) { + decode.data.shift(); + return Crypto.util.bytesToHex(coinjs.bech32_convert(decode.data, 5, 8, false)); + } + return r; + } + + /* provide a privkey and return an WIF */ + coinjs.privkey2wif = function(h) { + var r = Crypto.util.hexToBytes(h); + + if (coinjs.compressed == true) { + r.push(0x01); + } + + r.unshift(coinjs.priv); + var hash = Crypto.SHA256(Crypto.SHA256(r, { + asBytes: true + }), { + asBytes: true + }); + var checksum = hash.slice(0, 4); + + return coinjs.base58encode(r.concat(checksum)); + } + + /* convert a wif key back to a private key */ + coinjs.wif2privkey = function(wif) { + var compressed = false; + var decode = coinjs.base58decode(wif); + var key = decode.slice(0, decode.length - 4); + key = key.slice(1, key.length); + if (key.length >= 33 && key[key.length - 1] == 0x01) { + key = key.slice(0, key.length - 1); + compressed = true; + } + return { + 'privkey': Crypto.util.bytesToHex(key), + 'compressed': compressed + }; + } + + /* convert a wif to a pubkey */ + coinjs.wif2pubkey = function(wif) { + var compressed = coinjs.compressed; + var r = coinjs.wif2privkey(wif); + coinjs.compressed = r['compressed']; + var pubkey = coinjs.newPubkey(r['privkey']); + coinjs.compressed = compressed; + return { + 'pubkey': pubkey, + 'compressed': r['compressed'] + }; + } + + /* convert a wif to a address */ + coinjs.wif2address = function(wif) { + var r = coinjs.wif2pubkey(wif); + return { + 'address': coinjs.pubkey2address(r['pubkey']), + 'compressed': r['compressed'] + }; + } + + /* decode or validate an address and return the hash */ + coinjs.addressDecode = function(addr) { + try { + var bytes = coinjs.base58decode(addr); + var front = bytes.slice(0, bytes.length - 4); + var back = bytes.slice(bytes.length - 4); + var checksum = Crypto.SHA256(Crypto.SHA256(front, { + asBytes: true + }), { + asBytes: true + }).slice(0, 4); + if (checksum + "" == back + "") { + + var o = {}; + o.bytes = front.slice(1); + o.version = front[0]; + + if (o.version == coinjs.pub) { // standard address + o.type = 'standard'; + + } else if (o.version == coinjs.multisig) { // multisig address + o.type = 'multisig'; + + } else if (o.version == coinjs.priv) { // wifkey + o.type = 'wifkey'; + + } else if (o.version == 42) { // stealth address + o.type = 'stealth'; + + o.option = front[1]; + if (o.option != 0) { + alert("Stealth Address option other than 0 is currently not supported!"); + return false; + }; + + o.scankey = Crypto.util.bytesToHex(front.slice(2, 35)); + o.n = front[35]; + + if (o.n > 1) { + alert("Stealth Multisig is currently not supported!"); + return false; + }; + + o.spendkey = Crypto.util.bytesToHex(front.slice(36, 69)); + o.m = front[69]; + o.prefixlen = front[70]; + + if (o.prefixlen > 0) { + alert("Stealth Address Prefixes are currently not supported!"); + return false; + }; + o.prefix = front.slice(71); + + } else { // everything else + o.type = 'other'; // address is still valid but unknown version + } + + return o; + } else { + throw "Invalid checksum"; + } + } catch (e) { + bech32rs = coinjs.bech32redeemscript(addr); + if (bech32rs) { + return { + 'type': 'bech32', + 'redeemscript': bech32rs + }; + } else { + return false; + } + } + } + + /* retreive the balance from a given address */ + coinjs.addressBalance = function(address, callback) { + coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=bal&address=' + address + '&r=' + Math.random(), callback, "GET"); + } + + /* decompress an compressed public key */ + coinjs.pubkeydecompress = function(pubkey) { + if ((typeof(pubkey) == 'string') && pubkey.match(/^[a-f0-9]+$/i)) { + var curve = EllipticCurve.getSECCurveByName("secp256k1"); + try { + var pt = curve.curve.decodePointHex(pubkey); + var x = pt.getX().toBigInteger(); + var y = pt.getY().toBigInteger(); + + var publicKeyBytes = EllipticCurve.integerToBytes(x, 32); + publicKeyBytes = publicKeyBytes.concat(EllipticCurve.integerToBytes(y, 32)); + publicKeyBytes.unshift(0x04); + return Crypto.util.bytesToHex(publicKeyBytes); + } catch (e) { + // console.log(e); + return false; + } + } + return false; + } + + coinjs.bech32_polymod = function(values) { + var chk = 1; + var BECH32_GENERATOR = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; + for (var p = 0; p < values.length; ++p) { + var top = chk >> 25; + chk = (chk & 0x1ffffff) << 5 ^ values[p]; + for (var i = 0; i < 5; ++i) { + if ((top >> i) & 1) { + chk ^= BECH32_GENERATOR[i]; + } + } + } + return chk; + } + + coinjs.bech32_hrpExpand = function(hrp) { + var ret = []; + var p; + for (p = 0; p < hrp.length; ++p) { + ret.push(hrp.charCodeAt(p) >> 5); + } + ret.push(0); + for (p = 0; p < hrp.length; ++p) { + ret.push(hrp.charCodeAt(p) & 31); + } + return ret; + } + + coinjs.bech32_verifyChecksum = function(hrp, data) { + return coinjs.bech32_polymod(coinjs.bech32_hrpExpand(hrp).concat(data)) === 1; + } + + coinjs.bech32_createChecksum = function(hrp, data) { + var values = coinjs.bech32_hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]); + var mod = coinjs.bech32_polymod(values) ^ 1; + var ret = []; + for (var p = 0; p < 6; ++p) { + ret.push((mod >> 5 * (5 - p)) & 31); + } + return ret; + } + + coinjs.bech32_encode = function(hrp, data) { + var combined = data.concat(coinjs.bech32_createChecksum(hrp, data)); + var ret = hrp + '1'; + for (var p = 0; p < combined.length; ++p) { + ret += coinjs.bech32.charset.charAt(combined[p]); + } + return ret; + } + + coinjs.bech32_decode = function(bechString) { + var p; + var has_lower = false; + var has_upper = false; + for (p = 0; p < bechString.length; ++p) { + if (bechString.charCodeAt(p) < 33 || bechString.charCodeAt(p) > 126) { + return null; + } + if (bechString.charCodeAt(p) >= 97 && bechString.charCodeAt(p) <= 122) { + has_lower = true; + } + if (bechString.charCodeAt(p) >= 65 && bechString.charCodeAt(p) <= 90) { + has_upper = true; + } + } + if (has_lower && has_upper) { + return null; + } + bechString = bechString.toLowerCase(); + var pos = bechString.lastIndexOf('1'); + if (pos < 1 || pos + 7 > bechString.length || bechString.length > 90) { + return null; + } + var hrp = bechString.substring(0, pos); + var data = []; + for (p = pos + 1; p < bechString.length; ++p) { + var d = coinjs.bech32.charset.indexOf(bechString.charAt(p)); + if (d === -1) { + return null; + } + data.push(d); + } + if (!coinjs.bech32_verifyChecksum(hrp, data)) { + return null; + } + return { + hrp: hrp, + data: data.slice(0, data.length - 6) + }; + } + + coinjs.bech32_convert = function(data, inBits, outBits, pad) { + var value = 0; + var bits = 0; + var maxV = (1 << outBits) - 1; + + var result = []; + for (var i = 0; i < data.length; ++i) { + value = (value << inBits) | data[i]; + bits += inBits; + + while (bits >= outBits) { + bits -= outBits; + result.push((value >> bits) & maxV); + } + } + + if (pad) { + if (bits > 0) { + result.push((value << (outBits - bits)) & maxV); + } + } else { + if (bits >= inBits) throw new Error('Excess padding'); + if ((value << (outBits - bits)) & maxV) throw new Error('Non-zero padding'); + } + + return result; + } + + coinjs.testdeterministicK = function() { + // https://github.com/bitpay/bitcore/blob/9a5193d8e94b0bd5b8e7f00038e7c0b935405a03/test/crypto/ecdsa.js + // Line 21 and 22 specify digest hash and privkey for the first 2 test vectors. + // Line 96-117 tells expected result. + + var tx = coinjs.transaction(); + + var test_vectors = [{ + 'message': 'test data', + 'privkey': 'fee0a1f7afebf9d2a5a80c0c98a31c709681cce195cbcd06342b517970c0be1e', + 'k_bad00': 'fcce1de7a9bcd6b2d3defade6afa1913fb9229e3b7ddf4749b55c4848b2a196e', + 'k_bad01': '727fbcb59eb48b1d7d46f95a04991fc512eb9dbf9105628e3aec87428df28fd8', + 'k_bad15': '398f0e2c9f79728f7b3d84d447ac3a86d8b2083c8f234a0ffa9c4043d68bd258' + }, + { + 'message': 'Everything should be made as simple as possible, but not simpler.', + 'privkey': '0000000000000000000000000000000000000000000000000000000000000001', + 'k_bad00': 'ec633bd56a5774a0940cb97e27a9e4e51dc94af737596a0c5cbb3d30332d92a5', + 'k_bad01': 'df55b6d1b5c48184622b0ead41a0e02bfa5ac3ebdb4c34701454e80aabf36f56', + 'k_bad15': 'def007a9a3c2f7c769c75da9d47f2af84075af95cadd1407393dc1e26086ef87' + }, + { + 'message': 'Satoshi Nakamoto', + 'privkey': '0000000000000000000000000000000000000000000000000000000000000002', + 'k_bad00': 'd3edc1b8224e953f6ee05c8bbf7ae228f461030e47caf97cde91430b4607405e', + 'k_bad01': 'f86d8e43c09a6a83953f0ab6d0af59fb7446b4660119902e9967067596b58374', + 'k_bad15': '241d1f57d6cfd2f73b1ada7907b199951f95ef5ad362b13aed84009656e0254a' + }, + { + 'message': 'Diffie Hellman', + 'privkey': '7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f', + 'k_bad00': 'c378a41cb17dce12340788dd3503635f54f894c306d52f6e9bc4b8f18d27afcc', + 'k_bad01': '90756c96fef41152ac9abe08819c4e95f16da2af472880192c69a2b7bac29114', + 'k_bad15': '7b3f53300ab0ccd0f698f4d67db87c44cf3e9e513d9df61137256652b2e94e7c' + }, + { + 'message': 'Japan', + 'privkey': '8080808080808080808080808080808080808080808080808080808080808080', + 'k_bad00': 'f471e61b51d2d8db78f3dae19d973616f57cdc54caaa81c269394b8c34edcf59', + 'k_bad01': '6819d85b9730acc876fdf59e162bf309e9f63dd35550edf20869d23c2f3e6d17', + 'k_bad15': 'd8e8bae3ee330a198d1f5e00ad7c5f9ed7c24c357c0a004322abca5d9cd17847' + }, + { + 'message': 'Bitcoin', + 'privkey': 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140', + 'k_bad00': '36c848ffb2cbecc5422c33a994955b807665317c1ce2a0f59c689321aaa631cc', + 'k_bad01': '4ed8de1ec952a4f5b3bd79d1ff96446bcd45cabb00fc6ca127183e14671bcb85', + 'k_bad15': '56b6f47babc1662c011d3b1f93aa51a6e9b5f6512e9f2e16821a238d450a31f8' + }, + { + 'message': 'i2FLPP8WEus5WPjpoHwheXOMSobUJVaZM1JPMQZq', + 'privkey': 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140', + 'k_bad00': '6e9b434fcc6bbb081a0463c094356b47d62d7efae7da9c518ed7bac23f4e2ed6', + 'k_bad01': 'ae5323ae338d6117ce8520a43b92eacd2ea1312ae514d53d8e34010154c593bb', + 'k_bad15': '3eaa1b61d1b8ab2f1ca71219c399f2b8b3defa624719f1e96fe3957628c2c4ea' + }, + { + 'message': 'lEE55EJNP7aLrMtjkeJKKux4Yg0E8E1SAJnWTCEh', + 'privkey': '3881e5286abc580bb6139fe8e83d7c8271c6fe5e5c2d640c1f0ed0e1ee37edc9', + 'k_bad00': '5b606665a16da29cc1c5411d744ab554640479dd8abd3c04ff23bd6b302e7034', + 'k_bad01': 'f8b25263152c042807c992eacd2ac2cc5790d1e9957c394f77ea368e3d9923bd', + 'k_bad15': 'ea624578f7e7964ac1d84adb5b5087dd14f0ee78b49072aa19051cc15dab6f33' + }, + { + 'message': '2SaVPvhxkAPrayIVKcsoQO5DKA8Uv5X/esZFlf+y', + 'privkey': '7259dff07922de7f9c4c5720d68c9745e230b32508c497dd24cb95ef18856631', + 'k_bad00': '3ab6c19ab5d3aea6aa0c6da37516b1d6e28e3985019b3adb388714e8f536686b', + 'k_bad01': '19af21b05004b0ce9cdca82458a371a9d2cf0dc35a813108c557b551c08eb52e', + 'k_bad15': '117a32665fca1b7137a91c4739ac5719fec0cf2e146f40f8e7c21b45a07ebc6a' + }, + { + 'message': '00A0OwO2THi7j5Z/jp0FmN6nn7N/DQd6eBnCS+/b', + 'privkey': '0d6ea45d62b334777d6995052965c795a4f8506044b4fd7dc59c15656a28f7aa', + 'k_bad00': '79487de0c8799158294d94c0eb92ee4b567e4dc7ca18addc86e49d31ce1d2db6', + 'k_bad01': '9561d2401164a48a8f600882753b3105ebdd35e2358f4f808c4f549c91490009', + 'k_bad15': 'b0d273634129ff4dbdf0df317d4062a1dbc58818f88878ffdb4ec511c77976c0' + } + ]; + + var result_txt = '\n----------------------\nResults\n----------------------\n\n'; + + for (i = 0; i < test_vectors.length; i++) { + var hash = Crypto.SHA256(test_vectors[i]['message'].split('').map(function(c) { + return c.charCodeAt(0); + }), { + asBytes: true + }); + var wif = coinjs.privkey2wif(test_vectors[i]['privkey']); + + var KBigInt = tx.deterministicK(wif, hash); + var KBigInt0 = tx.deterministicK(wif, hash, 0); + var KBigInt1 = tx.deterministicK(wif, hash, 1); + var KBigInt15 = tx.deterministicK(wif, hash, 15); + + var K = Crypto.util.bytesToHex(KBigInt.toByteArrayUnsigned()); + var K0 = Crypto.util.bytesToHex(KBigInt0.toByteArrayUnsigned()); + var K1 = Crypto.util.bytesToHex(KBigInt1.toByteArrayUnsigned()); + var K15 = Crypto.util.bytesToHex(KBigInt15.toByteArrayUnsigned()); + + if (K != test_vectors[i]['k_bad00']) { + result_txt += 'Failed Test #' + (i + 1) + '\n K = ' + K + '\nExpected = ' + test_vectors[i]['k_bad00'] + '\n\n'; + } else if (K0 != test_vectors[i]['k_bad00']) { + result_txt += 'Failed Test #' + (i + 1) + '\n K0 = ' + K0 + '\nExpected = ' + test_vectors[i]['k_bad00'] + '\n\n'; + } else if (K1 != test_vectors[i]['k_bad01']) { + result_txt += 'Failed Test #' + (i + 1) + '\n K1 = ' + K1 + '\nExpected = ' + test_vectors[i]['k_bad01'] + '\n\n'; + } else if (K15 != test_vectors[i]['k_bad15']) { + result_txt += 'Failed Test #' + (i + 1) + '\n K15 = ' + K15 + '\nExpected = ' + test_vectors[i]['k_bad15'] + '\n\n'; + }; + }; + + if (result_txt.length < 60) { + result_txt = 'All Tests OK!'; + }; + + return result_txt; + }; + + /* start of hd functions, thanks bip32.org */ + coinjs.hd = function(data) { + + var r = {}; + + /* some hd value parsing */ + r.parse = function() { + + var bytes = []; + + // some quick validation + if (typeof(data) == 'string') { + var decoded = coinjs.base58decode(data); + if (decoded.length == 82) { + var checksum = decoded.slice(78, 82); + var hash = Crypto.SHA256(Crypto.SHA256(decoded.slice(0, 78), { + asBytes: true + }), { + asBytes: true + }); + if (checksum[0] == hash[0] && checksum[1] == hash[1] && checksum[2] == hash[2] && checksum[3] == hash[3]) { + bytes = decoded.slice(0, 78); + } + } + } + + // actual parsing code + if (bytes && bytes.length > 0) { + r.version = coinjs.uint(bytes.slice(0, 4), 4); + r.depth = coinjs.uint(bytes.slice(4, 5), 1); + r.parent_fingerprint = bytes.slice(5, 9); + r.child_index = coinjs.uint(bytes.slice(9, 13), 4); + r.chain_code = bytes.slice(13, 45); + r.key_bytes = bytes.slice(45, 78); + + var c = coinjs.compressed; // get current default + coinjs.compressed = true; + + if (r.key_bytes[0] == 0x00) { + r.type = 'private'; + var privkey = (r.key_bytes).slice(1, 33); + var privkeyHex = Crypto.util.bytesToHex(privkey); + var pubkey = coinjs.newPubkey(privkeyHex); + + r.keys = { + 'privkey': privkeyHex, + 'pubkey': pubkey, + 'address': coinjs.pubkey2address(pubkey), + 'wif': coinjs.privkey2wif(privkeyHex) + }; + + } else if (r.key_bytes[0] == 0x02 || r.key_bytes[0] == 0x03) { + r.type = 'public'; + var pubkeyHex = Crypto.util.bytesToHex(r.key_bytes); + + r.keys = { + 'pubkey': pubkeyHex, + 'address': coinjs.pubkey2address(pubkeyHex) + }; + } else { + r.type = 'invalid'; + } + + r.keys_extended = r.extend(); + + coinjs.compressed = c; // reset to default + } + + return r; + } + + // extend prv/pub key + r.extend = function() { + var hd = coinjs.hd(); + return hd.make({ + 'depth': (this.depth * 1) + 1, + 'parent_fingerprint': this.parent_fingerprint, + 'child_index': this.child_index, + 'chain_code': this.chain_code, + 'privkey': this.keys.privkey, + 'pubkey': this.keys.pubkey + }); + } + + // derive from path + r.derive_path = function(path) { + + if (path == 'm' || path == 'M' || path == 'm\'' || path == 'M\'') return this; + + var p = path.split('/'); + var hdp = coinjs.clone(this); // clone hd path + + for (var i in p) { + + if (((i == 0) && c != 'm') || i == 'remove') { + continue; + } + + var c = p[i]; + + var use_private = (c.length > 1) && (c[c.length - 1] == '\''); + var child_index = parseInt(use_private ? c.slice(0, c.length - 1) : c) & 0x7fffffff; + if (use_private) + child_index += 0x80000000; + + hdp = hdp.derive(child_index); + var key = ((hdp.keys_extended.privkey) && hdp.keys_extended.privkey != '') ? hdp.keys_extended.privkey : hdp.keys_extended.pubkey; + hdp = coinjs.hd(key); + } + return hdp; + } + + // derive key from index + r.derive = function(i) { + + i = (i) ? i : 0; + var blob = (Crypto.util.hexToBytes(this.keys.pubkey)).concat(coinjs.numToBytes(i, 4).reverse()); + + var j = new jsSHA(Crypto.util.bytesToHex(blob), 'HEX'); + var hash = j.getHMAC(Crypto.util.bytesToHex(r.chain_code), "HEX", "SHA-512", "HEX"); + + var il = new BigInteger(hash.slice(0, 64), 16); + var ir = Crypto.util.hexToBytes(hash.slice(64, 128)); + + var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); + var curve = ecparams.getCurve(); + + var k, key, pubkey, o; + + o = coinjs.clone(this); + o.chain_code = ir; + o.child_index = i; + + if (this.type == 'private') { + // derive key pair from from a xprv key + k = il.add(new BigInteger([0].concat(Crypto.util.hexToBytes(this.keys.privkey)))).mod(ecparams.getN()); + key = Crypto.util.bytesToHex(k.toByteArrayUnsigned()); + + pubkey = coinjs.newPubkey(key); + + o.keys = { + 'privkey': key, + 'pubkey': pubkey, + 'wif': coinjs.privkey2wif(key), + 'address': coinjs.pubkey2address(pubkey) + }; + + } else if (this.type == 'public') { + // derive xpub key from an xpub key + q = ecparams.curve.decodePointHex(this.keys.pubkey); + var curvePt = ecparams.getG().multiply(il).add(q); + + var x = curvePt.getX().toBigInteger(); + var y = curvePt.getY().toBigInteger(); + + var publicKeyBytesCompressed = EllipticCurve.integerToBytes(x, 32) + if (y.isEven()) { + publicKeyBytesCompressed.unshift(0x02) + } else { + publicKeyBytesCompressed.unshift(0x03) + } + pubkey = Crypto.util.bytesToHex(publicKeyBytesCompressed); + + o.keys = { + 'pubkey': pubkey, + 'address': coinjs.pubkey2address(pubkey) + } + } else { + // fail + } + + o.parent_fingerprint = (ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(r.keys.pubkey), { + asBytes: true + }), { + asBytes: true + })).slice(0, 4); + o.keys_extended = o.extend(); + return o; + } + + // make a master hd xprv/xpub + r.master = function(pass) { + var seed = (pass) ? Crypto.SHA256(pass) : coinjs.newPrivkey(); + var hasher = new jsSHA(seed, 'HEX'); + var I = hasher.getHMAC("Bitcoin seed", "TEXT", "SHA-512", "HEX"); + + var privkey = Crypto.util.hexToBytes(I.slice(0, 64)); + var chain = Crypto.util.hexToBytes(I.slice(64, 128)); + + var hd = coinjs.hd(); + return hd.make({ + 'depth': 0, + 'parent_fingerprint': [0, 0, 0, 0], + 'child_index': 0, + 'chain_code': chain, + 'privkey': I.slice(0, 64), + 'pubkey': coinjs.newPubkey(I.slice(0, 64)) + }); + } + + // encode data to a base58 string + r.make = function(data) { // { (int) depth, (array) parent_fingerprint, (int) child_index, (byte array) chain_code, (hex str) privkey, (hex str) pubkey} + var k = []; + + //depth + k.push(data.depth * 1); + + //parent fingerprint + k = k.concat(data.parent_fingerprint); + + //child index + k = k.concat((coinjs.numToBytes(data.child_index, 4)).reverse()); + + //Chain code + k = k.concat(data.chain_code); + + var o = {}; // results + + //encode xprv key + if (data.privkey) { + var prv = (coinjs.numToBytes(coinjs.hdkey.prv, 4)).reverse(); + prv = prv.concat(k); + prv.push(0x00); + prv = prv.concat(Crypto.util.hexToBytes(data.privkey)); + var hash = Crypto.SHA256(Crypto.SHA256(prv, { + asBytes: true + }), { + asBytes: true + }); + var checksum = hash.slice(0, 4); + var ret = prv.concat(checksum); + o.privkey = coinjs.base58encode(ret); + } + + //encode xpub key + if (data.pubkey) { + var pub = (coinjs.numToBytes(coinjs.hdkey.pub, 4)).reverse(); + pub = pub.concat(k); + pub = pub.concat(Crypto.util.hexToBytes(data.pubkey)); + var hash = Crypto.SHA256(Crypto.SHA256(pub, { + asBytes: true + }), { + asBytes: true + }); + var checksum = hash.slice(0, 4); + var ret = pub.concat(checksum); + o.pubkey = coinjs.base58encode(ret); + } + return o; + } + + return r.parse(); + } + + + /* start of script functions */ + coinjs.script = function(data) { + var r = {}; + + if (!data) { + r.buffer = []; + } else if ("string" == typeof data) { + r.buffer = Crypto.util.hexToBytes(data); + } else if (coinjs.isArray(data)) { + r.buffer = data; + } else if (data instanceof coinjs.script) { + r.buffer = data.buffer; + } else { + r.buffer = data; + } + + /* parse buffer array */ + r.parse = function() { + + var self = this; + r.chunks = []; + var i = 0; + + function readChunk(n) { + self.chunks.push(self.buffer.slice(i, i + n)); + i += n; + }; + + while (i < this.buffer.length) { + var opcode = this.buffer[i++]; + if (opcode >= 0xF0) { + opcode = (opcode << 8) | this.buffer[i++]; + } + + var len; + if (opcode > 0 && opcode < 76) { //OP_PUSHDATA1 + readChunk(opcode); + } else if (opcode == 76) { //OP_PUSHDATA1 + len = this.buffer[i++]; + readChunk(len); + } else if (opcode == 77) { //OP_PUSHDATA2 + len = (this.buffer[i++] << 8) | this.buffer[i++]; + readChunk(len); + } else if (opcode == 78) { //OP_PUSHDATA4 + len = (this.buffer[i++] << 24) | (this.buffer[i++] << 16) | (this.buffer[i++] << 8) | this.buffer[i++]; + readChunk(len); + } else { + this.chunks.push(opcode); + } + + if (i < 0x00) { + break; + } + } + + return true; + }; + + /* decode the redeemscript of a multisignature transaction */ + r.decodeRedeemScript = function(script) { + var r = false; + try { + var s = coinjs.script(Crypto.util.hexToBytes(script)); + if ((s.chunks.length >= 3) && s.chunks[s.chunks.length - 1] == 174) { //OP_CHECKMULTISIG + r = {}; + r.signaturesRequired = s.chunks[0] - 80; + var pubkeys = []; + for (var i = 1; i < s.chunks.length - 2; i++) { + pubkeys.push(Crypto.util.bytesToHex(s.chunks[i])); + } + r.pubkeys = pubkeys; + var multi = coinjs.pubkeys2MultisigAddress(pubkeys, r.signaturesRequired); + r.address = multi['address']; + r.type = 'multisig__'; // using __ for now to differentiat from the other object .type == "multisig" + var rs = Crypto.util.bytesToHex(s.buffer); + r.redeemscript = rs; + + } else if ((s.chunks.length == 2) && (s.buffer[0] == 0 && s.buffer[1] == 20)) { // SEGWIT + r = {}; + r.type = "segwit__"; + var rs = Crypto.util.bytesToHex(s.buffer); + r.address = coinjs.pubkey2address(rs, coinjs.multisig); + r.redeemscript = rs; + + } else if (s.chunks.length == 5 && s.chunks[1] == 177 && s.chunks[2] == 117 && s.chunks[4] == 172) { + // ^ OP_CHECKLOCKTIMEVERIFY OP_DROP OP_CHECKSIG ^ + r = {} + r.pubkey = Crypto.util.bytesToHex(s.chunks[3]); + r.checklocktimeverify = coinjs.bytesToNum(s.chunks[0].slice()); + r.address = coinjs.simpleHodlAddress(r.pubkey, r.checklocktimeverify).address; + var rs = Crypto.util.bytesToHex(s.buffer); + r.redeemscript = rs; + r.type = "hodl__"; + } + } catch (e) { + // console.log(e); + r = false; + } + return r; + } + + /* create output script to spend */ + r.spendToScript = function(address) { + var addr = coinjs.addressDecode(address); + var s = coinjs.script(); + if (addr.type == "bech32") { + s.writeOp(0); + s.writeBytes(Crypto.util.hexToBytes(addr.redeemscript)); + } else if (addr.version == coinjs.multisig) { // multisig address + s.writeOp(169); //OP_HASH160 + s.writeBytes(addr.bytes); + s.writeOp(135); //OP_EQUAL + } else { // regular address + s.writeOp(118); //OP_DUP + s.writeOp(169); //OP_HASH160 + s.writeBytes(addr.bytes); + s.writeOp(136); //OP_EQUALVERIFY + s.writeOp(172); //OP_CHECKSIG + } + return s; + } + + /* geneate a (script) pubkey hash of the address - used for when signing */ + r.pubkeyHash = function(address) { + var addr = coinjs.addressDecode(address); + var s = coinjs.script(); + s.writeOp(118); //OP_DUP + s.writeOp(169); //OP_HASH160 + s.writeBytes(addr.bytes); + s.writeOp(136); //OP_EQUALVERIFY + s.writeOp(172); //OP_CHECKSIG + return s; + } + + /* write to buffer */ + r.writeOp = function(op) { + this.buffer.push(op); + this.chunks.push(op); + return true; + } + + /* write bytes to buffer */ + r.writeBytes = function(data) { + if (data.length < 76) { //OP_PUSHDATA1 + this.buffer.push(data.length); + } else if (data.length <= 0xff) { + this.buffer.push(76); //OP_PUSHDATA1 + this.buffer.push(data.length); + } else if (data.length <= 0xffff) { + this.buffer.push(77); //OP_PUSHDATA2 + this.buffer.push(data.length & 0xff); + this.buffer.push((data.length >>> 8) & 0xff); + } else { + this.buffer.push(78); //OP_PUSHDATA4 + this.buffer.push(data.length & 0xff); + this.buffer.push((data.length >>> 8) & 0xff); + this.buffer.push((data.length >>> 16) & 0xff); + this.buffer.push((data.length >>> 24) & 0xff); + } + this.buffer = this.buffer.concat(data); + this.chunks.push(data); + return true; + } + + r.parse(); + return r; + } + + /* start of transaction functions */ + + /* create a new transaction object */ + coinjs.transaction = function() { + + var r = {}; + r.version = 1; + r.lock_time = 0; + r.ins = []; + r.outs = []; + r.witness = false; + r.timestamp = null; + r.block = null; + + /* add an input to a transaction */ + r.addinput = function(txid, index, script, sequence) { + var o = {}; + o.outpoint = { + 'hash': txid, + 'index': index + }; + o.script = coinjs.script(script || []); + o.sequence = sequence || ((r.lock_time == 0) ? 4294967295 : 0); + return this.ins.push(o); + } + + /* add an output to a transaction */ + r.addoutput = function(address, value) { + var o = {}; + o.value = new BigInteger('' + Math.round((value * 1) * 1e8), 10); + var s = coinjs.script(); + o.script = s.spendToScript(address); + + return this.outs.push(o); + } + + /* add two outputs for stealth addresses to a transaction */ + r.addstealth = function(stealth, value) { + var ephemeralKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(coinjs.newPrivkey())); + var curve = EllipticCurve.getSECCurveByName("secp256k1"); + + var p = EllipticCurve.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"); + var a = BigInteger.ZERO; + var b = EllipticCurve.fromHex("7"); + var calccurve = new EllipticCurve.CurveFp(p, a, b); + + var ephemeralPt = curve.getG().multiply(ephemeralKeyBigInt); + var scanPt = calccurve.decodePointHex(stealth.scankey); + var sharedPt = scanPt.multiply(ephemeralKeyBigInt); + var stealthindexKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.SHA256(sharedPt.getEncoded(true), { + asBytes: true + })); + + var stealthindexPt = curve.getG().multiply(stealthindexKeyBigInt); + var spendPt = calccurve.decodePointHex(stealth.spendkey); + var addressPt = spendPt.add(stealthindexPt); + + var sendaddress = coinjs.pubkey2address(Crypto.util.bytesToHex(addressPt.getEncoded(true))); + + + var OPRETBytes = [6].concat(Crypto.util.randomBytes(4)).concat(ephemeralPt.getEncoded(true)); // ephemkey data + var q = coinjs.script(); + q.writeOp(106); // OP_RETURN + q.writeBytes(OPRETBytes); + v = {}; + v.value = 0; + v.script = q; + + this.outs.push(v); + + var o = {}; + o.value = new BigInteger('' + Math.round((value * 1) * 1e8), 10); + var s = coinjs.script(); + o.script = s.spendToScript(sendaddress); + + return this.outs.push(o); + } + + /* add data to a transaction */ + r.adddata = function(data) { + var r = false; + if (((data.match(/^[a-f0-9]+$/gi)) && data.length < 160) && (data.length % 2) == 0) { + var s = coinjs.script(); + s.writeOp(106); // OP_RETURN + s.writeBytes(Crypto.util.hexToBytes(data)); + o = {}; + o.value = 0; + o.script = s; + return this.outs.push(o); + } + return r; + } + + /* list unspent transactions */ + r.listUnspent = function(address, callback) { + coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=unspent&address=' + address + '&r=' + Math.random(), callback, "GET"); + } + + /* list transaction data */ + r.getTransaction = function(txid, callback) { + coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=bitcoin&request=gettransaction&txid=' + txid + '&r=' + Math.random(), callback, "GET"); + } + + /* add unspent to transaction */ + r.addUnspent = function(address, callback, script, segwit, sequence) { + var self = this; + this.listUnspent(address, function(data) { + var s = coinjs.script(); + var value = 0; + var total = 0; + var x = {}; + + if (GLOBAL.DOMParser) { + parser = new DOMParser(); + xmlDoc = parser.parseFromString(data, "text/xml"); + } else { + xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); + xmlDoc.async = false; + xmlDoc.loadXML(data); + } + + var unspent = xmlDoc.getElementsByTagName("unspent")[0]; + + if (unspent) { + for (i = 1; i <= unspent.childElementCount; i++) { + var u = xmlDoc.getElementsByTagName("unspent_" + i)[0] + var txhash = (u.getElementsByTagName("tx_hash")[0].childNodes[0].nodeValue).match(/.{1,2}/g).reverse().join("") + ''; + var n = u.getElementsByTagName("tx_output_n")[0].childNodes[0].nodeValue; + var scr = script || u.getElementsByTagName("script")[0].childNodes[0].nodeValue; + + if (segwit) { + /* this is a small hack to include the value with the redeemscript to make the signing procedure smoother. + It is not standard and removed during the signing procedure. */ + + s = coinjs.script(); + s.writeBytes(Crypto.util.hexToBytes(script)); + s.writeOp(0); + s.writeBytes(coinjs.numToBytes(u.getElementsByTagName("value")[0].childNodes[0].nodeValue * 1, 8)); + scr = Crypto.util.bytesToHex(s.buffer); + } + + var seq = sequence || false; + self.addinput(txhash, n, scr, seq); + value += u.getElementsByTagName("value")[0].childNodes[0].nodeValue * 1; + total++; + } + } + + x.result = xmlDoc.getElementsByTagName("result")[0].childNodes[0].nodeValue; + x.unspent = unspent; + x.value = value; + x.total = total; + x.response = xmlDoc.getElementsByTagName("response")[0].childNodes[0].nodeValue; + + return callback(x); + }); + } + + /* add unspent and sign */ + r.addUnspentAndSign = function(wif, callback) { + var self = this; + var address = coinjs.wif2address(wif); + self.addUnspent(address['address'], function(data) { + self.sign(wif); + return callback(data); + }); + } + + /* broadcast a transaction */ + r.broadcast = function(callback, txhex) { + var tx = txhex || this.serialize(); + coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=bitcoin&request=sendrawtransaction', callback, "POST", ["rawtx=" + tx]); + } + + /* generate the transaction hash to sign from a transaction input */ + r.transactionHash = function(index, sigHashType) { + + var clone = coinjs.clone(this); + var shType = sigHashType || 1; + + /* black out all other ins, except this one */ + for (var i = 0; i < clone.ins.length; i++) { + if (index != i) { + clone.ins[i].script = coinjs.script(); + } + } + + var extract = this.extractScriptKey(index); + clone.ins[index].script = coinjs.script(extract['script']); + + if ((clone.ins) && clone.ins[index]) { + + /* SIGHASH : For more info on sig hashs see https://en.bitcoin.it/wiki/OP_CHECKSIG + and https://bitcoin.org/en/developer-guide#signature-hash-type */ + + if (shType == 1) { + //SIGHASH_ALL 0x01 + + } else if (shType == 2) { + //SIGHASH_NONE 0x02 + clone.outs = []; + for (var i = 0; i < clone.ins.length; i++) { + if (index != i) { + clone.ins[i].sequence = 0; + } + } + + } else if (shType == 3) { + + //SIGHASH_SINGLE 0x03 + clone.outs.length = index + 1; + + for (var i = 0; i < index; i++) { + clone.outs[i].value = -1; + clone.outs[i].script.buffer = []; + } + + for (var i = 0; i < clone.ins.length; i++) { + if (index != i) { + clone.ins[i].sequence = 0; + } + } + + } else if (shType >= 128) { + //SIGHASH_ANYONECANPAY 0x80 + clone.ins = [clone.ins[index]]; + + if (shType == 129) { + // SIGHASH_ALL + SIGHASH_ANYONECANPAY + + } else if (shType == 130) { + // SIGHASH_NONE + SIGHASH_ANYONECANPAY + clone.outs = []; + + } else if (shType == 131) { + // SIGHASH_SINGLE + SIGHASH_ANYONECANPAY + clone.outs.length = index + 1; + for (var i = 0; i < index; i++) { + clone.outs[i].value = -1; + clone.outs[i].script.buffer = []; + } + } + } + + var buffer = Crypto.util.hexToBytes(clone.serialize()); + buffer = buffer.concat(coinjs.numToBytes(parseInt(shType), 4)); + var hash = Crypto.SHA256(buffer, { + asBytes: true + }); + var r = Crypto.util.bytesToHex(Crypto.SHA256(hash, { + asBytes: true + })); + return r; + } else { + return false; + } + } + + /* generate a segwit transaction hash to sign from a transaction input */ + r.transactionHashSegWitV0 = function(index, sigHashType) { + /* + Notice: coinb.in by default, deals with segwit transactions in a non-standard way. + Segwit transactions require that input values are included in the transaction hash. + To save wasting resources and potentially slowing down this service, we include the amount with the + redeem script to generate the transaction hash and remove it after its signed. + */ + + // start redeem script check + var extract = this.extractScriptKey(index); + if (extract['type'] != 'segwit') { + return { + 'result': 0, + 'fail': 'redeemscript', + 'response': 'redeemscript missing or not valid for segwit' + }; + } + + if (extract['value'] == -1) { + return { + 'result': 0, + 'fail': 'value', + 'response': 'unable to generate a valid segwit hash without a value' + }; + } + + var scriptcode = Crypto.util.hexToBytes(extract['script']); + + // end of redeem script check + + /* P2WPKH */ + if (scriptcode.length == 20) { + scriptcode = [0x00, 0x14].concat(scriptcode); + } + + if (scriptcode.length == 22) { + scriptcode = scriptcode.slice(1); + scriptcode.unshift(25, 118, 169); + scriptcode.push(136, 172); + } + + var value = coinjs.numToBytes(extract['value'], 8); + + // start + + var zero = coinjs.numToBytes(0, 32); + var version = coinjs.numToBytes(parseInt(this.version), 4); + + var bufferTmp = []; + if (!(sigHashType >= 80)) { // not sighash anyonecanpay + for (var i = 0; i < this.ins.length; i++) { + bufferTmp = bufferTmp.concat(Crypto.util.hexToBytes(this.ins[i].outpoint.hash).reverse()); + bufferTmp = bufferTmp.concat(coinjs.numToBytes(this.ins[i].outpoint.index, 4)); + } + } + var hashPrevouts = bufferTmp.length >= 1 ? Crypto.SHA256(Crypto.SHA256(bufferTmp, { + asBytes: true + }), { + asBytes: true + }) : zero; + + var bufferTmp = []; + if (!(sigHashType >= 80) && sigHashType != 2 && sigHashType != 3) { // not sighash anyonecanpay & single & none + for (var i = 0; i < this.ins.length; i++) { + bufferTmp = bufferTmp.concat(coinjs.numToBytes(this.ins[i].sequence, 4)); + } + } + var hashSequence = bufferTmp.length >= 1 ? Crypto.SHA256(Crypto.SHA256(bufferTmp, { + asBytes: true + }), { + asBytes: true + }) : zero; + + var outpoint = Crypto.util.hexToBytes(this.ins[index].outpoint.hash).reverse(); + outpoint = outpoint.concat(coinjs.numToBytes(this.ins[index].outpoint.index, 4)); + + var nsequence = coinjs.numToBytes(this.ins[index].sequence, 4); + var hashOutputs = zero; + var bufferTmp = []; + if (sigHashType != 2 && sigHashType != 3) { // not sighash single & none + for (var i = 0; i < this.outs.length; i++) { + bufferTmp = bufferTmp.concat(coinjs.numToBytes(this.outs[i].value, 8)); + bufferTmp = bufferTmp.concat(coinjs.numToVarInt(this.outs[i].script.buffer.length)); + bufferTmp = bufferTmp.concat(this.outs[i].script.buffer); + } + hashOutputs = Crypto.SHA256(Crypto.SHA256(bufferTmp, { + asBytes: true + }), { + asBytes: true + }); + + } else if ((sigHashType == 2) && index < this.outs.length) { // is sighash single + bufferTmp = bufferTmp.concat(coinjs.numToBytes(this.outs[index].value, 8)); + bufferTmp = bufferTmp.concat(coinjs.numToVarInt(this.outs[i].script.buffer.length)); + bufferTmp = bufferTmp.concat(this.outs[index].script.buffer); + hashOutputs = Crypto.SHA256(Crypto.SHA256(bufferTmp, { + asBytes: true + }), { + asBytes: true + }); + } + + var locktime = coinjs.numToBytes(this.lock_time, 4); + var sighash = coinjs.numToBytes(sigHashType, 4); + + var buffer = []; + buffer = buffer.concat(version); + buffer = buffer.concat(hashPrevouts); + buffer = buffer.concat(hashSequence); + buffer = buffer.concat(outpoint); + buffer = buffer.concat(scriptcode); + buffer = buffer.concat(value); + buffer = buffer.concat(nsequence); + buffer = buffer.concat(hashOutputs); + buffer = buffer.concat(locktime); + buffer = buffer.concat(sighash); + + var hash = Crypto.SHA256(buffer, { + asBytes: true + }); + return { + 'result': 1, + 'hash': Crypto.util.bytesToHex(Crypto.SHA256(hash, { + asBytes: true + })), + 'response': 'hash generated' + }; + } + + /* extract the scriptSig, used in the transactionHash() function */ + r.extractScriptKey = function(index) { + if (this.ins[index]) { + if ((this.ins[index].script.chunks.length == 5) && this.ins[index].script.chunks[4] == 172 && coinjs.isArray(this.ins[index].script.chunks[2])) { //OP_CHECKSIG + // regular scriptPubkey (not signed) + return { + 'type': 'scriptpubkey', + 'signed': 'false', + 'signatures': 0, + 'script': Crypto.util.bytesToHex(this.ins[index].script.buffer) + }; + } else if ((this.ins[index].script.chunks.length == 2) && this.ins[index].script.chunks[0][0] == 48 && this.ins[index].script.chunks[1].length == 5 && this.ins[index].script.chunks[1][1] == 177) { //OP_CHECKLOCKTIMEVERIFY + // hodl script (signed) + return { + 'type': 'hodl', + 'signed': 'true', + 'signatures': 1, + 'script': Crypto.util.bytesToHex(this.ins[index].script.buffer) + }; + } else if ((this.ins[index].script.chunks.length == 2) && this.ins[index].script.chunks[0][0] == 48) { + // regular scriptPubkey (probably signed) + return { + 'type': 'scriptpubkey', + 'signed': 'true', + 'signatures': 1, + 'script': Crypto.util.bytesToHex(this.ins[index].script.buffer) + }; + } else if (this.ins[index].script.chunks.length == 5 && this.ins[index].script.chunks[1] == 177) { //OP_CHECKLOCKTIMEVERIFY + // hodl script (not signed) + return { + 'type': 'hodl', + 'signed': 'false', + 'signatures': 0, + 'script': Crypto.util.bytesToHex(this.ins[index].script.buffer) + }; + } else if ((this.ins[index].script.chunks.length <= 3 && this.ins[index].script.chunks.length > 0) && ((this.ins[index].script.chunks[0].length == 22 && this.ins[index].script.chunks[0][0] == 0) || (this.ins[index].script.chunks[0].length == 20 && this.ins[index].script.chunks[1] == 0))) { + var signed = ((this.witness[index]) && this.witness[index].length == 2) ? 'true' : 'false'; + var sigs = (signed == 'true') ? 1 : 0; + var value = -1; // no value found + if ((this.ins[index].script.chunks[2]) && this.ins[index].script.chunks[2].length == 8) { + value = coinjs.bytesToNum(this.ins[index].script.chunks[2]); // value found encoded in transaction (THIS IS NON STANDARD) + } + return { + 'type': 'segwit', + 'signed': signed, + 'signatures': sigs, + 'script': Crypto.util.bytesToHex(this.ins[index].script.chunks[0]), + 'value': value + }; + } else if (this.ins[index].script.chunks[0] == 0 && this.ins[index].script.chunks[this.ins[index].script.chunks.length - 1][this.ins[index].script.chunks[this.ins[index].script.chunks.length - 1].length - 1] == 174) { // OP_CHECKMULTISIG + // multisig script, with signature(s) included + var sigcount = 0; + for (i = 1; i < this.ins[index].script.chunks.length - 1; i++) { + if (this.ins[index].script.chunks[i] != 0) { + sigcount++; + } + } + + return { + 'type': 'multisig', + 'signed': 'true', + 'signatures': sigcount, + 'script': Crypto.util.bytesToHex(this.ins[index].script.chunks[this.ins[index].script.chunks.length - 1]) + }; + } else if (this.ins[index].script.chunks[0] >= 80 && this.ins[index].script.chunks[this.ins[index].script.chunks.length - 1] == 174) { // OP_CHECKMULTISIG + // multisig script, without signature! + return { + 'type': 'multisig', + 'signed': 'false', + 'signatures': 0, + 'script': Crypto.util.bytesToHex(this.ins[index].script.buffer) + }; + } else if (this.ins[index].script.chunks.length == 0) { + // empty + //bech32 witness check + var signed = ((this.witness[index]) && this.witness[index].length == 2) ? 'true' : 'false'; + var sigs = (signed == 'true') ? 1 : 0; + return { + 'type': 'empty', + 'signed': signed, + 'signatures': sigs, + 'script': '' + }; + } else { + // something else + return { + 'type': 'unknown', + 'signed': 'false', + 'signatures': 0, + 'script': Crypto.util.bytesToHex(this.ins[index].script.buffer) + }; + } + } else { + return false; + } + } + + /* generate a signature from a transaction hash */ + r.transactionSig = function(index, wif, sigHashType, txhash) { + + function serializeSig(r, s) { + var rBa = r.toByteArraySigned(); + var sBa = s.toByteArraySigned(); + + var sequence = []; + sequence.push(0x02); // INTEGER + sequence.push(rBa.length); + sequence = sequence.concat(rBa); + + sequence.push(0x02); // INTEGER + sequence.push(sBa.length); + sequence = sequence.concat(sBa); + + sequence.unshift(sequence.length); + sequence.unshift(0x30); // SEQUENCE + + return sequence; + } + + var shType = sigHashType || 1; + var hash = txhash || Crypto.util.hexToBytes(this.transactionHash(index, shType)); + + if (hash) { + var curve = EllipticCurve.getSECCurveByName("secp256k1"); + var key = coinjs.wif2privkey(wif); + var priv = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(key['privkey'])); + var n = curve.getN(); + var e = BigInteger.fromByteArrayUnsigned(hash); + var badrs = 0 + do { + var k = this.deterministicK(wif, hash, badrs); + var G = curve.getG(); + var Q = G.multiply(k); + var r = Q.getX().toBigInteger().mod(n); + var s = k.modInverse(n).multiply(e.add(priv.multiply(r))).mod(n); + badrs++ + } while (r.compareTo(BigInteger.ZERO) <= 0 || s.compareTo(BigInteger.ZERO) <= 0); + + // Force lower s values per BIP62 + var halfn = n.shiftRight(1); + if (s.compareTo(halfn) > 0) { + s = n.subtract(s); + }; + + var sig = serializeSig(r, s); + sig.push(parseInt(shType, 10)); + + return Crypto.util.bytesToHex(sig); + } else { + return false; + } + } + + // https://tools.ietf.org/html/rfc6979#section-3.2 + r.deterministicK = function(wif, hash, badrs) { + // if r or s were invalid when this function was used in signing, + // we do not want to actually compute r, s here for efficiency, so, + // we can increment badrs. explained at end of RFC 6979 section 3.2 + + // wif is b58check encoded wif privkey. + // hash is byte array of transaction digest. + // badrs is used only if the k resulted in bad r or s. + + // some necessary things out of the way for clarity. + badrs = badrs || 0; + var key = coinjs.wif2privkey(wif); + var x = Crypto.util.hexToBytes(key['privkey']) + var curve = EllipticCurve.getSECCurveByName("secp256k1"); + var N = curve.getN(); + + // Step: a + // hash is a byteArray of the message digest. so h1 == hash in our case + + // Step: b + var v = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; + + // Step: c + var k = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + + // Step: d + k = Crypto.HMAC(Crypto.SHA256, v.concat([0]).concat(x).concat(hash), k, { + asBytes: true + }); + + // Step: e + v = Crypto.HMAC(Crypto.SHA256, v, k, { + asBytes: true + }); + + // Step: f + k = Crypto.HMAC(Crypto.SHA256, v.concat([1]).concat(x).concat(hash), k, { + asBytes: true + }); + + // Step: g + v = Crypto.HMAC(Crypto.SHA256, v, k, { + asBytes: true + }); + + // Step: h1 + var T = []; + + // Step: h2 (since we know tlen = qlen, just copy v to T.) + v = Crypto.HMAC(Crypto.SHA256, v, k, { + asBytes: true + }); + T = v; + + // Step: h3 + var KBigInt = BigInteger.fromByteArrayUnsigned(T); + + // loop if KBigInt is not in the range of [1, N-1] or if badrs needs incrementing. + var i = 0 + while (KBigInt.compareTo(N) >= 0 || KBigInt.compareTo(BigInteger.ZERO) <= 0 || i < badrs) { + k = Crypto.HMAC(Crypto.SHA256, v.concat([0]), k, { + asBytes: true + }); + v = Crypto.HMAC(Crypto.SHA256, v, k, { + asBytes: true + }); + v = Crypto.HMAC(Crypto.SHA256, v, k, { + asBytes: true + }); + T = v; + KBigInt = BigInteger.fromByteArrayUnsigned(T); + i++ + }; + + return KBigInt; + }; + + /* sign a "standard" input */ + r.signinput = function(index, wif, sigHashType) { + var key = coinjs.wif2pubkey(wif); + var shType = sigHashType || 1; + var signature = this.transactionSig(index, wif, shType); + var s = coinjs.script(); + s.writeBytes(Crypto.util.hexToBytes(signature)); + s.writeBytes(Crypto.util.hexToBytes(key['pubkey'])); + this.ins[index].script = s; + return true; + } + + /* signs a time locked / hodl input */ + r.signhodl = function(index, wif, sigHashType) { + var shType = sigHashType || 1; + var signature = this.transactionSig(index, wif, shType); + var redeemScript = this.ins[index].script.buffer + var s = coinjs.script(); + s.writeBytes(Crypto.util.hexToBytes(signature)); + s.writeBytes(redeemScript); + this.ins[index].script = s; + return true; + } + + /* sign a multisig input */ + r.signmultisig = function(index, wif, sigHashType) { + + function scriptListPubkey(redeemScript) { + var r = {}; + for (var i = 1; i < redeemScript.chunks.length - 2; i++) { + r[i] = Crypto.util.hexToBytes(coinjs.pubkeydecompress(Crypto.util.bytesToHex(redeemScript.chunks[i]))); + } + return r; + } + + function scriptListSigs(scriptSig) { + var r = {}; + var c = 0; + if (scriptSig.chunks[0] == 0 && scriptSig.chunks[scriptSig.chunks.length - 1][scriptSig.chunks[scriptSig.chunks.length - 1].length - 1] == 174) { + for (var i = 1; i < scriptSig.chunks.length - 1; i++) { + if (scriptSig.chunks[i] != 0) { + c++; + r[c] = scriptSig.chunks[i]; + } + } + } + return r; + } + + var redeemScript = (this.ins[index].script.chunks[this.ins[index].script.chunks.length - 1] == 174) ? this.ins[index].script.buffer : this.ins[index].script.chunks[this.ins[index].script.chunks.length - 1]; + + var pubkeyList = scriptListPubkey(coinjs.script(redeemScript)); + var sigsList = scriptListSigs(this.ins[index].script); + + var shType = sigHashType || 1; + var sighash = Crypto.util.hexToBytes(this.transactionHash(index, shType)); + var signature = Crypto.util.hexToBytes(this.transactionSig(index, wif, shType)); + + sigsList[coinjs.countObject(sigsList) + 1] = signature; + + var s = coinjs.script(); + + s.writeOp(0); + + for (x in pubkeyList) { + for (y in sigsList) { + this.ins[index].script.buffer = redeemScript; + sighash = Crypto.util.hexToBytes(this.transactionHash(index, sigsList[y].slice(-1)[0] * 1)); + if (coinjs.verifySignature(sighash, sigsList[y], pubkeyList[x])) { + s.writeBytes(sigsList[y]); + } + } + } + + s.writeBytes(redeemScript); + this.ins[index].script = s; + return true; + } + + /* sign segwit input */ + r.signsegwit = function(index, wif, sigHashType) { + var shType = sigHashType || 1; + + var wif2 = coinjs.wif2pubkey(wif); + var segwit = coinjs.segwitAddress(wif2['pubkey']); + var bech32 = coinjs.bech32Address(wif2['pubkey']); + + if ((segwit['redeemscript'] == Crypto.util.bytesToHex(this.ins[index].script.chunks[0])) || (bech32['redeemscript'] == Crypto.util.bytesToHex(this.ins[index].script.chunks[0]))) { + var txhash = this.transactionHashSegWitV0(index, shType); + + if (txhash.result == 1) { + + var segwitHash = Crypto.util.hexToBytes(txhash.hash); + var signature = this.transactionSig(index, wif, shType, segwitHash); + + // remove any non standard data we store, i.e. input value + var script = coinjs.script(); + script.writeBytes(this.ins[index].script.chunks[0]); + this.ins[index].script = script; + + if (!coinjs.isArray(this.witness)) { + this.witness = new Array(this.ins.length); + this.witness.fill([]); + } + + this.witness[index] = ([signature, wif2['pubkey']]); + + // bech32, empty redeemscript + if (bech32['redeemscript'] == Crypto.util.bytesToHex(this.ins[index].script.chunks[0])) { + this.ins[index].script = coinjs.script(); + } + + /* attempt to reorder witness data as best as we can. + data can't be easily validated at this stage as + we dont have access to the inputs value and + making a web call will be too slow. */ + + /* + var witness_order = []; + var witness_used = []; + for (var i = 0; i < this.ins.length; i++) { + for (var y = 0; y < this.witness.length; y++) { + if (!witness_used.includes(y)) { + var sw = coinjs.segwitAddress(this.witness[y][1]); + var b32 = coinjs.bech32Address(this.witness[y][1]); + var rs = ''; + + if (this.ins[i].script.chunks.length >= 1) { + rs = Crypto.util.bytesToHex(this.ins[i].script.chunks[0]); + } else if (this.ins[i].script.chunks.length == 0) { + rs = b32['redeemscript']; + } + + if ((sw['redeemscript'] == rs) || (b32['redeemscript'] == rs)) { + witness_order.push(this.witness[y]); + witness_used.push(y); + + // bech32, empty redeemscript + if (b32['redeemscript'] == rs) { + this.ins[index].script = coinjs.script(); + } + break; + } + } + } + } + + this.witness = witness_order; + */ + } + } + return true; + } + + /* sign inputs */ + r.sign = function(wif, sigHashType) { + var shType = sigHashType || 1; + for (var i = 0; i < this.ins.length; i++) { + var d = this.extractScriptKey(i); + + var w2a = coinjs.wif2address(wif); + var script = coinjs.script(); + var pubkeyHash = script.pubkeyHash(w2a['address']); + + if (((d['type'] == 'scriptpubkey' && d['script'] == Crypto.util.bytesToHex(pubkeyHash.buffer)) || d['type'] == 'empty') && d['signed'] == "false") { + this.signinput(i, wif, shType); + + } else if (d['type'] == 'hodl' && d['signed'] == "false") { + this.signhodl(i, wif, shType); + + } else if (d['type'] == 'multisig') { + this.signmultisig(i, wif, shType); + + } else if (d['type'] == 'segwit') { + this.signsegwit(i, wif, shType); + + } else { + // could not sign + } + } + return this.serialize(); + } + + /* serialize a transaction */ + r.serialize = function() { + var buffer = []; + buffer = buffer.concat(coinjs.numToBytes(parseInt(this.version), 4)); + + if (coinjs.isArray(this.witness)) { + buffer = buffer.concat([0x00, 0x01]); + } + + buffer = buffer.concat(coinjs.numToVarInt(this.ins.length)); + for (var i = 0; i < this.ins.length; i++) { + var txin = this.ins[i]; + buffer = buffer.concat(Crypto.util.hexToBytes(txin.outpoint.hash).reverse()); + buffer = buffer.concat(coinjs.numToBytes(parseInt(txin.outpoint.index), 4)); + var scriptBytes = txin.script.buffer; + buffer = buffer.concat(coinjs.numToVarInt(scriptBytes.length)); + buffer = buffer.concat(scriptBytes); + buffer = buffer.concat(coinjs.numToBytes(parseInt(txin.sequence), 4)); + } + buffer = buffer.concat(coinjs.numToVarInt(this.outs.length)); + + for (var i = 0; i < this.outs.length; i++) { + var txout = this.outs[i]; + buffer = buffer.concat(coinjs.numToBytes(txout.value, 8)); + var scriptBytes = txout.script.buffer; + buffer = buffer.concat(coinjs.numToVarInt(scriptBytes.length)); + buffer = buffer.concat(scriptBytes); + } + + if ((coinjs.isArray(this.witness)) && this.witness.length >= 1) { + for (var i = 0; i < this.witness.length; i++) { + buffer = buffer.concat(coinjs.numToVarInt(this.witness[i].length)); + for (var x = 0; x < this.witness[i].length; x++) { + buffer = buffer.concat(coinjs.numToVarInt(Crypto.util.hexToBytes(this.witness[i][x]).length)); + buffer = buffer.concat(Crypto.util.hexToBytes(this.witness[i][x])); + } + } + } + + buffer = buffer.concat(coinjs.numToBytes(parseInt(this.lock_time), 4)); + return Crypto.util.bytesToHex(buffer); + } + + /* deserialize a transaction */ + r.deserialize = function(buffer) { + if (typeof buffer == "string") { + buffer = Crypto.util.hexToBytes(buffer) + } + + var pos = 0; + var witness = false; + + var readAsInt = function(bytes) { + if (bytes == 0) return 0; + pos++; + return buffer[pos - 1] + readAsInt(bytes - 1) * 256; + } + + var readVarInt = function() { + pos++; + if (buffer[pos - 1] < 253) { + return buffer[pos - 1]; + } + return readAsInt(buffer[pos - 1] - 251); + } + + var readBytes = function(bytes) { + pos += bytes; + return buffer.slice(pos - bytes, pos); + } + + var readVarString = function() { + var size = readVarInt(); + return readBytes(size); + } + + var obj = new coinjs.transaction(); + obj.version = readAsInt(4); + + if (buffer[pos] == 0x00 && buffer[pos + 1] == 0x01) { + // segwit transaction + witness = true; + obj.witness = []; + pos += 2; + } + + var ins = readVarInt(); + for (var i = 0; i < ins; i++) { + obj.ins.push({ + outpoint: { + hash: Crypto.util.bytesToHex(readBytes(32).reverse()), + index: readAsInt(4) + }, + script: coinjs.script(readVarString()), + sequence: readAsInt(4) + }); + } + + var outs = readVarInt(); + for (var i = 0; i < outs; i++) { + obj.outs.push({ + value: coinjs.bytesToNum(readBytes(8)), + script: coinjs.script(readVarString()) + }); + } + + if (witness == true) { + for (i = 0; i < ins; ++i) { + var count = readVarInt(); + var vector = []; + if (!coinjs.isArray(obj.witness[i])) { + obj.witness[i] = []; + } + for (var y = 0; y < count; y++) { + var slice = readVarInt(); + pos += slice; + obj.witness[i].push(Crypto.util.bytesToHex(buffer.slice(pos - slice, pos))); + } + } + } + + obj.lock_time = readAsInt(4); + return obj; + } + + r.size = function() { + return ((this.serialize()).length / 2).toFixed(0); + } + + return r; + } + + /* start of signature vertification functions */ + + coinjs.verifySignature = function(hash, sig, pubkey) { + + function parseSig(sig) { + var cursor; + if (sig[0] != 0x30) + throw new Error("Signature not a valid DERSequence"); + + cursor = 2; + if (sig[cursor] != 0x02) + throw new Error("First element in signature must be a DERInteger");; + + var rBa = sig.slice(cursor + 2, cursor + 2 + sig[cursor + 1]); + + cursor += 2 + sig[cursor + 1]; + if (sig[cursor] != 0x02) + throw new Error("Second element in signature must be a DERInteger"); + + var sBa = sig.slice(cursor + 2, cursor + 2 + sig[cursor + 1]); + + cursor += 2 + sig[cursor + 1]; + + var r = BigInteger.fromByteArrayUnsigned(rBa); + var s = BigInteger.fromByteArrayUnsigned(sBa); + + return { + r: r, + s: s + }; + } + + var r, s; + + if (coinjs.isArray(sig)) { + var obj = parseSig(sig); + r = obj.r; + s = obj.s; + } else if ("object" === typeof sig && sig.r && sig.s) { + r = sig.r; + s = sig.s; + } else { + throw "Invalid value for signature"; + } + + var Q; + if (coinjs.isArray(pubkey)) { + var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); + Q = EllipticCurve.PointFp.decodeFrom(ecparams.getCurve(), pubkey); + } else { + throw "Invalid format for pubkey value, must be byte array"; + } + var e = BigInteger.fromByteArrayUnsigned(hash); + + return coinjs.verifySignatureRaw(e, r, s, Q); + } + + coinjs.verifySignatureRaw = function(e, r, s, Q) { + var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); + var n = ecparams.getN(); + var G = ecparams.getG(); + + if (r.compareTo(BigInteger.ONE) < 0 || r.compareTo(n) >= 0) + return false; + + if (s.compareTo(BigInteger.ONE) < 0 || s.compareTo(n) >= 0) + return false; + + var c = s.modInverse(n); + + var u1 = e.multiply(c).mod(n); + var u2 = r.multiply(c).mod(n); + + var point = G.multiply(u1).add(Q.multiply(u2)); + + var v = point.getX().toBigInteger().mod(n); + + return v.equals(r); + } + + /* start of privates functions */ + + /* base58 encode function */ + coinjs.base58encode = function(buffer) { + var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + var base = BigInteger.valueOf(58); + + var bi = BigInteger.fromByteArrayUnsigned(buffer); + var chars = []; + + while (bi.compareTo(base) >= 0) { + var mod = bi.mod(base); + chars.unshift(alphabet[mod.intValue()]); + bi = bi.subtract(mod).divide(base); + } + + chars.unshift(alphabet[bi.intValue()]); + for (var i = 0; i < buffer.length; i++) { + if (buffer[i] == 0x00) { + chars.unshift(alphabet[0]); + } else break; + } + return chars.join(''); + } + + /* base58 decode function */ + coinjs.base58decode = function(buffer) { + var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + var base = BigInteger.valueOf(58); + var validRegex = /^[1-9A-HJ-NP-Za-km-z]+$/; + + var bi = BigInteger.valueOf(0); + var leadingZerosNum = 0; + for (var i = buffer.length - 1; i >= 0; i--) { + var alphaIndex = alphabet.indexOf(buffer[i]); + if (alphaIndex < 0) { + throw "Invalid character"; + } + bi = bi.add(BigInteger.valueOf(alphaIndex).multiply(base.pow(buffer.length - 1 - i))); + + if (buffer[i] == "1") leadingZerosNum++; + else leadingZerosNum = 0; + } + + var bytes = bi.toByteArrayUnsigned(); + while (leadingZerosNum-- > 0) bytes.unshift(0); + return bytes; + } + + /* raw ajax function to avoid needing bigger frame works like jquery, mootools etc */ + coinjs.ajax = function(u, f, m, a) { + var x = false; + try { + x = new ActiveXObject('Msxml2.XMLHTTP') + } catch (e) { + try { + x = new ActiveXObject('Microsoft.XMLHTTP') + } catch (e) { + x = new XMLHttpRequest() + } + } + + if (x == false) { + return false; + } + + x.open(m, u, true); + x.onreadystatechange = function() { + if ((x.readyState == 4) && f) + f(x.responseText); + }; + + if (m == 'POST') { + x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); + } + + x.send(a); + } + + /* clone an object */ + coinjs.clone = function(obj) { + if (obj == null || typeof(obj) != 'object') return obj; + var temp = new obj.constructor(); + + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + temp[key] = coinjs.clone(obj[key]); + } + } + return temp; + } + + coinjs.numToBytes = function(num, bytes) { + if (typeof bytes === "undefined") bytes = 8; + if (bytes == 0) { + return []; + } else if (num == -1) { + return Crypto.util.hexToBytes("ffffffffffffffff"); + } else { + return [num % 256].concat(coinjs.numToBytes(Math.floor(num / 256), bytes - 1)); + } + } + + function scriptNumSize(i) { + return i > 0x7fffffff ? 5 : + i > 0x7fffff ? 4 : + i > 0x7fff ? 3 : + i > 0x7f ? 2 : + i > 0x00 ? 1 : + 0; + } + + coinjs.numToScriptNumBytes = function(_number) { + var value = Math.abs(_number); + var size = scriptNumSize(value); + var result = []; + for (var i = 0; i < size; ++i) { + result.push(0); + } + var negative = _number < 0; + for (i = 0; i < size; ++i) { + result[i] = value & 0xff; + value = Math.floor(value / 256); + } + if (negative) { + result[size - 1] |= 0x80; + } + return result; + } + + coinjs.numToVarInt = function(num) { + if (num < 253) { + return [num]; + } else if (num < 65536) { + return [253].concat(coinjs.numToBytes(num, 2)); + } else if (num < 4294967296) { + return [254].concat(coinjs.numToBytes(num, 4)); + } else { + return [255].concat(coinjs.numToBytes(num, 8)); + } + } + + coinjs.bytesToNum = function(bytes) { + if (bytes.length == 0) return 0; + else return bytes[0] + 256 * coinjs.bytesToNum(bytes.slice(1)); + } + + coinjs.uint = function(f, size) { + if (f.length < size) + throw new Error("not enough data"); + var n = 0; + for (var i = 0; i < size; i++) { + n *= 256; + n += f[i]; + } + return n; + } + + coinjs.isArray = function(o) { + return Object.prototype.toString.call(o) === '[object Array]'; + } + + coinjs.countObject = function(obj) { + var count = 0; + var i; + for (i in obj) { + if (obj.hasOwnProperty(i)) { + count++; + } + } + return count; + } + + coinjs.random = function(length) { + var r = ""; + var l = length || 25; + var chars = "!$%^&*()_+{}:@~?><|\./;'#][=-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; + for (x = 0; x < l; x++) { + r += chars.charAt(Math.floor(Math.random() * 62)); + } + return r; + } + + })(); + //secrets.js (function() { //Shamir Secret Share by Alexander Stetsyuk - released under MIT License @@ -6786,5 +9341,4 @@ } })(); - })(typeof global !== "undefined" ? global : window); \ No newline at end of file From 2b8e77b5f783d24e47ccdf23e94dcdde66328f88 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 26 Jul 2022 15:16:22 +0530 Subject: [PATCH 206/289] Bug fixes - floCrypto.validateAddr: bech default=true - floCloudAPI: proxyID - commented coinjs api vars --- README.md | 2 +- floCloudAPI.js | 20 ++++++++++---------- floCrypto.js | 4 ++-- lib.js | 5 +++-- 4 files changed, 16 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index da60c69..17ff13a 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,7 @@ In addition, we have these system variables outside FLO Globals but used globall `validateAddr` check if the given Address (any blockchain) is valid or not 1. address - address to validate 2. std - checks for legacy version (optional, default=true) (true: allow any, array: list of versions, value: one version only, false: allow none) -3. bech - checks for bech version (optional, default=false) (true: allow any, array: list of versions, value: one version only, false: allow none) [requires additional library: [btc_api](https://ranchimall.github.io/btc-webwallet/lib_btc.js)] +3. bech - checks for bech version (optional, default=true) (true: allow any, array: list of versions, value: one version only, false: allow none) * Returns : boolen (true or false) #### Validate FLO ID diff --git a/floCloudAPI.js b/floCloudAPI.js index 3a06e0b..7d2dad2 100644 --- a/floCloudAPI.js +++ b/floCloudAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCloudAPI v2.4.2 +(function(EXPORTS) { //floCloudAPI v2.4.2a /* FLO Cloud operations to send/request application data*/ 'use strict'; const floCloudAPI = EXPORTS; @@ -217,7 +217,7 @@ if (_inactive.size === kBucket.list.length) return reject('Cloud offline'); if (!(snID in supernodes)) - snID = kBucket.closestNode(snID); + snID = kBucket.closestNode(proxyID(snID)); ws_connect(snID) .then(node => resolve(node)) .catch(error => { @@ -255,7 +255,7 @@ if (_inactive.size === kBucket.list.length) return reject('Cloud offline'); if (!(snID in supernodes)) - snID = kBucket.closestNode(snID); + snID = kBucket.closestNode(proxyID(snID)); fetch_API(snID, data) .then(result => resolve(result)) .catch(error => { @@ -370,11 +370,11 @@ const filterKey = util.filterKey = function(type, options) { return type + (options.comment ? ':' + options.comment : '') + - '|' + (options.group || toFloID(options.receiverID) || DEFAULT.adminID) + + '|' + (options.group || options.receiverID || DEFAULT.adminID) + '|' + (options.application || DEFAULT.application); } - const toFloID = util.toFloID = function(address) { + const proxyID = util.proxyID = function(address) { if (!address) return; var bytes; @@ -390,7 +390,7 @@ hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3] ? bytes = undefined : bytes.shift(); } else if (address.length == 42 || address.length == 62) { //bech encoding - if (!(coinjs instanceof Object)) + if (typeof coinjs !== 'function') throw "library missing (lib_btc.js)"; let decode = coinjs.bech32_decode(address); if (decode) { @@ -519,7 +519,7 @@ return new Promise((resolve, reject) => { var data = { senderID: user.id, - receiverID: toFloID(options.receiverID) || DEFAULT.adminID, + receiverID: options.receiverID || DEFAULT.adminID, pubKey: user.public, message: encodeMessage(message), time: Date.now(), @@ -540,7 +540,7 @@ const requestApplicationData = floCloudAPI.requestApplicationData = function(type, options = {}) { return new Promise((resolve, reject) => { var request = { - receiverID: toFloID(options.receiverID) || DEFAULT.adminID, + receiverID: options.receiverID || DEFAULT.adminID, senderID: options.senderID || undefined, application: options.application || DEFAULT.application, type: type, @@ -645,7 +645,7 @@ if (!floGlobals.subAdmins.includes(user.id)) return reject("Only subAdmins can tag data") var request = { - receiverID: toFloID(options.receiverID) || DEFAULT.adminID, + receiverID: options.receiverID || DEFAULT.adminID, requestorID: user.id, pubKey: user.public, time: Date.now(), @@ -664,7 +664,7 @@ floCloudAPI.noteApplicationData = function(vectorClock, note, options = {}) { return new Promise((resolve, reject) => { var request = { - receiverID: toFloID(options.receiverID) || DEFAULT.adminID, + receiverID: options.receiverID || DEFAULT.adminID, requestorID: user.id, pubKey: user.public, time: Date.now(), diff --git a/floCrypto.js b/floCrypto.js index 064c060..e32882e 100644 --- a/floCrypto.js +++ b/floCrypto.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCrypto v2.3.2a +(function(EXPORTS) { //floCrypto v2.3.2b /* FLO Crypto Operators */ 'use strict'; const floCrypto = EXPORTS; @@ -209,7 +209,7 @@ } //Check if the given address (any blockchain) is valid or not - floCrypto.validateAddr = function(address, std = true, bech = false) { + floCrypto.validateAddr = function(address, std = true, bech = true) { if (address.length == 34) { //legacy or segwit encoding if (std === false) return false; diff --git a/lib.js b/lib.js index a7e41fe..b55a81c 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function(GLOBAL) { //lib v1.3.0 +(function(GLOBAL) { //lib v1.3.0a 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -6312,11 +6312,12 @@ /* other vars */ coinjs.developer = '33tht1bKDgZVxb39MnZsWa8oxHXHvUYE4G'; //bitcoin - /* bit(coinb.in) api vars */ + /* bit(coinb.in) api vars coinjs.hostname = ((document.location.hostname.split(".")[(document.location.hostname.split(".")).length - 1]) == 'onion') ? 'coinbin3ravkwb24f7rmxx6w3snkjw45jhs5lxbh3yfeg3vpt6janwqd.onion' : 'coinb.in'; coinjs.host = ('https:' == document.location.protocol ? 'https://' : 'http://') + coinjs.hostname + '/api/'; coinjs.uid = '1'; coinjs.key = '12345678901234567890123456789012'; + */ /* start of address functions */ From f673d3f37a075adfc22fb2ab76ec91a7a8eda14b Mon Sep 17 00:00:00 2001 From: sairajzero Date: Wed, 27 Jul 2022 22:16:52 +0530 Subject: [PATCH 207/289] floCrypto v2.3.3a floCrypto.verifyPubKey: verify public key of any blockchain address - Parameters: 1. pubKeyHex - public key hex 2. address - blockchain address floCrypto.getAddress: get address respective to the blockchain - Parameters: 1. privateKeyHex - private key (WIF) 2. strict - (optional, default=false) if false returns floID when no match of privatekey prefix found. --- floCrypto.js | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/floCrypto.js b/floCrypto.js index e32882e..b252169 100644 --- a/floCrypto.js +++ b/floCrypto.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCrypto v2.3.2b +(function(EXPORTS) { //floCrypto v2.3.3a /* FLO Crypto Operators */ 'use strict'; const floCrypto = EXPORTS; @@ -7,6 +7,7 @@ const ecparams = EllipticCurve.getSECCurveByName("secp256k1"); const ascii_alternatives = `‘ '\n’ '\n“ "\n” "\n– --\n— ---\n≥ >=\n≤ <=\n≠ !=\n× *\n÷ /\n← <-\n→ ->\n↔ <->\n⇒ =>\n⇐ <=\n⇔ <=>`; const exponent1 = () => p.add(BigInteger.ONE).divide(BigInteger("4")); + coinjs.compressed = true; //defaulting coinjs compressed to true; function calculateY(x) { let exp = exponent1(); @@ -176,6 +177,25 @@ } } + floCrypto.getAddress = function(privateKeyHex, strict = false) { + if (!privateKeyHex) + return; + var key = new Bitcoin.ECKey(privateKeyHex); + if (key.priv == null) + return null; + key.setCompressed(true); + let pubKey = key.getPubKeyHex(), + version = bitjs.Base58.decode(privateKeyHex)[0]; + switch (version) { + case coinjs.priv: //BTC + return coinjs.bech32Address(pubKey).address; + case bitjs.priv: //FLO + return bitjs.pubkey2address(pubKey); + default: + return strict ? false : bitjs.pubkey2address(pubKey); //default to FLO address (if strict=false) + } + } + //Verify the private-key for the given public-key or flo-ID floCrypto.verifyPrivKey = function(privateKeyHex, pubKey_floID, isfloID = true) { if (!privateKeyHex || !pubKey_floID) @@ -242,6 +262,35 @@ return false; } + floCrypto.verifyPubKey = function(pubKeyHex, address) { + let pub_hash = Crypto.util.bytesToHex(ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubKeyHex), { + asBytes: true + }))); + if (address.length == 34) { //legacy encoding + let decode = bitjs.Base58.decode(address); + var raw = decode.slice(0, decode.length - 4), + checksum = decode.slice(decode.length - 4); + var hash = Crypto.SHA256(Crypto.SHA256(raw, { + asBytes: true + }), { + asBytes: true + }); + if (hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3]) + return false; + raw.shift(); + return pub_hash === Crypto.util.bytesToHex(raw); + } else if (address.length == 42 || address.length == 62) { //bech encoding + let decode = coinjs.bech32_decode(address); + if (!decode) + return false; + var raw = decode.data; + raw.shift(); + raw = coinjs.bech32_convert(raw, 5, 8, false); + return pub_hash === Crypto.util.bytesToHex(raw); + } else //unknown length + return false; + } + //Split the str using shamir's Secret and Returns the shares floCrypto.createShamirsSecretShares = function(str, total_shares, threshold_limit) { try { From 4bced4352d79b2f185dadd34cafa30b8363e7620 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 28 Jul 2022 02:24:26 +0530 Subject: [PATCH 208/289] floDapps, floCloudAPI: retain blkchain id on login floDapps login: - login to btc address when btc private key is entered - login to flo id when flo (or any other) private key is entered floCloudAPI user: - accept userID and private key for user set Others: - Fixed: minor bugs --- floCloudAPI.js | 76 +++++++++++++++++++++++++++----------------------- floDapps.js | 17 ++++++----- lib.js | 6 ++-- 3 files changed, 54 insertions(+), 45 deletions(-) diff --git a/floCloudAPI.js b/floCloudAPI.js index 7d2dad2..01560a1 100644 --- a/floCloudAPI.js +++ b/floCloudAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCloudAPI v2.4.2a +(function(EXPORTS) { //floCloudAPI v2.4.2b /* FLO Cloud operations to send/request application data*/ 'use strict'; const floCloudAPI = EXPORTS; @@ -12,27 +12,48 @@ }; var user_id, user_public, user_private, aes_key; - const user = { - get id() { - if (!user_id) - throw "User not set"; - return user_id; - }, - get public() { - if (!user_public) - throw "User not set"; - return user_public; - }, - sign(msg) { - if (!user_private) - throw "User not set"; - return floCrypto.signData(msg, Crypto.AES.decrypt(user_private, aes_key)); - }, - clear() { - user_id = user_public = user_private = aes_key = undefined; - } + + function user(id, priv) { + if (!priv || !id) + return user.clear(); + let pub = floCrypto.getPubKeyHex(priv); + if (!pub || !floCrypto.verifyPubKey(pub, id)) + return user.clear(); + let n = floCrypto.randInt(12, 20); + aes_key = floCrypto.randString(n); + user_private = Crypto.AES.encrypt(priv, aes_key); + user_public = pub; + user_id = id; + return user_id; } + Object.defineProperties(user, { + id: { + get: () => { + if (!user_id) + throw "User not set"; + return user_id; + } + }, + public: { + get: () => { + if (!user_public) + throw "User not set"; + return user_public; + } + }, + sign: { + value: msg => { + if (!user_private) + throw "User not set"; + return floCrypto.signData(msg, Crypto.AES.decrypt(user_private, aes_key)); + } + }, + clear: { + value: () => user_id = user_public = user_private = aes_key = undefined + } + }) + Object.defineProperties(floCloudAPI, { SNStorageID: { get: () => DEFAULT.SNStorageID @@ -44,21 +65,6 @@ get: () => DEFAULT.application }, user: { - set: priv => { - if (!priv) - user_id = user_public = user_private = aes_key = undefined; - else { - user_public = floCrypto.getPubKeyHex(priv); - user_id = floCrypto.getFloID(user_public); - if (!user_public || !user_id || !floCrypto.verifyPrivKey(priv, user_id)) - user_id = user_public = user_private = aes_key = undefined; - else { - let n = floCrypto.randInt(12, 20); - aes_key = floCrypto.randString(n); - user_private = Crypto.AES.encrypt(priv, aes_key); - } - } - }, get: () => user } }); diff --git a/floDapps.js b/floDapps.js index e5e2d6d..556e7fe 100644 --- a/floDapps.js +++ b/floDapps.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floDapps v2.3.2 +(function(EXPORTS) { //floDapps v2.3.2a /* General functions for FLO Dapps*/ 'use strict'; const floDapps = EXPORTS; @@ -75,6 +75,9 @@ myFloID: { get: () => user.id }, + myUserID: { + get: () => user.id + }, myPubKey: { get: () => user.public }, @@ -179,14 +182,14 @@ }).then(result => { for (var i = result.data.length - 1; i >= 0; i--) { var content = JSON.parse(result.data[i]).SuperNodeStorage; - for (sn in content.removeNodes) + for (let sn in content.removeNodes) compactIDB.removeData("supernodes", sn, DEFAULT.root); - for (sn in content.newNodes) + for (let sn in content.newNodes) compactIDB.writeData("supernodes", content.newNodes[sn], sn, DEFAULT.root); } compactIDB.writeData("lastTx", result.totalTxs, floCloudAPI.SNStorageID, DEFAULT.root); - compactIDB.readAllData("supernodes", DEFAULT.root).then(result => { - floCloudAPI.init(result) + compactIDB.readAllData("supernodes", DEFAULT.root).then(nodes => { + floCloudAPI.init(nodes) .then(result => resolve("Loaded Supernode list\n" + result)) .catch(error => reject(error)) }) @@ -342,8 +345,8 @@ checkIfPinRequired(key).then(privKey => { try { user_public = floCrypto.getPubKeyHex(privKey); - user_id = floCrypto.getFloID(privKey); - floCloudAPI.user = privKey; //Set user for floCloudAPI + user_id = floCrypto.getAddress(privKey); + floCloudAPI.user(user_id, privKey); //Set user for floCloudAPI user_priv_wrap = () => checkIfPinRequired(key); let n = floCrypto.randInt(12, 20); aes_key = floCrypto.randString(n); diff --git a/lib.js b/lib.js index b55a81c..26311f0 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function(GLOBAL) { //lib v1.3.0a +(function(GLOBAL) { //lib v1.3.0b 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -6353,7 +6353,7 @@ x += (document.getElementById("entropybucket")) ? document.getElementById("entropybucket").innerHTML : ''; x += x + '' + x; var r = x; - for (i = 0; i < (x).length / 25; i++) { + for (let i = 0; i < (x).length / 25; i++) { r = Crypto.SHA256(r.concat(x)); } var checkrBigInt = new BigInteger(r); @@ -8565,7 +8565,7 @@ var r = ""; var l = length || 25; var chars = "!$%^&*()_+{}:@~?><|\./;'#][=-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; - for (x = 0; x < l; x++) { + for (let x = 0; x < l; x++) { r += chars.charAt(Math.floor(Math.random() * 62)); } return r; From 9dd132b145d9d7bb47178660509e140fa23f39a8 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 28 Jul 2022 02:45:56 +0530 Subject: [PATCH 209/289] Update README.md --- README.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 17ff13a..3c47aa3 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ We are offering methods simplifying access to inbuilt browser database IndexedDB Last but not the least, we are also providing methods for simplying common operations for FLO based Distributed Application Development. # IMPORTANT -We have two versions of cloud: old cloud version is 2.0.x in floCloudAPI, and new cloud version is 2.1.x in floCloudAPI. Please check that the version in floCloudAPI is 2.1.x whenever you use floCloudAPI as we are deprecating version 2.0.x +We have two versions of cloud: old cloud version is 2.0.x in floCloudAPI, and new cloud version is >2.1.0 in floCloudAPI. Please check that the version in floCloudAPI is >2.1.0 whenever you use floCloudAPI as we are deprecating version 2.0.x # Background on FLO Distributed Applications @@ -208,6 +208,13 @@ In addition, we have these system variables outside FLO Globals but used globall 1. publickey_or_privateKey - public key or private key hex value * Returns : floID (string) +#### Calculate Address + floCrypto.getAddress(privateKey, *strict) +`getAddress` returns respective address from given private-key +1. privateKey - private key in WIF format +2. strict - boolean value (optional, default=false) (false: return flo-id if no prefix match is found) +* Returns : address (string) + #### Verify Private Key floCrypto.verifyPrivKey(privateKey, pubKey_floID, *isfloID) `verifyPrivKey` verify the private-key for the given public-key or flo-ID @@ -230,6 +237,13 @@ In addition, we have these system variables outside FLO Globals but used globall 1. floID - flo ID to validate * Returns : boolen (true or false) +#### Verify Public Key + floCrypto.verifyPubKey(publicKey, address) +`verifyPubKey` verify the public key for the given address (any blockchain) +1. publicKey - public key +2. address - address to verify +* Returns : boolen (true or false) + #### Data Encryption floCrypto.encryptData(data, publicKey) `encryptData` encrypts the given data using public-key From 4244774635e6531d20e40b0a70f878651c74b98c Mon Sep 17 00:00:00 2001 From: sairajzero Date: Wed, 3 Aug 2022 03:54:58 +0530 Subject: [PATCH 210/289] btcOperator v1.0.7 - Added createTx: Create an unsigned tx (no privkey required) [segwit sender not supported for now as redeem-script needed] - Added createMultiSigTx: Create an unsigned tx for multisig address - Optimised sendTx to reuse code (no functional change) --- btcOperator.js | 206 ++++++++++++++++++++++++++++++++++++------------- 1 file changed, 151 insertions(+), 55 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index f79cdb5..b3992b6 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //btcOperator v1.0.6 +(function(EXPORTS) { //btcOperator v1.0.7 /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -187,7 +187,7 @@ case "standard": return false; case "multisig": - return coinjs.segwitAddress(btcOperator.pubkey(key)).redeemscript; + return key ? coinjs.segwitAddress(btcOperator.pubkey(key)).redeemscript : null; case "bech32": return decode.redeemscript; default: @@ -195,6 +195,53 @@ } } + function validateTxParameters(parameters) { + let invalids = []; + //sender-ids + if (parameters.senders) { + if (!Array.isArray(parameters.senders)) + parameters.senders = [parameters.senders]; + parameters.senders.forEach(id => !validateAddress(id) ? invalids.push(id) : null); + if (invalids.length) + throw "Invalid senders:" + invalids; + } + if (parameters.privkeys) { + if (!Array.isArray(parameters.privkeys)) + parameters.privkeys = [parameters.privkeys]; + if (parameters.senders.length != parameters.privkeys.length) + throw "Array length for senders and privkeys should be equal"; + parameters.senders.forEach((id, i) => { + let key = parameters.privkeys[i]; + if (!verifyKey(id, key)) //verify private-key + invalids.push(id); + if (key.length === 64) //convert Hex to WIF if needed + parameters.privkeys[i] = coinjs.privkey2wif(key); + }); + if (invalids.length) + throw "Invalid keys:" + invalids; + } + //receiver-ids (and change-id) + if (!Array.isArray(parameters.receivers)) + parameters.receivers = [parameters.receivers]; + parameters.receivers.forEach(id => !validateAddress(id) ? invalids.push(id) : null); + if (invalids.length) + throw "Invalid receivers:" + invalids; + if (parameters.change_addr && !validateAddress(parameters.change_addr)) + throw "Invalid change_address:" + parameters.change_addr; + //fee and amounts + if (typeof parameters.fee !== "number" || parameters.fee <= 0) + throw "Invalid fee:" + parameters.fee; + if (!Array.isArray(parameters.amounts)) + parameters.amounts = [parameters.amounts]; + if (parameters.receivers.length != parameters.amounts.length) + throw "Array length for receivers and amounts should be equal"; + parameters.amounts.forEach(a => typeof a !== "number" || a <= 0 ? invalids.push(a) : null); + if (invalids.length) + throw "Invalid amounts:" + invalids; + //return + return parameters; + } + function addUTXOs(tx, senders, redeemScripts, required_amount, n = 0) { return new Promise((resolve, reject) => { required_amount = parseFloat(required_amount.toFixed(8)); @@ -227,70 +274,48 @@ }) } + function addOutputs(tx, receivers, amounts, change, change_addr) { + for (let i in receivers) + tx.addoutput(receivers[i], amounts[i]); + if (parseFloat(change.toFixed(8)) > 0) + tx.addoutput(change_addr || senders[0], change); + } + btcOperator.sendTx = function(senders, privkeys, receivers, amounts, fee, change_addr = null) { return new Promise((resolve, reject) => { - //Add values into array (if single values are passed) - if (!Array.isArray(senders)) - senders = [senders]; - if (!Array.isArray(privkeys)) - privkeys = [privkeys]; - if (!Array.isArray(receivers)) - receivers = [receivers]; - if (!Array.isArray(amounts)) - amounts = [amounts]; - - let invalids = []; - //validate tx-input parameters - if (senders.length != privkeys.length) - return reject("Array length for senders and privkeys should be equal"); - const redeemScripts = [], + try { + ({ + senders, + receivers, + amounts + } = validateTxParameters({ + senders, + privkeys, + receivers, + amounts, + fee, + change_addr + })); + } catch (e) { + return reject(e) + } + let total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8)), + redeemScripts = [], wif_keys = []; for (let i in senders) { - if (!verifyKey(senders[i], privkeys[i])) //verify private-key - invalids.push(senders[i]); - if (privkeys[i].length === 64) //convert Hex to WIF if needed - privkeys[i] = coinjs.privkey2wif(privkeys[i]); let rs = _redeemScript(senders[i], privkeys[i]); //get redeem-script (segwit/bech32) redeemScripts.push(rs); rs === false ? wif_keys.unshift(privkeys[i]) : wif_keys.push(privkeys[i]); //sorting private-keys (wif) } - if (invalids.length) - return reject("Invalid keys:" + invalids); - if (typeof fee !== "number" || fee <= 0) - return reject("Invalid fee:" + fee); - - //validate tx-output parameters - if (receivers.length != amounts.length) - return reject("Array length for receivers and amounts should be equal"); - let total_amount = 0; - for (let i in receivers) - if (!validateAddress(receivers[i])) - invalids.push(receivers[i]); - if (invalids.length) - return reject("Invalid receivers:" + invalids); - for (let i in amounts) { - if (typeof amounts[i] !== "number" || amounts[i] <= 0) - invalids.push(amounts[i]); - else - total_amount += amounts[i]; - } - if (invalids.length) - return reject("Invalid amounts:" + invalids); - if (change_addr && !validateAddress(change_addr)) - return reject("Invalid change_address:" + change_addr); + if (redeemScripts.includes(null)) //TODO: segwit + return reject("Unable to get redeem-script"); //create transaction - var tx = coinjs.transaction(); - total_amount = parseFloat(total_amount.toFixed(8)); + const tx = coinjs.transaction(); addUTXOs(tx, senders, redeemScripts, total_amount + fee).then(result => { if (result > 0) return reject("Insufficient Balance"); - for (let i in receivers) - tx.addoutput(receivers[i], amounts[i]); - let change = parseFloat(Math.abs(result).toFixed(8)); - if (change > 0) - tx.addoutput(change_addr || senders[0], change); - console.debug("amounts (total, fee, change):", total_amount, fee, change); + addOutputs(tx, receivers, amounts, Math.abs(result), change_addr || senders[0]) console.debug("Unsigned:", tx.serialize()); new Set(wif_keys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/ ))); //Sign the tx using private key WIF @@ -299,9 +324,80 @@ broadcast(tx.serialize()) .then(result => resolve(result)) .catch(error => reject(error)); - }).catch(error => reject(error)) + }); }) - }; + } + + btcOperator.createTx = function(senders, receivers, amounts, fee, change_addr = null) { + return new Promise((resolve, reject) => { + try { + ({ + senders, + receivers, + amounts + } = validateTxParameters({ + senders, + receivers, + amounts, + fee, + change_addr + })); + } catch (e) { + return reject(e) + } + let total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8)), + redeemScripts = senders.map(id => _redeemScript(id)); + if (redeemScripts.includes(null)) //TODO: segwit + return reject("Unable to get redeem-script"); + + //create transaction + const tx = coinjs.transaction(); + addUTXOs(tx, senders, redeemScripts, total_amount + fee).then(result => { + if (result > 0) + return reject("Insufficient Balance"); + addOutputs(tx, receivers, amounts, Math.abs(result), change_addr || senders[0]) + resolve(tx.serialize()); + }) + }) + } + + btcOperator.createMultiSigTx = function(sender, redeemScript, receivers, amounts, fee) { + return new Promise((resolve, reject) => { + + //validate tx parameters + if (validateAddress(sender) !== "multisig") + return reject("Invalid sender (multisig):" + sender); + else { + let script = coinjs.script(); + let decode = script.decodeRedeemScript(redeemScript); + if (!decode || decode.address !== sender) + return reject("Invalid redeem-script"); + } + try { + ({ + receivers, + amounts + } = validateTxParameters({ + receivers, + amounts, + fee, + change_addr + })); + } catch (e) { + return reject(e) + } + let total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8)) + + //create transaction + const tx = coinjs.transaction(); + addUTXOs(tx, senders, redeemScript, total_amount + fee).then(result => { + if (result > 0) + return reject("Insufficient Balance"); + addOutputs(tx, receivers, amounts, Math.abs(result), sender); + resolve(tx.serialize()); + }) + }) + } btcOperator.getTx = txid => new Promise((resolve, reject) => { fetch_api(`get_tx/BTC/${txid}`) From bc44405102096bc266ed2394e721647803d68c67 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 9 Aug 2022 03:16:51 +0530 Subject: [PATCH 211/289] btcOperator v1.0.7a - Adding auto fee calculation - Optimized the code - Fixed minor bugs --- btcOperator.js | 133 +++++++++++++++++++++++++++++++++++-------------- lib.js | 2 +- 2 files changed, 97 insertions(+), 38 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index b3992b6..60f1bd9 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //btcOperator v1.0.7 +(function(EXPORTS) { //btcOperator v1.0.7a /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -16,6 +16,21 @@ }) }; + const SIGN_SIZE = 73; + + function get_fee_rate() { + return new Promise((resolve, reject) => { + fetch('https://api.blockchain.info/mempool/fees').then(response => { + if (response.ok) + response.json() + .then(result => resolve(result.regular)) + .catch(error => reject(error)); + else + reject(response); + }).catch(error => reject(error)) + }) + } + const broadcast = btcOperator.broadcast = rawtx => new Promise((resolve, reject) => { $.ajax({ type: "POST", @@ -229,7 +244,7 @@ if (parameters.change_addr && !validateAddress(parameters.change_addr)) throw "Invalid change_address:" + parameters.change_addr; //fee and amounts - if (typeof parameters.fee !== "number" || parameters.fee <= 0) + if ((typeof parameters.fee !== "number" || parameters.fee <= 0) && parameters.fee !== null) //fee = null (auto calc) throw "Invalid fee:" + parameters.fee; if (!Array.isArray(parameters.amounts)) parameters.amounts = [parameters.amounts]; @@ -242,6 +257,32 @@ return parameters; } + const TMP_FEE = 0.00001; + + function createTransaction(senders, redeemScripts, receivers, amounts, fee, change_addr) { + let auto_fee = false, + total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8)); + if (fee === null) { + auto_fee = true; + fee = TMP_FEE; + } + const tx = coinjs.transaction(); + addUTXOs(tx, senders, redeemScripts, total_amount + fee).then(result => { + if (result > 0) + return reject("Insufficient Balance"); + let change = addOutputs(tx, receivers, amounts, Math.abs(result), change_addr); + if (!auto_fee) + return resolve(tx); + autoFeeCalc(tx).then(fee_calc => { + fee = Math.round((fee * 1) * 1e8); //satoshi convertion + if (!change) + tx.addoutput(change_addr, 0); + editFee(tx, fee, fee_calc); + resolve(tx); + }).catch(error => reject(error)) + }) + } + function addUTXOs(tx, senders, redeemScripts, required_amount, n = 0) { return new Promise((resolve, reject) => { required_amount = parseFloat(required_amount.toFixed(8)); @@ -277,8 +318,47 @@ function addOutputs(tx, receivers, amounts, change, change_addr) { for (let i in receivers) tx.addoutput(receivers[i], amounts[i]); - if (parseFloat(change.toFixed(8)) > 0) - tx.addoutput(change_addr || senders[0], change); + if (parseFloat(change.toFixed(8)) > 0) { + tx.addoutput(change_addr, change); + return true; + } else + return false; + + } + + function autoFeeCalc(tx) { + return new Promise((resolve, reject) => { + get_fee_rate().then(fee_rate => { + let tx_size = tx.size(); + for (var i = 0; i < this.ins.length; i++) + switch (tx.extractScriptKey(i).type) { + case 'scriptpubkey': + tx_size += SIGN_SIZE; + break; + case 'segwit': + case 'multisig': + tx_size += SIGN_SIZE * 0.25; + break; + default: + console.warn('Unknown script-type'); + tx_size += SIGN_SIZE; + } + resolve(tx_size * fee_rate); + }).catch(error => reject(error)) + }) + } + + function editFee(tx, current_fee, target_fee, index = -1) { + //values are in satoshi + index = parseInt(index >= 0 ? index : tx.out.length - index); + if (index < 0 || index >= tx.out.length) + throw "Invalid index"; + let edit_value = parseInt(current_fee - target_fee), //rip of any decimal places + current_value = tx.out[index].value; //could be BigInterger + if (edit_value < 0 && edit_value > current_value) + throw "Insufficient value at vout"; + tx.out[index].value = current_value instanceof BigInteger ? + current_value.add(new BigInteger('' + edit_value)) : parseInt(current_value + edit_value); } btcOperator.sendTx = function(senders, privkeys, receivers, amounts, fee, change_addr = null) { @@ -299,8 +379,7 @@ } catch (e) { return reject(e) } - let total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8)), - redeemScripts = [], + let redeemScripts = [], wif_keys = []; for (let i in senders) { let rs = _redeemScript(senders[i], privkeys[i]); //get redeem-script (segwit/bech32) @@ -309,26 +388,20 @@ } if (redeemScripts.includes(null)) //TODO: segwit return reject("Unable to get redeem-script"); - //create transaction - const tx = coinjs.transaction(); - addUTXOs(tx, senders, redeemScripts, total_amount + fee).then(result => { - if (result > 0) - return reject("Insufficient Balance"); - addOutputs(tx, receivers, amounts, Math.abs(result), change_addr || senders[0]) + createTransaction(senders, redeemScripts, receivers, amounts, fee, change_addr || senders[0]).then(tx => { console.debug("Unsigned:", tx.serialize()); new Set(wif_keys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/ ))); //Sign the tx using private key WIF - console.debug("Signed:", tx.serialize()); debugger; broadcast(tx.serialize()) .then(result => resolve(result)) .catch(error => reject(error)); - }); + }).catch(error => reject(error)); }) } - btcOperator.createTx = function(senders, receivers, amounts, fee, change_addr = null) { + btcOperator.createTx = function(senders, receivers, amounts, fee = null, change_addr = null) { return new Promise((resolve, reject) => { try { ({ @@ -345,25 +418,18 @@ } catch (e) { return reject(e) } - let total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8)), - redeemScripts = senders.map(id => _redeemScript(id)); + let redeemScripts = senders.map(id => _redeemScript(id)); if (redeemScripts.includes(null)) //TODO: segwit return reject("Unable to get redeem-script"); - //create transaction - const tx = coinjs.transaction(); - addUTXOs(tx, senders, redeemScripts, total_amount + fee).then(result => { - if (result > 0) - return reject("Insufficient Balance"); - addOutputs(tx, receivers, amounts, Math.abs(result), change_addr || senders[0]) - resolve(tx.serialize()); - }) + createTransaction(senders, redeemScripts, receivers, amounts, fee, change_addr || senders[0]) + .then(tx => resolve(tx.serialize())) + .catch(error => reject(error)) }) } btcOperator.createMultiSigTx = function(sender, redeemScript, receivers, amounts, fee) { return new Promise((resolve, reject) => { - //validate tx parameters if (validateAddress(sender) !== "multisig") return reject("Invalid sender (multisig):" + sender); @@ -380,22 +446,15 @@ } = validateTxParameters({ receivers, amounts, - fee, - change_addr + fee })); } catch (e) { return reject(e) } - let total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8)) - //create transaction - const tx = coinjs.transaction(); - addUTXOs(tx, senders, redeemScript, total_amount + fee).then(result => { - if (result > 0) - return reject("Insufficient Balance"); - addOutputs(tx, receivers, amounts, Math.abs(result), sender); - resolve(tx.serialize()); - }) + createTransaction([sender], [redeemScript], receivers, amounts, fee, sender) + .then(tx => resolve(tx.serialize())) + .catch(error => reject(error)) }) } diff --git a/lib.js b/lib.js index 26311f0..d2fd11d 100644 --- a/lib.js +++ b/lib.js @@ -6676,7 +6676,7 @@ throw "Invalid checksum"; } } catch (e) { - bech32rs = coinjs.bech32redeemscript(addr); + let bech32rs = coinjs.bech32redeemscript(addr); if (bech32rs) { return { 'type': 'bech32', From 91e6b823872963c6f82d31b39192adc7c6be9aef Mon Sep 17 00:00:00 2001 From: sairajzero Date: Wed, 10 Aug 2022 02:58:36 +0530 Subject: [PATCH 212/289] btcOperator v1.0.7b - Added: signTx - Added multiSigAddress --- btcOperator.js | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index 60f1bd9..170be20 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //btcOperator v1.0.7a +(function(EXPORTS) { //btcOperator v1.0.7b /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -94,6 +94,14 @@ return false; } + btcOperator.multiSigAddress = function(pubKeys, minRequired) { + if (!Array.isArray(pubKeys)) + throw "pubKeys must be an array of public keys"; + else if (pubKeys.length < minRequired) + throw "minimum required should be less than the number of pubKeys"; + return coinjs.pubkeys2MultisigAddress(pubKeys, minRequired); + } + //convert from one blockchain to another blockchain (target version) btcOperator.convert = {}; @@ -323,7 +331,6 @@ return true; } else return false; - } function autoFeeCalc(tx) { @@ -366,6 +373,7 @@ try { ({ senders, + privkeys, receivers, amounts } = validateTxParameters({ @@ -458,6 +466,25 @@ }) } + btcOperator.signTx = function(tx, privKeys) { + if (typeof tx === 'string' || Array.isArray(tx)) { + try { + tx = coinjs.transaction().deserialize(tx); + } catch { + throw "Invalid transaction hex"; + } + } else if (typeof tx !== 'object' || typeof tx.sign !== 'function') + throw "Invalid transaction object"; + + if (!Array.isArray(privkeys)) + privkeys = [privkeys]; + for (let i in privKeys) + if (privKeys[i].length === 64) + privkeys[i] = coinjs.privkey2wif(privKeys[i]); + new Set(privKeys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/ ))); //Sign the tx using private key WIF + return tx.serialize(); + } + btcOperator.getTx = txid => new Promise((resolve, reject) => { fetch_api(`get_tx/BTC/${txid}`) .then(result => resolve(result.data)) From 45878e6ebe3d8f8aecd81d02ad17fd977e7896ad Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 14 Aug 2022 18:38:29 +0530 Subject: [PATCH 213/289] Update floDapps.js - myFloID, myPubKey, myPrivKey will now return undefined when user not logged in --- floDapps.js | 50 ++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 42 insertions(+), 8 deletions(-) diff --git a/floDapps.js b/floDapps.js index 556e7fe..e2435a8 100644 --- a/floDapps.js +++ b/floDapps.js @@ -1,16 +1,26 @@ -(function(EXPORTS) { //floDapps v2.3.2a +(function(EXPORTS) { //floDapps v2.3.2b /* General functions for FLO Dapps*/ 'use strict'; const floDapps = EXPORTS; const DEFAULT = { - get root() { - return "floDapps" - }, + root: "floDapps", application: floGlobals.application, adminID: floGlobals.adminID }; + Object.defineProperties(floDapps, { + application: { + get: () => DEFAULT.application + }, + adminID: { + get: () => DEFAULT.adminID + }, + root: { + get: () => DEFAULT.root + } + }); + var user_priv_raw, aes_key, user_priv_wrap; //private variable inside capsule const raw_user = { get private() { @@ -73,16 +83,40 @@ Object.defineProperties(window, { myFloID: { - get: () => user.id + get: () => { + try { + return user.id; + } catch { + return; + } + } }, myUserID: { - get: () => user.id + get: () => { + try { + return user.id; + } catch { + return; + } + } }, myPubKey: { - get: () => user.public + get: () => { + try { + return user.public; + } catch { + return; + } + } }, myPrivKey: { - get: () => user.private + get: () => { + try { + return user.private; + } catch { + return; + } + } } }); From 36a4067d67e321ee6e7df95d9ac11c5f40201932 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 16 Aug 2022 00:37:38 +0530 Subject: [PATCH 214/289] bug fix --- floDapps.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/floDapps.js b/floDapps.js index e2435a8..1da58b8 100644 --- a/floDapps.js +++ b/floDapps.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floDapps v2.3.2b +(function(EXPORTS) { //floDapps v2.3.2c /* General functions for FLO Dapps*/ 'use strict'; const floDapps = EXPORTS; @@ -164,7 +164,7 @@ } //add other given objectStores initIndexedDB.appObs = initIndexedDB.appObs || {} - for (o in initIndexedDB.appObs) + for (let o in initIndexedDB.appObs) if (!(o in obs_a)) obs_a[o] = initIndexedDB.appObs[o] Promise.all([ @@ -456,7 +456,10 @@ Promise.all([p1, p2]) .then(r => resolve('App Startup finished successful')) .catch(e => reject('App Startup failed')) - }).catch(error => reject("App database initiation failed")) + }).catch(error => { + startUpLog(false, error); + reject("App database initiation failed") + }) }) } From 6e5cdbd820008de1b54a3926932d1af846665d91 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 16 Aug 2022 03:08:02 +0530 Subject: [PATCH 215/289] floCrypto v2.3.3b - Added floCrypto.tmpID: generates a random floID with no private key (use this only for one-time id) - Added toFloID(address): returns equivalent floID (btc-segwit address NOT supported) - Fixed bug: legacy addresses of length 33 not working in verifyPubKey and validateAddr --- floCloudAPI.js | 4 ++-- floCrypto.js | 61 +++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 58 insertions(+), 7 deletions(-) diff --git a/floCloudAPI.js b/floCloudAPI.js index 01560a1..402c0c5 100644 --- a/floCloudAPI.js +++ b/floCloudAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCloudAPI v2.4.2b +(function(EXPORTS) { //floCloudAPI v2.4.2c /* FLO Cloud operations to send/request application data*/ 'use strict'; const floCloudAPI = EXPORTS; @@ -384,7 +384,7 @@ if (!address) return; var bytes; - if (address.length == 34) { //legacy encoding + if (address.length == 33 || address.length == 34) { //legacy encoding let decode = bitjs.Base58.decode(address); bytes = decode.slice(0, decode.length - 4); let checksum = decode.slice(decode.length - 4), diff --git a/floCrypto.js b/floCrypto.js index b252169..01921d1 100644 --- a/floCrypto.js +++ b/floCrypto.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCrypto v2.3.3a +(function(EXPORTS) { //floCrypto v2.3.3b /* FLO Crypto Operators */ 'use strict'; const floCrypto = EXPORTS; @@ -148,8 +148,23 @@ } } - Object.defineProperty(floCrypto, 'newID', { - get: () => generateNewID() + Object.defineProperties(floCrypto, { + newID: { + get: () => generateNewID() + }, + tmpID: { + get: () => { + let bytes = Crypto.util.randomBytes(20); + bytes.unshift(bitjs.pub); + var hash = Crypto.SHA256(Crypto.SHA256(bytes, { + asBytes: true + }), { + asBytes: true + }); + var checksum = hash.slice(0, 4); + return bitjs.Base58.encode(bytes.concat(checksum)); + } + } }); //Returns public-key from private-key @@ -230,7 +245,7 @@ //Check if the given address (any blockchain) is valid or not floCrypto.validateAddr = function(address, std = true, bech = true) { - if (address.length == 34) { //legacy or segwit encoding + if (address.length == 33 || address.length == 34) { //legacy or segwit encoding if (std === false) return false; let decode = bitjs.Base58.decode(address); @@ -262,11 +277,12 @@ return false; } + //Check the public-key for the address (any blockchain) floCrypto.verifyPubKey = function(pubKeyHex, address) { let pub_hash = Crypto.util.bytesToHex(ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubKeyHex), { asBytes: true }))); - if (address.length == 34) { //legacy encoding + if (address.length == 33 || address.length == 34) { //legacy encoding let decode = bitjs.Base58.decode(address); var raw = decode.slice(0, decode.length - 4), checksum = decode.slice(decode.length - 4); @@ -291,6 +307,41 @@ return false; } + //Convert the given address (any blockchain) to equivalent floID + floCrypto.toFloID = function(address) { + if (!address) + return; + var bytes; + if (address.length == 33 || address.length == 34) { //legacy encoding + let decode = bitjs.Base58.decode(address); + bytes = decode.slice(0, decode.length - 4); + let checksum = decode.slice(decode.length - 4), + hash = Crypto.SHA256(Crypto.SHA256(bytes, { + asBytes: true + }), { + asBytes: true + }); + hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3] ? + bytes = undefined : bytes.shift(); + } else if (address.length == 42) { //bech encoding + let decode = coinjs.bech32_decode(address); + if (decode) { + bytes = decode.data; + bytes.shift(); + bytes = coinjs.bech32_convert(bytes, 5, 8, false); + } + } + if (!bytes) + return; + bytes.unshift(bitjs.pub); + let hash = Crypto.SHA256(Crypto.SHA256(bytes, { + asBytes: true + }), { + asBytes: true + }); + return bitjs.Base58.encode(bytes.concat(hash.slice(0, 4))); + } + //Split the str using shamir's Secret and Returns the shares floCrypto.createShamirsSecretShares = function(str, total_shares, threshold_limit) { try { From f0a48372225babfb87d466563e97d8d7da0b6ba5 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 16 Aug 2022 03:24:55 +0530 Subject: [PATCH 216/289] btcOperator v1.0.7c - Fixed: createTransaction not returning promise - Fixed: script not correctly added for multisig inputs - Fixed: signTx throwing syntax error - Added checkSigned(tx, bool?): check if the tx is signed or not. (bool is optional, default=true, if true returns a boolean value, else returns a detailed array of input's length) - Fixed minor bugs in lib.js --- btcOperator.js | 92 ++++++++++++++++++++++++++++++++++---------------- lib.js | 8 ++--- 2 files changed, 67 insertions(+), 33 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index 170be20..591cd0a 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //btcOperator v1.0.7b +(function(EXPORTS) { //btcOperator v1.0.7c /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -268,26 +268,28 @@ const TMP_FEE = 0.00001; function createTransaction(senders, redeemScripts, receivers, amounts, fee, change_addr) { - let auto_fee = false, - total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8)); - if (fee === null) { - auto_fee = true; - fee = TMP_FEE; - } - const tx = coinjs.transaction(); - addUTXOs(tx, senders, redeemScripts, total_amount + fee).then(result => { - if (result > 0) - return reject("Insufficient Balance"); - let change = addOutputs(tx, receivers, amounts, Math.abs(result), change_addr); - if (!auto_fee) - return resolve(tx); - autoFeeCalc(tx).then(fee_calc => { - fee = Math.round((fee * 1) * 1e8); //satoshi convertion - if (!change) - tx.addoutput(change_addr, 0); - editFee(tx, fee, fee_calc); - resolve(tx); - }).catch(error => reject(error)) + return new Promise((resolve, reject) => { + let auto_fee = false, + total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8)); + if (fee === null) { + auto_fee = true; + fee = TMP_FEE; + } + const tx = coinjs.transaction(); + addUTXOs(tx, senders, redeemScripts, total_amount + fee).then(result => { + if (result > 0) + return reject("Insufficient Balance"); + let change = addOutputs(tx, receivers, amounts, Math.abs(result), change_addr); + if (!auto_fee) + return resolve(tx); + autoFeeCalc(tx).then(fee_calc => { + fee = Math.round((fee * 1) * 1e8); //satoshi convertion + if (!change) + tx.addoutput(change_addr, 0); + editFee(tx, fee, fee_calc); + resolve(tx); + }).catch(error => reject(error)) + }) }) } @@ -306,14 +308,17 @@ continue; required_amount -= parseFloat(utxos[i].value); var script; - if (rs) { //redeemScript for segwit/bech32 + if (!rs || !rs.length) //legacy script + script = utxos[i].script_hex; + else if (((rs.match(/^00/) && rs.length == 44)) || (rs.length == 40 && rs.match(/^[a-f0-9]+$/gi))) { + //redeemScript for segwit/bech32 let s = coinjs.script(); s.writeBytes(Crypto.util.hexToBytes(rs)); s.writeOp(0); s.writeBytes(coinjs.numToBytes((utxos[i].value * 100000000).toFixed(0), 8)); script = Crypto.util.bytesToHex(s.buffer); - } else //legacy script - script = utxos[i].script_hex; + } else //redeemScript for multisig + script = rs; tx.addinput(utxos[i].txid, utxos[i].output_no, script, 0xfffffffd /*sequence*/ ); //0xfffffffd for Replace-by-fee } addUTXOs(tx, senders, redeemScripts, required_amount, n + 1) @@ -466,7 +471,7 @@ }) } - btcOperator.signTx = function(tx, privKeys) { + function deserializeTx(tx) { if (typeof tx === 'string' || Array.isArray(tx)) { try { tx = coinjs.transaction().deserialize(tx); @@ -475,16 +480,45 @@ } } else if (typeof tx !== 'object' || typeof tx.sign !== 'function') throw "Invalid transaction object"; + return tx; + } + btcOperator.signTx = function(tx, privkeys, sighashtype = 1) { + tx = deserializeTx(tx); if (!Array.isArray(privkeys)) privkeys = [privkeys]; - for (let i in privKeys) - if (privKeys[i].length === 64) - privkeys[i] = coinjs.privkey2wif(privKeys[i]); - new Set(privKeys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/ ))); //Sign the tx using private key WIF + for (let i in privkeys) + if (privkeys[i].length === 64) + privkeys[i] = coinjs.privkey2wif(privkeys[i]); + new Set(privkeys).forEach(key => tx.sign(key, sighashtype)); //Sign the tx using private key WIF return tx.serialize(); } + btcOperator.checkSigned = function(tx, bool = true) { + tx = deserializeTx(tx); + let n = []; + for (let i in tx.ins) { + var s = tx.extractScriptKey(i); + if (s['type'] !== 'multisig') + n.push(s.signed == 'true' || (tx.witness[i] && tx.witness[i].length == 2)) + else { + var rs = coinjs.script().decodeRedeemScript(s.script); + let x = { + s: s['signatures'], + r: rs['signaturesRequired'], + t: rs['pubkeys'].length + }; + if (x.r > x.t) + throw "signaturesRequired is more than publicKeys"; + else if (x.s < x.r) + n.push(x); + else + n.push(true); + } + } + return bool ? !(n.filter(x => x !== true).length) : n; + } + btcOperator.getTx = txid => new Promise((resolve, reject) => { fetch_api(`get_tx/BTC/${txid}`) .then(result => resolve(result.data)) diff --git a/lib.js b/lib.js index d2fd11d..1ae4ca2 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function(GLOBAL) { //lib v1.3.0b +(function(GLOBAL) { //lib v1.3.0c 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -7814,7 +7814,7 @@ } else if (this.ins[index].script.chunks[0] == 0 && this.ins[index].script.chunks[this.ins[index].script.chunks.length - 1][this.ins[index].script.chunks[this.ins[index].script.chunks.length - 1].length - 1] == 174) { // OP_CHECKMULTISIG // multisig script, with signature(s) included var sigcount = 0; - for (i = 1; i < this.ins[index].script.chunks.length - 1; i++) { + for (let i = 1; i < this.ins[index].script.chunks.length - 1; i++) { if (this.ins[index].script.chunks[i] != 0) { sigcount++; } @@ -8057,8 +8057,8 @@ s.writeOp(0); - for (x in pubkeyList) { - for (y in sigsList) { + for (let x in pubkeyList) { + for (let y in sigsList) { this.ins[index].script.buffer = redeemScript; sighash = Crypto.util.hexToBytes(this.transactionHash(index, sigsList[y].slice(-1)[0] * 1)); if (coinjs.verifySignature(sighash, sigsList[y], pubkeyList[x])) { From dc19a4e56570d6fc3e372f61b63382757a2b5690 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 16 Aug 2022 17:30:46 +0530 Subject: [PATCH 217/289] Bug fixes: floBlockchainAPI and lib.js --- floBlockchainAPI.js | 14 +++++++------- lib.js | 6 +++--- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 8cf3a79..d250f86 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floBlockchainAPI v2.3.3a +(function(EXPORTS) { //floBlockchainAPI v2.3.3b /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -6,7 +6,7 @@ const DEFAULT = { blockchain: floGlobals.blockchain, apiURL: { - FLO: ['https://livenet.flocha.in/', 'https://flosight.duckdns.org/'], + FLO: ['https://flosight.duckdns.org/'], FLO_TEST: ['https://testnet-flosight.duckdns.org', 'https://testnet.flocha.in/'] }, sendAmt: 0.001, @@ -49,7 +49,7 @@ const allServerList = new Set(floGlobals.apiURL && floGlobals.apiURL[DEFAULT.blockchain] ? floGlobals.apiURL[DEFAULT.blockchain] : DEFAULT.apiURL[DEFAULT.blockchain]); var serverList = Array.from(allServerList); - var curPos = floCrypto.randInt(0, serverList - 1); + var curPos = floCrypto.randInt(0, serverList.length - 1); function fetch_retry(apicall, rm_flosight) { return new Promise((resolve, reject) => { @@ -371,18 +371,18 @@ }) //Calculate totalSentAmount and check if totalBalance is sufficient let totalSendAmt = totalFee; - for (floID in receivers) + for (let floID in receivers) totalSendAmt += receivers[floID]; if (totalBalance < totalSendAmt) return reject("Insufficient total Balance"); //Get the UTXOs of the senders let promises = []; - for (floID in senders) + for (let floID in senders) promises.push(promisedAPI(`api/addr/${floID}/utxo`)); Promise.all(promises).then(results => { let wifSeq = []; var trx = bitjs.transaction(); - for (floID in senders) { + for (let floID in senders) { let utxos = results.shift(); let sendAmt; if (preserveRatio) { @@ -406,7 +406,7 @@ if (change > 0) trx.addoutput(floID, change); } - for (floID in receivers) + for (let floID in receivers) trx.addoutput(floID, receivers[floID]); trx.addflodata(floData.replace(/\n/g, ' ')); for (let i = 0; i < wifSeq.length; i++) diff --git a/lib.js b/lib.js index 1ae4ca2..6fc8af8 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function(GLOBAL) { //lib v1.3.0c +(function(GLOBAL) { //lib v1.3.0d 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -4782,8 +4782,8 @@ } else if (floDataCount < 253) { floDataCountString = floDataCount.toString(16); } else if (floDataCount <= 1040) { - floDataCountAdjusted = (floDataCount - 253) + parseInt("0xfd00fd"); - floDataCountStringAdjusted = floDataCountAdjusted.toString(16); + let floDataCountAdjusted = (floDataCount - 253) + parseInt("0xfd00fd"); + let floDataCountStringAdjusted = floDataCountAdjusted.toString(16); floDataCountString = floDataCountStringAdjusted.substr(0, 2) + floDataCountStringAdjusted.substr(4, 2) + floDataCountStringAdjusted.substr(2, 2); } else { floDataCountString = "Character Limit Exceeded"; From 67386fd69f45610c1c02912828d24ce9d654282c Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 16 Aug 2022 20:39:49 +0530 Subject: [PATCH 218/289] Update btcOperator.js - Added checkIfSameTx(tx1, tx2): checks if the transactions is of the same --- btcOperator.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/btcOperator.js b/btcOperator.js index 591cd0a..aff13ee 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //btcOperator v1.0.7c +(function(EXPORTS) { //btcOperator v1.0.8 /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -519,6 +519,20 @@ return bool ? !(n.filter(x => x !== true).length) : n; } + btcOperator.checkIfSameTx = function(tx1, tx2) { + tx1 = deserializeTx(tx1); + tx2 = deserializeTx(tx2); + if (tx1.ins.length !== tx2.ins.length || tx1.outs.length !== tx2.outs.length) + return false; + for (let i = 0; i < tx1.ins.length; i++) + if (tx1.ins[i].outpoint.hash !== tx2.ins[i].outpoint.hash || tx1.ins[i].outpoint.index !== tx2.ins[i].outpoint.index) + return false; + for (let i = 0; i < tx2.ins.length; i++) + if (tx1.outs[i].value !== tx2.outs[i].value || Crypto.util.bytesToHex(tx1.outs[i].script.buffer) !== Crypto.util.bytesToHex(tx2.outs[i].script.buffer)) + return false; + return true; + } + btcOperator.getTx = txid => new Promise((resolve, reject) => { fetch_api(`get_tx/BTC/${txid}`) .then(result => resolve(result.data)) From 7b5a5e6bfe369c4a58dfd0abcf64951747da9051 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 21 Aug 2022 21:14:29 +0530 Subject: [PATCH 219/289] Bug fixes and improvements floCrypto v2.3.3b floCloudAPI v2.4.2d floDapps v2.3.2d --- floCloudAPI.js | 5 +- floCrypto.js | 121 ++++++++++++++++++++++++------------------------- floDapps.js | 34 ++++++++++++-- 3 files changed, 90 insertions(+), 70 deletions(-) diff --git a/floCloudAPI.js b/floCloudAPI.js index 402c0c5..1fafb51 100644 --- a/floCloudAPI.js +++ b/floCloudAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCloudAPI v2.4.2c +(function(EXPORTS) { //floCloudAPI v2.4.2d /* FLO Cloud operations to send/request application data*/ 'use strict'; const floCloudAPI = EXPORTS; @@ -317,6 +317,7 @@ data => { data = objectifier(data); let filtered = {}, + proxy = proxyID(request.receiverID), r = request; for (let v in data) { let d = data[v]; @@ -325,7 +326,7 @@ (r.atVectorClock || !r.upperVectorClock || r.upperVectorClock >= v) && (!r.afterTime || r.afterTime < d.log_time) && r.application == d.application && - r.receiverID == d.receiverID && + (proxy == d.receiverID || proxy == d.proxyID) && (!r.comment || r.comment == d.comment) && (!r.type || r.type == d.type) && (!r.senderID || r.senderID.includes(d.senderID))) diff --git a/floCrypto.js b/floCrypto.js index 01921d1..025f698 100644 --- a/floCrypto.js +++ b/floCrypto.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCrypto v2.3.3b +(function(EXPORTS) { //floCrypto v2.3.3c /* FLO Crypto Operators */ 'use strict'; const floCrypto = EXPORTS; @@ -245,101 +245,96 @@ //Check if the given address (any blockchain) is valid or not floCrypto.validateAddr = function(address, std = true, bech = true) { - if (address.length == 33 || address.length == 34) { //legacy or segwit encoding - if (std === false) + let raw = decodeAddress(address); + if (!raw) + return false; + if (typeof raw.version !== 'undefined') { //legacy or segwit + if (std == false) return false; - let decode = bitjs.Base58.decode(address); - var raw = decode.slice(0, decode.length - 4), - checksum = decode.slice(decode.length - 4); - var hash = Crypto.SHA256(Crypto.SHA256(raw, { - asBytes: true - }), { - asBytes: true - }); - if (hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3]) - return false; - else if (std === true || (!Array.isArray(std) && std === raw[0]) || (Array.isArray(std) && std.includes(raw[0]))) + else if (std === true || (!Array.isArray(std) && std === raw.version) || (Array.isArray(std) && std.includes(raw.version))) return true; else return false; - } else if (address.length == 42 || address.length == 62) { //bech encoding + } else if (typeof raw.bech_version !== 'undefined') { //bech32 if (bech === false) return false; - let decode = coinjs.bech32_decode(address); - if (!decode) - return false; - var raw = decode.data; - if (bech === true || (!Array.isArray(bech) && bech === raw[0]) || (Array.isArray(bech) && bech.includes(raw[0]))) + else if (bech === true || (!Array.isArray(bech) && bech === raw.bech_version) || (Array.isArray(bech) && bech.includes(raw.bech_version))) return true; else return false; - } else //unknown length + } else //unknown return false; } //Check the public-key for the address (any blockchain) floCrypto.verifyPubKey = function(pubKeyHex, address) { - let pub_hash = Crypto.util.bytesToHex(ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubKeyHex), { - asBytes: true - }))); - if (address.length == 33 || address.length == 34) { //legacy encoding - let decode = bitjs.Base58.decode(address); - var raw = decode.slice(0, decode.length - 4), - checksum = decode.slice(decode.length - 4); - var hash = Crypto.SHA256(Crypto.SHA256(raw, { + let raw = decodeAddress(address), + pub_hash = Crypto.util.bytesToHex(ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubKeyHex), { asBytes: true - }), { - asBytes: true - }); - if (hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3]) - return false; - raw.shift(); - return pub_hash === Crypto.util.bytesToHex(raw); - } else if (address.length == 42 || address.length == 62) { //bech encoding - let decode = coinjs.bech32_decode(address); - if (!decode) - return false; - var raw = decode.data; - raw.shift(); - raw = coinjs.bech32_convert(raw, 5, 8, false); - return pub_hash === Crypto.util.bytesToHex(raw); - } else //unknown length - return false; + }))); + return raw ? pub_hash === raw.hex : false; } //Convert the given address (any blockchain) to equivalent floID floCrypto.toFloID = function(address) { if (!address) return; - var bytes; - if (address.length == 33 || address.length == 34) { //legacy encoding + let raw = decodeAddress(address); + if (!raw) + return; + raw.bytes.unshift(bitjs.pub); + let hash = Crypto.SHA256(Crypto.SHA256(raw.bytes, { + asBytes: true + }), { + asBytes: true + }); + return bitjs.Base58.encode(raw.bytes.concat(hash.slice(0, 4))); + } + + //Checks if the given addresses (any blockchain) are same (w.r.t keys) + floCrypto.isSameAddr = function(addr1, addr2) { + if (!addr1 || !addr2) + return; + let raw1 = decodeAddress(addr1), + raw2 = decodeAddress(addr2); + if (!raw1 || !raw2) + return false; + else + return raw1.hex === raw2.hex; + } + + const decodeAddress = floCrypto.decodeAddr = function(address) { + if (!address) + return; + else if (address.length == 33 || address.length == 34) { //legacy encoding let decode = bitjs.Base58.decode(address); - bytes = decode.slice(0, decode.length - 4); + let bytes = decode.slice(0, decode.length - 4); let checksum = decode.slice(decode.length - 4), hash = Crypto.SHA256(Crypto.SHA256(bytes, { asBytes: true }), { asBytes: true }); - hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3] ? - bytes = undefined : bytes.shift(); + return (hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3]) ? null : { + version: bytes.shift(), + hex: Crypto.util.bytesToHex(bytes), + bytes + } } else if (address.length == 42) { //bech encoding let decode = coinjs.bech32_decode(address); if (decode) { - bytes = decode.data; - bytes.shift(); + let bytes = decode.data; + let bech_version = bytes.shift(); bytes = coinjs.bech32_convert(bytes, 5, 8, false); - } + return { + bech_version, + hrp: decode.hrp, + hex: Crypto.util.bytesToHex(bytes), + bytes + } + } else + return null; } - if (!bytes) - return; - bytes.unshift(bitjs.pub); - let hash = Crypto.SHA256(Crypto.SHA256(bytes, { - asBytes: true - }), { - asBytes: true - }); - return bitjs.Base58.encode(bytes.concat(hash.slice(0, 4))); } //Split the str using shamir's Secret and Returns the shares diff --git a/floDapps.js b/floDapps.js index 1da58b8..38ee0b4 100644 --- a/floDapps.js +++ b/floDapps.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floDapps v2.3.2c +(function(EXPORTS) { //floDapps v2.3.2d /* General functions for FLO Dapps*/ 'use strict'; const floDapps = EXPORTS; @@ -63,7 +63,7 @@ return Crypto.AES.decrypt(data, raw_user.private); }, get db_name() { - return "floDapps#" + user.id; + return "floDapps#" + floCrypto.toFloID(user.id); }, lock() { user_private = user_priv_wrap; @@ -72,6 +72,30 @@ if (await user.private === raw_user.private) user_private = user_priv_raw; }, + get_contact(id) { + if (!user.contacts) + throw "Contacts not available"; + else if (user.contacts[id]) + return user.contacts[id]; + else { + let id_raw = floCrypto.decodeAddr(id).hex; + for (let i in user.contacts) + if (floCrypto.decodeAddr(i).hex == id_raw) + return user.contacts[i]; + } + }, + get_pubKey(id) { + if (!user.pubKeys) + throw "Contacts not available"; + else if (user.pubKeys[id]) + return user.pubKeys[id]; + else { + let id_raw = floCrypto.decodeAddr(id).hex; + for (let i in user.pubKeys) + if (floCrypto.decodeAddr(i).hex == id_raw) + return user.pubKeys[i]; + } + }, clear() { user_id = user_public = user_private = undefined; user_priv_raw = aes_key = undefined; @@ -475,7 +499,7 @@ floDapps.storeContact = function(floID, name) { return new Promise((resolve, reject) => { - if (!floCrypto.validateFloID(floID)) + if (!floCrypto.validateAddr(floID)) return reject("Invalid floID!") compactIDB.writeData("contacts", name, floID, user.db_name).then(result => { user.contacts[floID] = name; @@ -488,9 +512,9 @@ return new Promise((resolve, reject) => { if (floID in user.pubKeys) return resolve("pubKey already stored") - if (!floCrypto.validateFloID(floID)) + if (!floCrypto.validateAddr(floID)) return reject("Invalid floID!") - if (floCrypto.getFloID(pubKey) != floID) + if (!floCrypto.verifyPubKey(pubKey, floID)) return reject("Incorrect pubKey") compactIDB.writeData("pubKeys", pubKey, floID, user.db_name).then(result => { user.pubKeys[floID] = pubKey; From 77ff76d787c0458795b9fe38c79a27c46a2b10bd Mon Sep 17 00:00:00 2001 From: sairajzero Date: Mon, 22 Aug 2022 22:06:14 +0530 Subject: [PATCH 220/289] Replacing Math.random with securedMathRandom --- floCrypto.js | 6 ++-- lib.js | 89 +++++++++++++++++++++++++++++----------------------- 2 files changed, 53 insertions(+), 42 deletions(-) diff --git a/floCrypto.js b/floCrypto.js index 025f698..6671ffa 100644 --- a/floCrypto.js +++ b/floCrypto.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCrypto v2.3.3c +(function(EXPORTS) { //floCrypto v2.3.3d /* FLO Crypto Operators */ 'use strict'; const floCrypto = EXPORTS; @@ -81,7 +81,7 @@ floCrypto.randInt = function(min, max) { min = Math.ceil(min); max = Math.floor(max); - return Math.floor(Math.random() * (max - min + 1)) + min; + return Math.floor(securedMathRandom() * (max - min + 1)) + min; } //generate a random String within length (options : alphaNumeric chars only) @@ -90,7 +90,7 @@ var characters = alphaNumeric ? 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+-./*?@#&$<>=[]{}():'; for (var i = 0; i < length; i++) - result += characters.charAt(Math.floor(Math.random() * characters.length)); + result += characters.charAt(Math.floor(securedMathRandom() * characters.length)); return result; } diff --git a/lib.js b/lib.js index 6fc8af8..b435194 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function(GLOBAL) { //lib v1.3.0d +(function(GLOBAL) { //lib v1.3.1 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -6,6 +6,37 @@ */ GLOBAL.cryptocoin = (typeof floGlobals === 'undefined' ? null : floGlobals.blockchain) || 'FLO'; + const getRandomBytes = (function() { + if (typeof require === 'function') { + const crypto = require('crypto'); + return function(buf) { + var bytes = crypto.randomBytes(buf.length); + buf.set(bytes); + return buf; + } + } else if (GLOBAL.crypto && GLOBAL.crypto.getRandomValues) { + return function(buf) { + return GLOBAL.crypto.getRandomValues(buf); + } + } else + throw Error('Unable to define getRandomBytes'); + })(); + + + GLOBAL.securedMathRandom = (function() { + if (typeof require === 'function') { + const crypto = require('crypto'); + return function() { + return crypto.randomBytes(4).readUInt32LE() / 0xffffffff; + } + } else if (GLOBAL.crypto && GLOBAL.crypto.getRandomValues) { + return function() { + return (GLOBAL.crypto.getRandomValues(new Uint32Array(1))[0] / 0xffffffff); + } + } else + throw Error('Unable to define securedMathRandom'); + })(); + //Crypto.js (function() { // Global Crypto object @@ -52,7 +83,7 @@ // Generate an array of any length of random bytes randomBytes: function(n) { for (var bytes = []; n > 0; n--) - bytes.push(Math.floor(Math.random() * 256)); + bytes.push(Math.floor(securedMathRandom() * 256)); return bytes; }, @@ -405,16 +436,6 @@ //SecureRandom.js (function() { - const getRandomValues = function(buf) { - if (typeof require === 'function') { - var bytes = require('crypto').randomBytes(buf.length); - buf.set(bytes) - return buf; - } else if (GLOBAL.crypto && GLOBAL.crypto.getRandomValues) - return GLOBAL.crypto.getRandomValues(buf); - else - return null; - } /*! * Random number generator with ArcFour PRNG @@ -446,10 +467,10 @@ // ba: byte array sr.prototype.nextBytes = function(ba) { var i; - if (getRandomValues && GLOBAL.Uint8Array) { + if (getRandomBytes && GLOBAL.Uint8Array) { try { var rvBytes = new Uint8Array(ba.length); - getRandomValues(rvBytes); + getRandomBytes(rvBytes); for (i = 0; i < ba.length; ++i) ba[i] = sr.getByte() ^ rvBytes[i]; return; @@ -549,23 +570,23 @@ sr.pool = new Array(); sr.pptr = 0; var t; - if (getRandomValues && GLOBAL.Uint8Array) { + if (getRandomBytes && GLOBAL.Uint8Array) { try { // Use webcrypto if available var ua = new Uint8Array(sr.poolSize); - getRandomValues(ua); + getRandomBytes(ua); for (t = 0; t < sr.poolSize; ++t) sr.pool[sr.pptr++] = ua[t]; } catch (e) { alert(e); } } - while (sr.pptr < sr.poolSize) { // extract some randomness from Math.random() - t = Math.floor(65536 * Math.random()); + while (sr.pptr < sr.poolSize) { // extract some randomness from securedMathRandom() + t = Math.floor(65536 * securedMathRandom()); sr.pool[sr.pptr++] = t >>> 8; sr.pool[sr.pptr++] = t & 255; } - sr.pptr = Math.floor(sr.poolSize * Math.random()); + sr.pptr = Math.floor(sr.poolSize * securedMathRandom()); sr.seedTime(); // entropy var entropyStr = ""; @@ -1654,7 +1675,7 @@ var a = nbi(); for (var i = 0; i < t; ++i) { //Pick bases at random, instead of starting at 2 - a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); + a.fromInt(lowprimes[Math.floor(securedMathRandom() * lowprimes.length)]); var y = a.modPow(r, this); if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; @@ -2612,7 +2633,7 @@ pad: function(cipher, message) { var reqd = _requiredPadding(cipher, message); for (var i = 1; i < reqd; i++) { - message.push(Math.floor(Math.random() * 256)); + message.push(Math.floor(securedMathRandom() * 256)); } message.push(reqd); }, @@ -6690,7 +6711,7 @@ /* retreive the balance from a given address */ coinjs.addressBalance = function(address, callback) { - coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=bal&address=' + address + '&r=' + Math.random(), callback, "GET"); + coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=bal&address=' + address + '&r=' + securedMathRandom(), callback, "GET"); } /* decompress an compressed public key */ @@ -7469,12 +7490,12 @@ /* list unspent transactions */ r.listUnspent = function(address, callback) { - coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=unspent&address=' + address + '&r=' + Math.random(), callback, "GET"); + coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=unspent&address=' + address + '&r=' + securedMathRandom(), callback, "GET"); } /* list transaction data */ r.getTransaction = function(txid, callback) { - coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=bitcoin&request=gettransaction&txid=' + txid + '&r=' + Math.random(), callback, "GET"); + coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=bitcoin&request=gettransaction&txid=' + txid + '&r=' + securedMathRandom(), callback, "GET"); } /* add unspent to transaction */ @@ -8566,7 +8587,7 @@ var l = length || 25; var chars = "!$%^&*()_+{}:@~?><|\./;'#][=-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; for (let x = 0; x < l; x++) { - r += chars.charAt(Math.floor(Math.random() * 62)); + r += chars.charAt(Math.floor(securedMathRandom() * 62)); } return r; } @@ -8595,7 +8616,7 @@ ], // warning for insecure PRNG - warning: 'WARNING:\nA secure random number generator was not found.\nUsing Math.random(), which is NOT cryptographically strong!' + warning: 'WARNING:\nA secure random number generator was not found.\nUsing securedMathRandom(), which is NOT cryptographically strong!' }; // Protected settings object @@ -8715,7 +8736,7 @@ str = null; while (str === null) { for (var i = 0; i < elems; i++) { - arr[i] = Math.floor(Math.random() * max + 1); + arr[i] = Math.floor(securedMathRandom() * max + 1); } str = construct(bits, arr, 10, bitsPerNum); } @@ -8724,7 +8745,7 @@ }; // Warn about using insecure rng. - // Called when Math.random() is being used. + // Called when securedMathRandom() is being used. function warn() { GLOBAL['console']['warn'](defaults.warning); if (typeof GLOBAL['alert'] === 'function' && config.alert) { @@ -9148,22 +9169,12 @@ //kbucket.js (function() { - const getRandomValues = function(buf) { - if (typeof require === 'function') { - var bytes = require('crypto').randomBytes(buf.length); - buf.set(bytes) - return buf; - } else if (GLOBAL.crypto && GLOBAL.crypto.getRandomValues) - return GLOBAL.crypto.getRandomValues(buf); - else - return null; - } // Kademlia DHT K-bucket implementation as a binary tree. // by 'Tristan Slominski' under 'MIT License' GLOBAL.BuildKBucket = function KBucket(options = {}) { if (!(this instanceof KBucket)) return new KBucket(options); - this.localNodeId = options.localNodeId || getRandomValues(new Uint8Array(20)) + this.localNodeId = options.localNodeId || getRandomBytes(new Uint8Array(20)) this.numberOfNodesPerKBucket = options.numberOfNodesPerKBucket || 20 this.numberOfNodesToPing = options.numberOfNodesToPing || 3 this.distance = options.distance || this.distance From 04aad2860052220995192e59e337d4b29baabc27 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 25 Aug 2022 03:04:56 +0530 Subject: [PATCH 221/289] Improved auto-fee calc - createTx and createMultiSigTx will now resolve an object with tx_hex and other values (amount, size, etc) --- btcOperator.js | 185 +++++++++++++++++++++++++++++++++++-------------- 1 file changed, 134 insertions(+), 51 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index aff13ee..9593541 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //btcOperator v1.0.8 +(function(EXPORTS) { //btcOperator v1.0.9 /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -16,14 +16,14 @@ }) }; - const SIGN_SIZE = 73; + const SATOSHI_IN_BTC = 1e8; function get_fee_rate() { return new Promise((resolve, reject) => { fetch('https://api.blockchain.info/mempool/fees').then(response => { if (response.ok) response.json() - .then(result => resolve(result.regular)) + .then(result => resolve(parseFloat((result.regular / SATOSHI_IN_BTC).toFixed(8)))) .catch(error => reject(error)); else reject(response); @@ -204,6 +204,17 @@ .catch(error => reject(error)) }); + const BASE_TX_SIZE = 12, + BASE_INPUT_SIZE = 41, + LEGACY_INPUT_SIZE = 107, + BECH32_INPUT_SIZE = 27, + SEGWIT_INPUT_SIZE = 59, + MULTISIG_INPUT_SIZE_ES = 351, + BASE_OUTPUT_SIZE = 9, + LEGACY_OUTPUT_SIZE = 25, + BECH32_OUTPUT_SIZE = 23, + SEGWIT_OUTPUT_SIZE = 23; + function _redeemScript(addr, key) { let decode = coinjs.addressDecode(addr); switch (decode.type) { @@ -218,6 +229,39 @@ } } + function _sizePerInput(addr, rs) { + switch (coinjs.addressDecode(addr).type) { + case "standard": + return BASE_INPUT_SIZE + LEGACY_INPUT_SIZE; + case "bech32": + return BASE_INPUT_SIZE + BECH32_INPUT_SIZE; + case "multisig": + switch (coinjs.script().decodeRedeemScript(rs).type) { + case "segwit__": + return BASE_INPUT_SIZE + SEGWIT_INPUT_SIZE; + case "multisig__": + return BASE_INPUT_SIZE + MULTISIG_INPUT_SIZE_ES; + default: + return null; + }; + default: + return null; + } + } + + function _sizePerOutput(addr) { + switch (coinjs.addressDecode(addr).type) { + case "standard": + return BASE_OUTPUT_SIZE + LEGACY_OUTPUT_SIZE; + case "bech32": + return BASE_OUTPUT_SIZE + BECH32_OUTPUT_SIZE; + case "multisig": + return BASE_OUTPUT_SIZE + SEGWIT_OUTPUT_SIZE; + default: + return null; + } + } + function validateTxParameters(parameters) { let invalids = []; //sender-ids @@ -265,48 +309,71 @@ return parameters; } - const TMP_FEE = 0.00001; - function createTransaction(senders, redeemScripts, receivers, amounts, fee, change_addr) { return new Promise((resolve, reject) => { - let auto_fee = false, - total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8)); - if (fee === null) { - auto_fee = true; - fee = TMP_FEE; - } + let total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8)); const tx = coinjs.transaction(); - addUTXOs(tx, senders, redeemScripts, total_amount + fee).then(result => { - if (result > 0) - return reject("Insufficient Balance"); - let change = addOutputs(tx, receivers, amounts, Math.abs(result), change_addr); - if (!auto_fee) - return resolve(tx); - autoFeeCalc(tx).then(fee_calc => { - fee = Math.round((fee * 1) * 1e8); //satoshi convertion - if (!change) - tx.addoutput(change_addr, 0); - editFee(tx, fee, fee_calc); - resolve(tx); - }).catch(error => reject(error)) - }) + let output_size = addOutputs(tx, receivers, amounts, change_addr); + addInputs(tx, senders, redeemScripts, total_amount, fee, output_size).then(result => { + if (result.change_amount > 0) + tx.outs[tx.outs.length - 1].value = parseInt(result.change_amount * SATOSHI_IN_BTC); //values are in satoshi + else + tx.outs.pop(); //remove the change output if no change_amount + result.output_size = output_size; + result.output_amount = total_amount; + result.total_size = BASE_TX_SIZE + output_size + result.input_size; + result.transaction = tx; + resolve(result); + }).catch(error => reject(error)) }) } - function addUTXOs(tx, senders, redeemScripts, required_amount, n = 0) { + function addInputs(tx, senders, redeemScripts, total_amount, fee, output_size) { + return new Promise((resolve, reject) => { + if (fee !== null) { + addUTXOs(tx, senders, redeemScripts, total_amount + fee, false).then(result => { + result.fee = fee; + resolve(result); + }).catch(error => reject(error)) + } else { + get_fee_rate().then(fee_rate => { + let net_fee = BASE_TX_SIZE * fee_rate; + net_fee += (output_size * fee_rate); + addUTXOs(tx, senders, redeemScripts, total_amount + net_fee, fee_rate).then(result => { + result.fee_amount = parseFloat((net_fee + (result.input_size * fee_rate)).toFixed(8)); + result.fee_rate = fee_rate; + resolve(result); + }).catch(error => reject(error)) + }).catch(error => reject(error)) + } + }) + } + + function addUTXOs(tx, senders, redeemScripts, required_amount, fee_rate, rec_args = {}) { return new Promise((resolve, reject) => { required_amount = parseFloat(required_amount.toFixed(8)); - if (required_amount <= 0 || n >= senders.length) - return resolve(required_amount); - let addr = senders[n], - rs = redeemScripts[n]; + if (typeof rec_args.n === "undefined") { + rec_args.n = 0; + rec_args.input_size = 0; + rec_args.input_amount = 0; + } + if (required_amount <= 0) + return resolve({ + input_size: rec_args.input_size, + input_amount: rec_args.input_amount, + change_amount: required_amount * -1 //required_amount will be -ve of change_amount + }); + else if (rec_args.n >= senders.length) + return reject("Insufficient Balance"); + let addr = senders[rec_args.n], + rs = redeemScripts[rec_args.n]; + let size_per_input = _sizePerInput(addr, rs); fetch_api(`get_tx_unspent/BTC/${addr}`).then(result => { let utxos = result.data.txs; console.debug("add-utxo", addr, rs, required_amount, utxos); for (let i = 0; i < utxos.length && required_amount > 0; i++) { if (!utxos[i].confirmations) //ignore unconfirmed utxo continue; - required_amount -= parseFloat(utxos[i].value); var script; if (!rs || !rs.length) //legacy script script = utxos[i].script_hex; @@ -315,29 +382,38 @@ let s = coinjs.script(); s.writeBytes(Crypto.util.hexToBytes(rs)); s.writeOp(0); - s.writeBytes(coinjs.numToBytes((utxos[i].value * 100000000).toFixed(0), 8)); + s.writeBytes(coinjs.numToBytes((utxos[i].value * SATOSHI_IN_BTC).toFixed(0), 8)); script = Crypto.util.bytesToHex(s.buffer); } else //redeemScript for multisig script = rs; tx.addinput(utxos[i].txid, utxos[i].output_no, script, 0xfffffffd /*sequence*/ ); //0xfffffffd for Replace-by-fee + //update track values + rec_args.input_size += size_per_input; + rec_args.input_amount += parseFloat(utxos[i].value); + required_amount -= parseFloat(utxos[i].value); + if (fee_rate) //automatic fee calculation (dynamic) + required_amount += size_per_input * fee_rate; } - addUTXOs(tx, senders, redeemScripts, required_amount, n + 1) + rec_args.n += 1; + addUTXOs(tx, senders, redeemScripts, required_amount, fee_rate, rec_args) .then(result => resolve(result)) .catch(error => reject(error)) }).catch(error => reject(error)) }) } - function addOutputs(tx, receivers, amounts, change, change_addr) { - for (let i in receivers) + function addOutputs(tx, receivers, amounts, change_addr) { + let size = 0; + for (let i in receivers) { tx.addoutput(receivers[i], amounts[i]); - if (parseFloat(change.toFixed(8)) > 0) { - tx.addoutput(change_addr, change); - return true; - } else - return false; + size += _sizePerOutput(receivers[i]); + } + tx.addoutput(change_addr, 0); + size += _sizePerOutput(change_addr); + return size; } + /* function autoFeeCalc(tx) { return new Promise((resolve, reject) => { get_fee_rate().then(fee_rate => { @@ -362,16 +438,17 @@ function editFee(tx, current_fee, target_fee, index = -1) { //values are in satoshi - index = parseInt(index >= 0 ? index : tx.out.length - index); - if (index < 0 || index >= tx.out.length) + index = parseInt(index >= 0 ? index : tx.outs.length - index); + if (index < 0 || index >= tx.outs.length) throw "Invalid index"; let edit_value = parseInt(current_fee - target_fee), //rip of any decimal places - current_value = tx.out[index].value; //could be BigInterger + current_value = tx.outs[index].value; //could be BigInterger if (edit_value < 0 && edit_value > current_value) throw "Insufficient value at vout"; - tx.out[index].value = current_value instanceof BigInteger ? + tx.outs[index].value = current_value instanceof BigInteger ? current_value.add(new BigInteger('' + edit_value)) : parseInt(current_value + edit_value); } + */ btcOperator.sendTx = function(senders, privkeys, receivers, amounts, fee, change_addr = null) { return new Promise((resolve, reject) => { @@ -402,7 +479,8 @@ if (redeemScripts.includes(null)) //TODO: segwit return reject("Unable to get redeem-script"); //create transaction - createTransaction(senders, redeemScripts, receivers, amounts, fee, change_addr || senders[0]).then(tx => { + createTransaction(senders, redeemScripts, receivers, amounts, fee, change_addr || senders[0]).then(result => { + let tx = result.transaction; console.debug("Unsigned:", tx.serialize()); new Set(wif_keys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/ ))); //Sign the tx using private key WIF console.debug("Signed:", tx.serialize()); @@ -435,9 +513,11 @@ if (redeemScripts.includes(null)) //TODO: segwit return reject("Unable to get redeem-script"); //create transaction - createTransaction(senders, redeemScripts, receivers, amounts, fee, change_addr || senders[0]) - .then(tx => resolve(tx.serialize())) - .catch(error => reject(error)) + createTransaction(senders, redeemScripts, receivers, amounts, fee, change_addr || senders[0]).then(result => { + result.tx_hex = result.transaction.serialize(); + delete result.transaction; + resolve(result); + }).catch(error => reject(error)) }) } @@ -465,9 +545,12 @@ return reject(e) } //create transaction - createTransaction([sender], [redeemScript], receivers, amounts, fee, sender) - .then(tx => resolve(tx.serialize())) - .catch(error => reject(error)) + createTransaction([sender], [redeemScript], receivers, amounts, fee, sender).then(result => { + result.tx_hex = result.transaction.serialize(); + delete result.transaction; + resolve(result); + }).catch(error => reject(error)) + }) } From 39d34f6e8ca61fc368ebc74f6c8cc6f2c3a17241 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 4 Sep 2022 04:09:27 +0530 Subject: [PATCH 222/289] floCloudAPI v2.4.2e - Adding generalDataset to floGlobals: returns the filtered general data set. (Parameters type and options) --- floCloudAPI.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/floCloudAPI.js b/floCloudAPI.js index 1fafb51..98dbfa6 100644 --- a/floCloudAPI.js +++ b/floCloudAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCloudAPI v2.4.2d +(function(EXPORTS) { //floCloudAPI v2.4.2e /* FLO Cloud operations to send/request application data*/ 'use strict'; const floCloudAPI = EXPORTS; @@ -79,6 +79,9 @@ get: () => generalData, set: data => generalData = data }, + generalDataset: { + value: (type, options = {}) => generalData[filterKey(type, options)] + }, lastVC: { get: () => lastVC, set: vc => lastVC = vc @@ -375,7 +378,7 @@ return JSON.parse(decodeURIComponent(escape(atob(message)))) } - const filterKey = util.filterKey = function(type, options) { + const filterKey = util.filterKey = function(type, options = {}) { return type + (options.comment ? ':' + options.comment : '') + '|' + (options.group || options.receiverID || DEFAULT.adminID) + '|' + (options.application || DEFAULT.application); @@ -1025,7 +1028,6 @@ return obj; } - const findDiff = (lhs, rhs) => ({ added: addedDiff(lhs, rhs), deleted: deletedDiff(lhs, rhs), From 084ffe10e2dd609c3ef5a40cee1b93e6602e07b0 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 11 Sep 2022 22:36:50 +0530 Subject: [PATCH 223/289] btcOperator v1.0.10: parseTransaction - Added parseTransaction: parse the given transaction Parameters: tx : transaction hex (or tx object from coinjs.transaction) Resolves: parsed object --- btcOperator.js | 52 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index 9593541..1d0147a 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //btcOperator v1.0.9 +(function(EXPORTS) { //btcOperator v1.0.10 /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -577,7 +577,7 @@ return tx.serialize(); } - btcOperator.checkSigned = function(tx, bool = true) { + const checkSigned = btcOperator.checkSigned = function(tx, bool = true) { tx = deserializeTx(tx); let n = []; for (let i in tx.ins) { @@ -616,6 +616,54 @@ return true; } + const getTxOutput = (txid, i) => new Promise((resolve, reject) => { + fetch_api(`get_tx_outputs/BTC/${txid}/${i}`) + .then(result => resolve(result.data.outputs)) + .catch(error => reject(error)) + }); + + btcOperator.parseTransaction = function(tx) { + return new Promise((resolve, reject) => { + tx = deserializeTx(tx); + let result = {}; + let promises = []; + //Parse Inputs + for (let i = 0; i < tx.ins.length; i++) + promises.push(getTxOutput(tx.ins[i].outpoint.hash, tx.ins[i].outpoint.index)); + Promise.all(promises).then(inputs => { + result.inputs = inputs.map(inp => Object({ + address: inp.address, + value: parseFloat(inp.value) + })); + let signed = checkSigned(tx, false); + result.inputs.forEach((inp, i) => inp.signed = signed[i]); + //Parse Outputs + result.outputs = tx.outs.map(out => { + var address; + switch (out.script.chunks[0]) { + case 0: //bech32 + address = encodeBech32(Crypto.util.bytesToHex(out.script.chunks[1]), coinjs.bech32.version, coinjs.bech32.hrp); + break; + case 169: //multisig, segwit + address = encodeLegacy(Crypto.util.bytesToHex(out.script.chunks[1]), coinjs.multisig); + break; + case 118: //legacy + address = encodeLegacy(Crypto.util.bytesToHex(out.script.chunks[2]), coinjs.pub); + } + return { + address, + value: parseFloat(out.value / SATOSHI_IN_BTC) + } + }); + //Parse Totals + result.total_input = parseFloat(result.inputs.reduce((a, inp) => a += inp.value, 0).toFixed(8)); + result.total_output = parseFloat(result.outputs.reduce((a, out) => a += out.value, 0).toFixed(8)); + result.fee = parseFloat((result.total_input - result.total_output).toFixed(8)); + resolve(result); + }).catch(error => reject(error)) + }) + } + btcOperator.getTx = txid => new Promise((resolve, reject) => { fetch_api(`get_tx/BTC/${txid}`) .then(result => resolve(result.data)) From 7d84ded4260c82cb02419e0cfcfc5d39ee242923 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 30 Sep 2022 05:11:09 +0530 Subject: [PATCH 224/289] btcOperator v1.0.10a: broadcastTx resolves txid - When broadcast is successful, txid is resolved - sendTx also resolves txid due to the above change --- btcOperator.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index 1d0147a..7406ba2 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //btcOperator v1.0.10 +(function(EXPORTS) { //btcOperator v1.0.10a /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -31,16 +31,16 @@ }) } - const broadcast = btcOperator.broadcast = rawtx => new Promise((resolve, reject) => { + const broadcastTx = btcOperator.broadcastTx = rawTxHex => new Promise((resolve, reject) => { $.ajax({ type: "POST", url: URL + "send_tx/BTC/", data: { - "tx_hex": rawtx + "tx_hex": rawTxHex }, dataType: "json", error: e => reject(e.responseJSON), - success: r => r.status === "success" ? resolve(r.data) : reject(r) + success: r => r.status === "success" ? resolve(r.data.txid) : reject(r) }) }); @@ -485,8 +485,8 @@ new Set(wif_keys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/ ))); //Sign the tx using private key WIF console.debug("Signed:", tx.serialize()); debugger; - broadcast(tx.serialize()) - .then(result => resolve(result)) + broadcastTx(tx.serialize()) + .then(txid => resolve(txid)) .catch(error => reject(error)); }).catch(error => reject(error)); }) From c38b7257cfd9836da6a98955704c203f148aff46 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 14 Oct 2022 23:11:05 +0530 Subject: [PATCH 225/289] Minor fixes floCrypto v2.3.3e - Adding options args to toFloID function. options object accept std and/or bech properties. if specified only converts if given address are from specified version floBlockchainAPI v2.3.3c - Fixed: tx failing due to dust amount in change value - readData: when passes tx option as true, now also gives senders and receivers (Set) btcOperator v1.0.10b - Fixed: minor bugs --- btcOperator.js | 46 ++++++++++++++++----------------- floBlockchainAPI.js | 33 +++++++++++++----------- floCrypto.js | 62 +++++++++++++++++++++++++-------------------- 3 files changed, 75 insertions(+), 66 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index 7406ba2..9fc39d2 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,11 +1,11 @@ -(function(EXPORTS) { //btcOperator v1.0.10a +(function (EXPORTS) { //btcOperator v1.0.10b /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; //This library uses API provided by chain.so (https://chain.so/) const URL = "https://chain.so/api/v2/"; - const fetch_api = btcOperator.fetch = function(api) { + const fetch_api = btcOperator.fetch = function (api) { return new Promise((resolve, reject) => { console.debug(URL + api); fetch(URL + api).then(response => { @@ -23,8 +23,8 @@ fetch('https://api.blockchain.info/mempool/fees').then(response => { if (response.ok) response.json() - .then(result => resolve(parseFloat((result.regular / SATOSHI_IN_BTC).toFixed(8)))) - .catch(error => reject(error)); + .then(result => resolve(parseFloat((result.regular / SATOSHI_IN_BTC).toFixed(8)))) + .catch(error => reject(error)); else reject(response); }).catch(error => reject(error)) @@ -69,7 +69,7 @@ coinjs.compressed = true; - const verifyKey = btcOperator.verifyKey = function(addr, key) { + const verifyKey = btcOperator.verifyKey = function (addr, key) { if (!addr || !key) return undefined; switch (coinjs.addressDecode(addr).type) { @@ -84,7 +84,7 @@ } } - const validateAddress = btcOperator.validateAddress = function(addr) { + const validateAddress = btcOperator.validateAddress = function (addr) { if (!addr) return undefined; let type = coinjs.addressDecode(addr).type; @@ -94,7 +94,7 @@ return false; } - btcOperator.multiSigAddress = function(pubKeys, minRequired) { + btcOperator.multiSigAddress = function (pubKeys, minRequired) { if (!Array.isArray(pubKeys)) throw "pubKeys must be an array of public keys"; else if (pubKeys.length < minRequired) @@ -105,7 +105,7 @@ //convert from one blockchain to another blockchain (target version) btcOperator.convert = {}; - btcOperator.convert.wif = function(source_wif, target_version = coinjs.priv) { + btcOperator.convert.wif = function (source_wif, target_version = coinjs.priv) { let keyHex = decodeLegacy(source_wif).hex; if (!keyHex || keyHex.length < 66 || !/01$/.test(keyHex)) return null; @@ -113,7 +113,7 @@ return encodeLegacy(keyHex, target_version); } - btcOperator.convert.legacy2legacy = function(source_addr, target_version = coinjs.pub) { + btcOperator.convert.legacy2legacy = function (source_addr, target_version = coinjs.pub) { let rawHex = decodeLegacy(source_addr).hex; if (!rawHex) return null; @@ -121,7 +121,7 @@ return encodeLegacy(rawHex, target_version); } - btcOperator.convert.legacy2bech = function(source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) { + btcOperator.convert.legacy2bech = function (source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) { let rawHex = decodeLegacy(source_addr).hex; if (!rawHex) return null; @@ -129,7 +129,7 @@ return encodeBech32(rawHex, target_version, target_hrp); } - btcOperator.convert.bech2bech = function(source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) { + btcOperator.convert.bech2bech = function (source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) { let rawHex = decodeBech32(source_addr).hex; if (!rawHex) return null; @@ -137,7 +137,7 @@ return encodeBech32(rawHex, target_version, target_hrp); } - btcOperator.convert.bech2legacy = function(source_addr, target_version = coinjs.pub) { + btcOperator.convert.bech2legacy = function (source_addr, target_version = coinjs.pub) { let rawHex = decodeBech32(source_addr).hex; if (!rawHex) return null; @@ -340,7 +340,7 @@ let net_fee = BASE_TX_SIZE * fee_rate; net_fee += (output_size * fee_rate); addUTXOs(tx, senders, redeemScripts, total_amount + net_fee, fee_rate).then(result => { - result.fee_amount = parseFloat((net_fee + (result.input_size * fee_rate)).toFixed(8)); + result.fee = parseFloat((net_fee + (result.input_size * fee_rate)).toFixed(8)); result.fee_rate = fee_rate; resolve(result); }).catch(error => reject(error)) @@ -386,7 +386,7 @@ script = Crypto.util.bytesToHex(s.buffer); } else //redeemScript for multisig script = rs; - tx.addinput(utxos[i].txid, utxos[i].output_no, script, 0xfffffffd /*sequence*/ ); //0xfffffffd for Replace-by-fee + tx.addinput(utxos[i].txid, utxos[i].output_no, script, 0xfffffffd /*sequence*/); //0xfffffffd for Replace-by-fee //update track values rec_args.input_size += size_per_input; rec_args.input_amount += parseFloat(utxos[i].value); @@ -450,7 +450,7 @@ } */ - btcOperator.sendTx = function(senders, privkeys, receivers, amounts, fee, change_addr = null) { + btcOperator.sendTx = function (senders, privkeys, receivers, amounts, fee, change_addr = null) { return new Promise((resolve, reject) => { try { ({ @@ -482,7 +482,7 @@ createTransaction(senders, redeemScripts, receivers, amounts, fee, change_addr || senders[0]).then(result => { let tx = result.transaction; console.debug("Unsigned:", tx.serialize()); - new Set(wif_keys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/ ))); //Sign the tx using private key WIF + new Set(wif_keys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/))); //Sign the tx using private key WIF console.debug("Signed:", tx.serialize()); debugger; broadcastTx(tx.serialize()) @@ -492,7 +492,7 @@ }) } - btcOperator.createTx = function(senders, receivers, amounts, fee = null, change_addr = null) { + btcOperator.createTx = function (senders, receivers, amounts, fee = null, change_addr = null) { return new Promise((resolve, reject) => { try { ({ @@ -521,7 +521,7 @@ }) } - btcOperator.createMultiSigTx = function(sender, redeemScript, receivers, amounts, fee) { + btcOperator.createMultiSigTx = function (sender, redeemScript, receivers, amounts, fee) { return new Promise((resolve, reject) => { //validate tx parameters if (validateAddress(sender) !== "multisig") @@ -566,7 +566,7 @@ return tx; } - btcOperator.signTx = function(tx, privkeys, sighashtype = 1) { + btcOperator.signTx = function (tx, privkeys, sighashtype = 1) { tx = deserializeTx(tx); if (!Array.isArray(privkeys)) privkeys = [privkeys]; @@ -577,7 +577,7 @@ return tx.serialize(); } - const checkSigned = btcOperator.checkSigned = function(tx, bool = true) { + const checkSigned = btcOperator.checkSigned = function (tx, bool = true) { tx = deserializeTx(tx); let n = []; for (let i in tx.ins) { @@ -602,7 +602,7 @@ return bool ? !(n.filter(x => x !== true).length) : n; } - btcOperator.checkIfSameTx = function(tx1, tx2) { + btcOperator.checkIfSameTx = function (tx1, tx2) { tx1 = deserializeTx(tx1); tx2 = deserializeTx(tx2); if (tx1.ins.length !== tx2.ins.length || tx1.outs.length !== tx2.outs.length) @@ -622,7 +622,7 @@ .catch(error => reject(error)) }); - btcOperator.parseTransaction = function(tx) { + btcOperator.parseTransaction = function (tx) { return new Promise((resolve, reject) => { tx = deserializeTx(tx); let result = {}; @@ -665,7 +665,7 @@ } btcOperator.getTx = txid => new Promise((resolve, reject) => { - fetch_api(`get_tx/BTC/${txid}`) + fetch_api(`tx/BTC/${txid}`) .then(result => resolve(result.data)) .catch(error => reject(error)) }); diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index d250f86..5bb3cbb 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floBlockchainAPI v2.3.3b +(function (EXPORTS) { //floBlockchainAPI v2.3.3c /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -11,6 +11,7 @@ }, sendAmt: 0.001, fee: 0.0005, + minChangeAmt: 0.0005, receiverID: floGlobals.adminID }; @@ -102,7 +103,7 @@ }); //Promised function to get data from API - const promisedAPI = floBlockchainAPI.promisedAPI = floBlockchainAPI.fetch = function(apicall) { + const promisedAPI = floBlockchainAPI.promisedAPI = floBlockchainAPI.fetch = function (apicall) { return new Promise((resolve, reject) => { //console.log(apicall); fetch_api(apicall) @@ -112,7 +113,7 @@ } //Get balance for the given Address - const getBalance = floBlockchainAPI.getBalance = function(addr) { + const getBalance = floBlockchainAPI.getBalance = function (addr) { return new Promise((resolve, reject) => { promisedAPI(`api/addr/${addr}/balance`) .then(balance => resolve(parseFloat(balance))) @@ -121,7 +122,7 @@ } //Send Tx to blockchain - const sendTx = floBlockchainAPI.sendTx = function(senderAddr, receiverAddr, sendAmt, privKey, floData = '', strict_utxo = true) { + const sendTx = floBlockchainAPI.sendTx = function (senderAddr, receiverAddr, sendAmt, privKey, floData = '', strict_utxo = true) { return new Promise((resolve, reject) => { if (!floCrypto.validateASCII(floData)) return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); @@ -171,7 +172,7 @@ else { trx.addoutput(receiverAddr, sendAmt); var change = utxoAmt - sendAmt - fee; - if (change > 0) + if (change > DEFAULT.minChangeAmt) trx.addoutput(senderAddr, change); trx.addflodata(floData.replace(/\n/g, ' ')); var signedTxHash = trx.sign(privKey, 1); @@ -187,7 +188,7 @@ } //Write Data into blockchain - floBlockchainAPI.writeData = function(senderAddr, data, privKey, receiverAddr = DEFAULT.receiverID, options = {}) { + floBlockchainAPI.writeData = function (senderAddr, data, privKey, receiverAddr = DEFAULT.receiverID, options = {}) { let strict_utxo = options.strict_utxo === false ? false : true, sendAmt = isNaN(options.sendAmt) ? DEFAULT.sendAmt : options.sendAmt; return new Promise((resolve, reject) => { @@ -200,7 +201,7 @@ } //merge all UTXOs of a given floID into a single UTXO - floBlockchainAPI.mergeUTXOs = function(floID, privKey, floData = '') { + floBlockchainAPI.mergeUTXOs = function (floID, privKey, floData = '') { return new Promise((resolve, reject) => { if (!floCrypto.validateFloID(floID)) return reject(`Invalid floID`); @@ -234,7 +235,7 @@ * @param {boolean} preserveRatio (optional) preserve ratio or equal contribution * @return {Promise} */ - floBlockchainAPI.writeDataMultiple = function(senderPrivKeys, data, receivers = [DEFAULT.receiverID], preserveRatio = true) { + floBlockchainAPI.writeDataMultiple = function (senderPrivKeys, data, receivers = [DEFAULT.receiverID], preserveRatio = true) { return new Promise((resolve, reject) => { if (!Array.isArray(senderPrivKeys)) return reject("Invalid senderPrivKeys: SenderPrivKeys must be Array"); @@ -266,7 +267,7 @@ * @param {string} floData FLO data of the txn * @return {Promise} */ - const sendTxMultiple = floBlockchainAPI.sendTxMultiple = function(senderPrivKeys, receivers, floData = '') { + const sendTxMultiple = floBlockchainAPI.sendTxMultiple = function (senderPrivKeys, receivers, floData = '') { return new Promise((resolve, reject) => { if (!floCrypto.validateASCII(floData)) return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); @@ -421,7 +422,7 @@ } //Broadcast signed Tx in blockchain using API - const broadcastTx = floBlockchainAPI.broadcastTx = function(signedTxHash) { + const broadcastTx = floBlockchainAPI.broadcastTx = function (signedTxHash) { return new Promise((resolve, reject) => { if (signedTxHash.length < 1) return reject("Empty Signature"); @@ -441,7 +442,7 @@ }) } - floBlockchainAPI.getTx = function(txid) { + floBlockchainAPI.getTx = function (txid) { return new Promise((resolve, reject) => { promisedAPI(`api/tx/${txid}`) .then(response => resolve(response)) @@ -450,7 +451,7 @@ } //Read Txs of Address between from and to - const readTxs = floBlockchainAPI.readTxs = function(addr, from, to) { + const readTxs = floBlockchainAPI.readTxs = function (addr, from, to) { return new Promise((resolve, reject) => { promisedAPI(`api/addrs/${addr}/txs?from=${from}&to=${to}`) .then(response => resolve(response)) @@ -459,7 +460,7 @@ } //Read All Txs of Address (newest first) - floBlockchainAPI.readAllTxs = function(addr) { + floBlockchainAPI.readAllTxs = function (addr) { return new Promise((resolve, reject) => { promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => { promisedAPI(`api/addrs/${addr}/txs?from=0&to=${response.totalItems}0`) @@ -481,7 +482,7 @@ sender : flo-id(s) of sender receiver : flo-id(s) of receiver */ - floBlockchainAPI.readData = function(addr, options = {}) { + floBlockchainAPI.readData = function (addr, options = {}) { options.limit = options.limit || 0; options.ignoreOld = options.ignoreOld || 0; if (typeof options.sender === "string") options.sender = [options.sender]; @@ -489,7 +490,7 @@ return new Promise((resolve, reject) => { promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => { var newItems = response.totalItems - options.ignoreOld; - promisedAPI(`api/addrs/${addr}/txs?from=0&to=${newItems*2}`).then(response => { + promisedAPI(`api/addrs/${addr}/txs?from=0&to=${newItems * 2}`).then(response => { if (options.limit <= 0) options.limit = response.items.length; var filteredData = []; @@ -555,6 +556,8 @@ d.txid = response.items[i].txid; d.time = response.items[i].time; d.blockheight = response.items[i].blockheight; + d.senders = new Set(response.items[i].vin.map(v => v.addr)); + d.receivers = new Set(response.items[i].vout.map(v => v.scriptPubKey.addresses[0])); d.data = response.items[i].floData; filteredData.push(d); } else diff --git a/floCrypto.js b/floCrypto.js index 6671ffa..563d77f 100644 --- a/floCrypto.js +++ b/floCrypto.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCrypto v2.3.3d +(function (EXPORTS) { //floCrypto v2.3.3e /* FLO Crypto Operators */ 'use strict'; const floCrypto = EXPORTS; @@ -78,14 +78,14 @@ } //generate a random Interger within range - floCrypto.randInt = function(min, max) { + floCrypto.randInt = function (min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(securedMathRandom() * (max - min + 1)) + min; } //generate a random String within length (options : alphaNumeric chars only) - floCrypto.randString = function(length, alphaNumeric = true) { + floCrypto.randString = function (length, alphaNumeric = true) { var result = ''; var characters = alphaNumeric ? 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+-./*?@#&$<>=[]{}():'; @@ -95,7 +95,7 @@ } //Encrypt Data using public-key - floCrypto.encryptData = function(data, receiverPublicKeyHex) { + floCrypto.encryptData = function (data, receiverPublicKeyHex) { var senderECKeyData = getSenderPublicKeyString(); var senderDerivedKey = deriveSharedKeySender(receiverPublicKeyHex, senderECKeyData.privateKey); let senderKey = senderDerivedKey.XValue + senderDerivedKey.YValue; @@ -107,7 +107,7 @@ } //Decrypt Data using private-key - floCrypto.decryptData = function(data, privateKeyHex) { + floCrypto.decryptData = function (data, privateKeyHex) { var receiverECKeyData = {}; if (typeof privateKeyHex !== "string") throw new Error("No private key found."); let privateKey = wifToDecimal(privateKeyHex, true); @@ -120,7 +120,7 @@ } //Sign data using private-key - floCrypto.signData = function(data, privateKeyHex) { + floCrypto.signData = function (data, privateKeyHex) { var key = new Bitcoin.ECKey(privateKeyHex); var messageHash = Crypto.SHA256(data); var messageSign = Bitcoin.ECDSA.sign(messageHash, key.priv); @@ -129,7 +129,7 @@ } //Verify signatue of the data using public-key - floCrypto.verifySign = function(data, signatureHex, publicKeyHex) { + floCrypto.verifySign = function (data, signatureHex, publicKeyHex) { var msgHash = Crypto.SHA256(data); var sigBytes = Crypto.util.hexToBytes(signatureHex); var publicKeyPoint = ecparams.getCurve().decodePointHex(publicKeyHex); @@ -138,7 +138,7 @@ } //Generates a new flo ID and returns private-key, public-key and floID - const generateNewID = floCrypto.generateNewID = function() { + const generateNewID = floCrypto.generateNewID = function () { var key = new Bitcoin.ECKey(false); key.setCompressed(true); return { @@ -168,7 +168,7 @@ }); //Returns public-key from private-key - floCrypto.getPubKeyHex = function(privateKeyHex) { + floCrypto.getPubKeyHex = function (privateKeyHex) { if (!privateKeyHex) return null; var key = new Bitcoin.ECKey(privateKeyHex); @@ -179,7 +179,7 @@ } //Returns flo-ID from public-key or private-key - floCrypto.getFloID = function(keyHex) { + floCrypto.getFloID = function (keyHex) { if (!keyHex) return null; try { @@ -192,7 +192,7 @@ } } - floCrypto.getAddress = function(privateKeyHex, strict = false) { + floCrypto.getAddress = function (privateKeyHex, strict = false) { if (!privateKeyHex) return; var key = new Bitcoin.ECKey(privateKeyHex); @@ -212,7 +212,7 @@ } //Verify the private-key for the given public-key or flo-ID - floCrypto.verifyPrivKey = function(privateKeyHex, pubKey_floID, isfloID = true) { + floCrypto.verifyPrivKey = function (privateKeyHex, pubKey_floID, isfloID = true) { if (!privateKeyHex || !pubKey_floID) return false; try { @@ -232,7 +232,7 @@ } //Check if the given flo-id is valid or not - floCrypto.validateFloID = function(floID) { + floCrypto.validateFloID = function (floID) { if (!floID) return false; try { @@ -244,7 +244,7 @@ } //Check if the given address (any blockchain) is valid or not - floCrypto.validateAddr = function(address, std = true, bech = true) { + floCrypto.validateAddr = function (address, std = true, bech = true) { let raw = decodeAddress(address); if (!raw) return false; @@ -267,7 +267,7 @@ } //Check the public-key for the address (any blockchain) - floCrypto.verifyPubKey = function(pubKeyHex, address) { + floCrypto.verifyPubKey = function (pubKeyHex, address) { let raw = decodeAddress(address), pub_hash = Crypto.util.bytesToHex(ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubKeyHex), { asBytes: true @@ -276,12 +276,18 @@ } //Convert the given address (any blockchain) to equivalent floID - floCrypto.toFloID = function(address) { + floCrypto.toFloID = function (address, options = null) { if (!address) return; let raw = decodeAddress(address); if (!raw) return; + else if (options) { + if (typeof raw.version !== 'undefined' && (!options.std || !options.std.includes(raw.version))) + return; + if (typeof raw.bech_version !== 'undefined' && (!options.bech || !options.bech.includes(raw.bech_version))) + return; + } raw.bytes.unshift(bitjs.pub); let hash = Crypto.SHA256(Crypto.SHA256(raw.bytes, { asBytes: true @@ -292,7 +298,7 @@ } //Checks if the given addresses (any blockchain) are same (w.r.t keys) - floCrypto.isSameAddr = function(addr1, addr2) { + floCrypto.isSameAddr = function (addr1, addr2) { if (!addr1 || !addr2) return; let raw1 = decodeAddress(addr1), @@ -303,7 +309,7 @@ return raw1.hex === raw2.hex; } - const decodeAddress = floCrypto.decodeAddr = function(address) { + const decodeAddress = floCrypto.decodeAddr = function (address) { if (!address) return; else if (address.length == 33 || address.length == 34) { //legacy encoding @@ -338,7 +344,7 @@ } //Split the str using shamir's Secret and Returns the shares - floCrypto.createShamirsSecretShares = function(str, total_shares, threshold_limit) { + floCrypto.createShamirsSecretShares = function (str, total_shares, threshold_limit) { try { if (str.length > 0) { var strHex = shamirSecretShare.str2hex(str); @@ -352,7 +358,7 @@ } //Returns the retrived secret by combining the shamirs shares - const retrieveShamirSecret = floCrypto.retrieveShamirSecret = function(sharesArray) { + const retrieveShamirSecret = floCrypto.retrieveShamirSecret = function (sharesArray) { try { if (sharesArray.length > 0) { var comb = shamirSecretShare.combine(sharesArray.slice(0, sharesArray.length)); @@ -366,7 +372,7 @@ } //Verifies the shares and str - floCrypto.verifyShamirsSecret = function(sharesArray, str) { + floCrypto.verifyShamirsSecret = function (sharesArray, str) { if (!str) return null; else if (retrieveShamirSecret(sharesArray) === str) @@ -375,7 +381,7 @@ return false; } - const validateASCII = floCrypto.validateASCII = function(string, bool = true) { + const validateASCII = floCrypto.validateASCII = function (string, bool = true) { if (typeof string !== "string") return null; if (bool) { @@ -393,8 +399,8 @@ if (x < 32 || x > 127) if (x in invalids) invalids[string[i]].push(i) - else - invalids[string[i]] = [i]; + else + invalids[string[i]] = [i]; } if (Object.keys(invalids).length) return invalids; @@ -403,7 +409,7 @@ } } - floCrypto.convertToASCII = function(string, mode = 'soft-remove') { + floCrypto.convertToASCII = function (string, mode = 'soft-remove') { let chars = validateASCII(string, false); if (chars === true) return string; @@ -414,9 +420,9 @@ ascii_alternatives.split('\n').forEach(a => refAlt[a[0]] = a.slice(2)); mode = mode.toLowerCase(); if (mode === "hard-unicode") - convertor = (c) => `\\u${('000'+c.charCodeAt().toString(16)).slice(-4)}`; + convertor = (c) => `\\u${('000' + c.charCodeAt().toString(16)).slice(-4)}`; else if (mode === "soft-unicode") - convertor = (c) => refAlt[c] || `\\u${('000'+c.charCodeAt().toString(16)).slice(-4)}`; + convertor = (c) => refAlt[c] || `\\u${('000' + c.charCodeAt().toString(16)).slice(-4)}`; else if (mode === "hard-remove") convertor = c => ""; else if (mode === "soft-remove") @@ -428,7 +434,7 @@ return result; } - floCrypto.revertUnicode = function(string) { + floCrypto.revertUnicode = function (string) { return string.replace(/\\u[\dA-F]{4}/gi, m => String.fromCharCode(parseInt(m.replace(/\\u/g, ''), 16))); } From 87f0260fe482fbbb2e3a2e891bc5bdc2ad000194 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 18 Oct 2022 04:43:53 +0530 Subject: [PATCH 226/289] btcOperator v1.0.11 - Added createSignedTx: creates a signed tx (same as sendTx, but doesnt broadcast) - Added transactionID: returns the txid of the tx_hex (or tx-object) --- btcOperator.js | 29 +++++++++++++++++++++++------ index.html | 1 + 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index 9fc39d2..ce8b09d 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //btcOperator v1.0.10b +(function (EXPORTS) { //btcOperator v1.0.11 /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -39,7 +39,7 @@ "tx_hex": rawTxHex }, dataType: "json", - error: e => reject(e.responseJSON), + error: e => reject((e.responseJSON && e.responseJSON.status === "fail") ? null : e.responseJSON), success: r => r.status === "success" ? resolve(r.data.txid) : reject(r) }) }); @@ -451,6 +451,17 @@ */ btcOperator.sendTx = function (senders, privkeys, receivers, amounts, fee, change_addr = null) { + return new Promise((resolve, reject) => { + createSignedTx(senders, privkeys, receivers, amounts, fee, change_addr).then(result => { + debugger; + broadcastTx(result.transaction.serialize()) + .then(txid => resolve(txid)) + .catch(error => reject(error)); + }).catch(error => reject(error)) + }) + } + + const createSignedTx = btcOperator.createSignedTx = function (senders, privkeys, receivers, amounts, fee, change_addr = null) { return new Promise((resolve, reject) => { try { ({ @@ -484,10 +495,7 @@ console.debug("Unsigned:", tx.serialize()); new Set(wif_keys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/))); //Sign the tx using private key WIF console.debug("Signed:", tx.serialize()); - debugger; - broadcastTx(tx.serialize()) - .then(txid => resolve(txid)) - .catch(error => reject(error)); + resolve(result); }).catch(error => reject(error)); }) } @@ -664,6 +672,15 @@ }) } + btcOperator.transactionID = function (tx) { + tx = deserializeTx(tx); + let clone = coinjs.clone(tx); + clone.witness = null; + let raw_bytes = Crypto.util.hexToBytes(clone.serialize()); + let txid = Crypto.SHA256(Crypto.SHA256(raw_bytes, { asBytes: true }), { asBytes: true }).reverse(); + return Crypto.util.bytesToHex(txid); + } + btcOperator.getTx = txid => new Promise((resolve, reject) => { fetch_api(`tx/BTC/${txid}`) .then(result => resolve(result.data)) diff --git a/index.html b/index.html index 2b60d9d..7ec9496 100644 --- a/index.html +++ b/index.html @@ -13,6 +13,7 @@ + From d21db616da4cb5cfb46c46689c482f97b812cf29 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Mon, 24 Oct 2022 15:38:48 +0530 Subject: [PATCH 227/289] btcOperator v1.0.12 - Changed broadcastTx to coinb API to eliminate $.ajax requirement - Set default value for fee=null (automatic fee) to createSignedTx and createMultiSigTx --- btcOperator.js | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index ce8b09d..bb0b7ca 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //btcOperator v1.0.11 +(function (EXPORTS) { //btcOperator v1.0.12 /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -32,16 +32,30 @@ } const broadcastTx = btcOperator.broadcastTx = rawTxHex => new Promise((resolve, reject) => { - $.ajax({ - type: "POST", - url: URL + "send_tx/BTC/", - data: { - "tx_hex": rawTxHex + let url = 'https://coinb.in/api/?uid=1&key=12345678901234567890123456789012&setmodule=bitcoin&request=sendrawtransaction'; + fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' }, - dataType: "json", - error: e => reject((e.responseJSON && e.responseJSON.status === "fail") ? null : e.responseJSON), - success: r => r.status === "success" ? resolve(r.data.txid) : reject(r) - }) + body: "rawtx=" + rawTxHex + }).then(response => { + response.text().then(resultText => { + let r = resultText.match(/.*<\/result>/); + if (!r) + reject(resultText); + else { + r = r.pop().replace('', '').replace('', ''); + if (r == '1') { + let txid = resultText.match(/.*<\/txid>/).pop().replace('', '').replace('', ''); + resolve(txid); + } else if (r == '0') { + let error = resultText.match(/.*<\/response>/).pop().replace('', '').replace('', ''); + reject(decodeURIComponent(error.replace(/\+/g, " "))); + } else reject(resultText); + } + }).catch(error => reject(error)) + }).catch(error => reject(error)) }); Object.defineProperties(btcOperator, { @@ -461,7 +475,7 @@ }) } - const createSignedTx = btcOperator.createSignedTx = function (senders, privkeys, receivers, amounts, fee, change_addr = null) { + const createSignedTx = btcOperator.createSignedTx = function (senders, privkeys, receivers, amounts, fee = null, change_addr = null) { return new Promise((resolve, reject) => { try { ({ @@ -529,7 +543,7 @@ }) } - btcOperator.createMultiSigTx = function (sender, redeemScript, receivers, amounts, fee) { + btcOperator.createMultiSigTx = function (sender, redeemScript, receivers, amounts, fee = null) { return new Promise((resolve, reject) => { //validate tx parameters if (validateAddress(sender) !== "multisig") From bffb130bd4acd529ffc86fbcb8c25058f01936b8 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Wed, 26 Oct 2022 04:58:41 +0530 Subject: [PATCH 228/289] floBlockchainAPI v2.3.3d - renamed sender and receiver options to senders and receivers (bug fix) --- floBlockchainAPI.js | 14 +++++++------- floTokenAPI.js | 18 +++++++++--------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 5bb3cbb..473b192 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.3.3c +(function (EXPORTS) { //floBlockchainAPI v2.3.3d /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -485,8 +485,8 @@ floBlockchainAPI.readData = function (addr, options = {}) { options.limit = options.limit || 0; options.ignoreOld = options.ignoreOld || 0; - if (typeof options.sender === "string") options.sender = [options.sender]; - if (typeof options.receiver === "string") options.receiver = [options.receiver]; + if (typeof options.senders === "string") options.senders = [options.senders]; + if (typeof options.receivers === "string") options.receivers = [options.receivers]; return new Promise((resolve, reject) => { promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => { var newItems = response.totalItems - options.ignoreOld; @@ -521,10 +521,10 @@ } if (!flag) continue; } - if (Array.isArray(options.sender)) { + if (Array.isArray(options.senders)) { let flag = false; for (let vin of response.items[i].vin) - if (options.sender.includes(vin.addr)) { + if (options.senders.includes(vin.addr)) { flag = true; break; } @@ -539,10 +539,10 @@ } if (!flag) continue; } - if (Array.isArray(options.receiver)) { + if (Array.isArray(options.receivers)) { let flag = false; for (let vout of response.items[i].vout) - if (options.receiver.includes(vout.scriptPubKey.addresses[0])) { + if (options.receivers.includes(vout.scriptPubKey.addresses[0])) { flag = true; break; } diff --git a/floTokenAPI.js b/floTokenAPI.js index 7378f43..efbd2ae 100644 --- a/floTokenAPI.js +++ b/floTokenAPI.js @@ -1,11 +1,11 @@ -(function(EXPORTS) { //floTokenAPI v1.0.3b +(function (EXPORTS) { //floTokenAPI v1.0.3c /* Token Operator to send/receive tokens via blockchain using API calls*/ 'use strict'; const tokenAPI = EXPORTS; const DEFAULT = { apiURL: floGlobals.tokenURL || "https://ranchimallflo.duckdns.org/", - currency: "rupee" + currency: floGlobals.currency || "rupee" } Object.defineProperties(tokenAPI, { @@ -27,9 +27,9 @@ } }); - const fetch_api = tokenAPI.fetch = function(apicall) { + const fetch_api = tokenAPI.fetch = function (apicall) { return new Promise((resolve, reject) => { - console.log(DEFAULT.apiURL + apicall); + console.debug(DEFAULT.apiURL + apicall); fetch(DEFAULT.apiURL + apicall).then(response => { if (response.ok) response.json().then(data => resolve(data)); @@ -39,7 +39,7 @@ }) } - const getBalance = tokenAPI.getBalance = function(floID, token = DEFAULT.currency) { + const getBalance = tokenAPI.getBalance = function (floID, token = DEFAULT.currency) { return new Promise((resolve, reject) => { fetch_api(`api/v1.0/getFloAddressBalance?token=${token}&floAddress=${floID}`) .then(result => resolve(result.balance || 0)) @@ -47,7 +47,7 @@ }) } - tokenAPI.getTx = function(txID) { + tokenAPI.getTx = function (txID) { return new Promise((resolve, reject) => { fetch_api(`api/v1.0/getTransactionDetails/${txID}`).then(res => { if (res.result === "error") @@ -62,7 +62,7 @@ }) } - tokenAPI.sendToken = function(privKey, amount, receiverID, message = "", token = DEFAULT.currency, options = {}) { + tokenAPI.sendToken = function (privKey, amount, receiverID, message = "", token = DEFAULT.currency, options = {}) { return new Promise((resolve, reject) => { let senderID = floCrypto.getFloID(privKey); if (typeof amount !== "number" || isNaN(amount) || amount <= 0) @@ -77,7 +77,7 @@ }); } - tokenAPI.getAllTxs = function(floID, token = DEFAULT.currency) { + tokenAPI.getAllTxs = function (floID, token = DEFAULT.currency) { return new Promise((resolve, reject) => { fetch_api(`api/v1.0/getFloAddressTransactions?token=${token}&floAddress=${floID}`) .then(result => resolve(result)) @@ -87,7 +87,7 @@ const util = tokenAPI.util = {}; - util.parseTxData = function(txData) { + util.parseTxData = function (txData) { let parsedData = {}; for (let p in txData.parsedFloData) parsedData[p] = txData.parsedFloData[p]; From 663dfe2d548b0e58767b666d1b176f2fe3db03db Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 6 Nov 2022 04:27:24 +0530 Subject: [PATCH 229/289] floCloudAPI v2.4.3 - Fixed a rare bug where array has empty value - now `null` is supported by objectData update (ie, objects can now have null as value) --- floCloudAPI.js | 86 +++++++++++++++++++++++--------------------------- 1 file changed, 40 insertions(+), 46 deletions(-) diff --git a/floCloudAPI.js b/floCloudAPI.js index 98dbfa6..921fa69 100644 --- a/floCloudAPI.js +++ b/floCloudAPI.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floCloudAPI v2.4.2e +(function (EXPORTS) { //floCloudAPI v2.4.3 /* FLO Cloud operations to send/request application data*/ 'use strict'; const floCloudAPI = EXPORTS; @@ -94,7 +94,7 @@ }); var kBucket; - const K_Bucket = floCloudAPI.K_Bucket = function(masterID, nodeList) { + const K_Bucket = floCloudAPI.K_Bucket = function (masterID, nodeList) { const decodeID = floID => { let k = bitjs.Base58.decode(floID); @@ -128,7 +128,7 @@ }); self.isNode = floID => _CO.includes(floID); - self.innerNodes = function(id1, id2) { + self.innerNodes = function (id1, id2) { if (!_CO.includes(id1) || !_CO.includes(id2)) throw Error('Given nodes are not supernode'); let iNodes = [] @@ -139,7 +139,7 @@ } return iNodes } - self.outterNodes = function(id1, id2) { + self.outterNodes = function (id1, id2) { if (!_CO.includes(id1) || !_CO.includes(id2)) throw Error('Given nodes are not supernode'); let oNodes = [] @@ -150,7 +150,7 @@ } return oNodes } - self.prevNode = function(id, N = 1) { + self.prevNode = function (id, N = 1) { let n = N || _CO.length; if (!_CO.includes(id)) throw Error('Given node is not supernode'); @@ -164,7 +164,7 @@ } return (N == 1 ? pNodes[0] : pNodes) } - self.nextNode = function(id, N = 1) { + self.nextNode = function (id, N = 1) { let n = N || _CO.length; if (!_CO.includes(id)) throw Error('Given node is not supernode'); @@ -179,7 +179,7 @@ } return (N == 1 ? nNodes[0] : nNodes) } - self.closestNode = function(id, N = 1) { + self.closestNode = function (id, N = 1) { let decodedId = decodeID(id); let n = N || _CO.length; let cNodes = _KB.closest(decodedId, n) @@ -293,8 +293,8 @@ fetch_ActiveAPI(floID, data).then(response => { if (response.ok) response.json() - .then(result => resolve(result)) - .catch(error => reject(error)) + .then(result => resolve(result)) + .catch(error => reject(error)) else response.text() .then(result => reject(response.status + ": " + result)) //Error Message from Node .catch(error => reject(error)) @@ -370,21 +370,21 @@ const util = floCloudAPI.util = {}; - const encodeMessage = util.encodeMessage = function(message) { + const encodeMessage = util.encodeMessage = function (message) { return btoa(unescape(encodeURIComponent(JSON.stringify(message)))) } - const decodeMessage = util.decodeMessage = function(message) { + const decodeMessage = util.decodeMessage = function (message) { return JSON.parse(decodeURIComponent(escape(atob(message)))) } - const filterKey = util.filterKey = function(type, options = {}) { + const filterKey = util.filterKey = function (type, options = {}) { return type + (options.comment ? ':' + options.comment : '') + '|' + (options.group || options.receiverID || DEFAULT.adminID) + '|' + (options.application || DEFAULT.application); } - const proxyID = util.proxyID = function(address) { + const proxyID = util.proxyID = function (address) { if (!address) return; var bytes; @@ -489,7 +489,7 @@ } //set status as online for user_id - floCloudAPI.setStatus = function(options = {}) { + floCloudAPI.setStatus = function (options = {}) { return new Promise((resolve, reject) => { let callback = options.callback instanceof Function ? options.callback : DEFAULT.callback; var request = { @@ -508,7 +508,7 @@ } //request status of floID(s) in trackList - floCloudAPI.requestStatus = function(trackList, options = {}) { + floCloudAPI.requestStatus = function (trackList, options = {}) { return new Promise((resolve, reject) => { if (!Array.isArray(trackList)) trackList = [trackList]; @@ -525,7 +525,7 @@ } //send any message to supernode cloud storage - const sendApplicationData = floCloudAPI.sendApplicationData = function(message, type, options = {}) { + const sendApplicationData = floCloudAPI.sendApplicationData = function (message, type, options = {}) { return new Promise((resolve, reject) => { var data = { senderID: user.id, @@ -547,7 +547,7 @@ } //request any data from supernode cloud - const requestApplicationData = floCloudAPI.requestApplicationData = function(type, options = {}) { + const requestApplicationData = floCloudAPI.requestApplicationData = function (type, options = {}) { return new Promise((resolve, reject) => { var request = { receiverID: options.receiverID || DEFAULT.adminID, @@ -650,7 +650,7 @@ */ //tag data in supernode cloud (subAdmin access only) - floCloudAPI.tagApplicationData = function(vectorClock, tag, options = {}) { + floCloudAPI.tagApplicationData = function (vectorClock, tag, options = {}) { return new Promise((resolve, reject) => { if (!floGlobals.subAdmins.includes(user.id)) return reject("Only subAdmins can tag data") @@ -671,7 +671,7 @@ } //note data in supernode cloud (receiver only or subAdmin allowed if receiver is adminID) - floCloudAPI.noteApplicationData = function(vectorClock, note, options = {}) { + floCloudAPI.noteApplicationData = function (vectorClock, note, options = {}) { return new Promise((resolve, reject) => { var request = { receiverID: options.receiverID || DEFAULT.adminID, @@ -690,7 +690,7 @@ } //send general data - floCloudAPI.sendGeneralData = function(message, type, options = {}) { + floCloudAPI.sendGeneralData = function (message, type, options = {}) { return new Promise((resolve, reject) => { if (options.encrypt) { let encryptionKey = options.encrypt === true ? @@ -704,7 +704,7 @@ } //request general data - floCloudAPI.requestGeneralData = function(type, options = {}) { + floCloudAPI.requestGeneralData = function (type, options = {}) { return new Promise((resolve, reject) => { var fk = filterKey(type, options) lastVC[fk] = parseInt(lastVC[fk]) || 0; @@ -728,7 +728,7 @@ } //request an object data from supernode cloud - floCloudAPI.requestObjectData = function(objectName, options = {}) { + floCloudAPI.requestObjectData = function (objectName, options = {}) { return new Promise((resolve, reject) => { options.lowerVectorClock = options.lowerVectorClock || lastVC[objectName] + 1; options.senderID = [false, null].includes(options.senderID) ? null : @@ -765,7 +765,7 @@ }) } - floCloudAPI.closeRequest = function(requestID) { + floCloudAPI.closeRequest = function (requestID) { return new Promise((resolve, reject) => { let conn = _liveRequest[requestID] if (!conn) @@ -779,7 +779,7 @@ } //reset or initialize an object and send it to cloud - floCloudAPI.resetObjectData = function(objectName, options = {}) { + floCloudAPI.resetObjectData = function (objectName, options = {}) { return new Promise((resolve, reject) => { let message = { reset: appObjects[objectName] @@ -793,7 +793,7 @@ } //update the diff and send it to cloud - floCloudAPI.updateObjectData = function(objectName, options = {}) { + floCloudAPI.updateObjectData = function (objectName, options = {}) { return new Promise((resolve, reject) => { let message = { diff: diff.find(lastCommit.get(objectName), appObjects[ @@ -812,7 +812,7 @@ findDiff(original, updatedObj) returns an object with the added, deleted and updated differences mergeDiff(original, allDiff) returns a new object from original object merged with all differences (allDiff is returned object of findDiff) */ - var diff = (function() { + var diff = (function () { const isDate = d => d instanceof Date; const isEmpty = o => Object.keys(o).length === 0; const isObject = o => o != null && typeof o === 'object'; @@ -986,23 +986,23 @@ }, {}); }; - const mergeRecursive = (obj1, obj2) => { + const mergeRecursive = (obj1, obj2, deleteMode = false) => { for (var p in obj2) { try { if (obj2[p].constructor == Object) - obj1[p] = mergeRecursive(obj1[p], obj2[p]); + obj1[p] = mergeRecursive(obj1[p], obj2[p], deleteMode); // Property in destination object set; update its value. - else if (Ext.isArray(obj2[p])) { + else if (Array.isArray(obj2[p])) { // obj1[p] = []; if (obj2[p].length < 1) obj1[p] = obj2[p]; else - obj1[p] = mergeRecursive(obj1[p], obj2[p]); + obj1[p] = mergeRecursive(obj1[p], obj2[p], deleteMode); } else - obj1[p] = obj2[p]; + obj1[p] = deleteMode && obj2[p] === null ? undefined : obj2[p]; } catch (e) { // Property in destination object not set; create it and set its value. - obj1[p] = obj2[p]; + obj1[p] = deleteMode && obj2[p] === null ? undefined : obj2[p]; } } return obj1; @@ -1011,23 +1011,17 @@ const cleanse = (obj) => { Object.keys(obj).forEach(key => { var value = obj[key]; - if (typeof value === "object" && value !== null) { - // Recurse... - cleanse(value); - // ...and remove if now "empty" (NOTE: insert your definition of "empty" here) - //if (!Object.keys(value).length) - // delete obj[key]; - } else if (value === null) - delete obj[key]; // null, remove it + if (typeof value === "object" && value !== null) + obj[key] = cleanse(value); + else if (typeof value === 'undefined') + delete obj[key]; // undefined, remove it }); - if (obj.constructor.toString().indexOf("Array") != -1) { - obj = obj.filter(function(el) { - return el != null; - }); - } + if (Array.isArray(obj)) + obj = obj.filter(v => typeof v !== 'undefined'); return obj; } + const findDiff = (lhs, rhs) => ({ added: addedDiff(lhs, rhs), deleted: deletedDiff(lhs, rhs), @@ -1039,7 +1033,7 @@ if (Object.keys(diff.updated).length !== 0) obj = mergeRecursive(obj, diff.updated) if (Object.keys(diff.deleted).length !== 0) { - obj = mergeRecursive(obj, diff.deleted) + obj = mergeRecursive(obj, diff.deleted, true) obj = cleanse(obj) } if (Object.keys(diff.added).length !== 0) From 006ff9f0a95bc268defcb30c91bf4588e59aacd7 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 18 Nov 2022 17:49:03 +0530 Subject: [PATCH 230/289] btcOperator v1.0.13b: Fee from receiver - Added: fee_from_receiver option to create transaction. - change_address and fee_from_receiver are passed as options for createTx, createSignedTx, sendTx and createMultiSigTx - Fixed: getTx not rejecting properly when txid is invalid --- btcOperator.js | 74 +++++++++++++++++++++++++++++++------------------- 1 file changed, 46 insertions(+), 28 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index bb0b7ca..85ae761 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //btcOperator v1.0.12 +(function (EXPORTS) { //btcOperator v1.0.13b /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -307,8 +307,8 @@ parameters.receivers.forEach(id => !validateAddress(id) ? invalids.push(id) : null); if (invalids.length) throw "Invalid receivers:" + invalids; - if (parameters.change_addr && !validateAddress(parameters.change_addr)) - throw "Invalid change_address:" + parameters.change_addr; + if (parameters.change_address && !validateAddress(parameters.change_address)) + throw "Invalid change_address:" + parameters.change_address; //fee and amounts if ((typeof parameters.fee !== "number" || parameters.fee <= 0) && parameters.fee !== null) //fee = null (auto calc) throw "Invalid fee:" + parameters.fee; @@ -323,18 +323,32 @@ return parameters; } - function createTransaction(senders, redeemScripts, receivers, amounts, fee, change_addr) { + function createTransaction(senders, redeemScripts, receivers, amounts, fee, change_address, fee_from_receiver) { return new Promise((resolve, reject) => { let total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8)); const tx = coinjs.transaction(); - let output_size = addOutputs(tx, receivers, amounts, change_addr); - addInputs(tx, senders, redeemScripts, total_amount, fee, output_size).then(result => { - if (result.change_amount > 0) + let output_size = addOutputs(tx, receivers, amounts, change_address); + addInputs(tx, senders, redeemScripts, total_amount, fee, output_size, fee_from_receiver).then(result => { + if (result.change_amount > 0) //add change amount if any tx.outs[tx.outs.length - 1].value = parseInt(result.change_amount * SATOSHI_IN_BTC); //values are in satoshi - else - tx.outs.pop(); //remove the change output if no change_amount + if (fee_from_receiver) { //deduce fee from receivers if fee_from_receiver + let fee_remaining = parseInt(result.fee * SATOSHI_IN_BTC); + for (let i = 0; i < tx.outs.length - 1 && fee_remaining > 0; i++) { + if (fee_remaining < tx.outs[i].value) { + tx.outs[i].value -= fee_remaining; + fee_remaining = 0; + } else { + fee_remaining -= tx.outs[i].value; + tx.outs[i].value = 0; + } + } + if (fee_remaining > 0) + return reject("Send amount is less than fee"); + + } + tx.outs = tx.outs.filter(o => o.value !== 0); //remove all output with value 0 result.output_size = output_size; - result.output_amount = total_amount; + result.output_amount = total_amount - (fee_from_receiver ? result.fee : 0); result.total_size = BASE_TX_SIZE + output_size + result.input_size; result.transaction = tx; resolve(result); @@ -342,10 +356,10 @@ }) } - function addInputs(tx, senders, redeemScripts, total_amount, fee, output_size) { + function addInputs(tx, senders, redeemScripts, total_amount, fee, output_size, fee_from_receiver) { return new Promise((resolve, reject) => { if (fee !== null) { - addUTXOs(tx, senders, redeemScripts, total_amount + fee, false).then(result => { + addUTXOs(tx, senders, redeemScripts, fee_from_receiver ? total_amount : total_amount + fee, false).then(result => { result.fee = fee; resolve(result); }).catch(error => reject(error)) @@ -353,7 +367,10 @@ get_fee_rate().then(fee_rate => { let net_fee = BASE_TX_SIZE * fee_rate; net_fee += (output_size * fee_rate); - addUTXOs(tx, senders, redeemScripts, total_amount + net_fee, fee_rate).then(result => { + (fee_from_receiver ? + addUTXOs(tx, senders, redeemScripts, total_amount, false) : + addUTXOs(tx, senders, redeemScripts, total_amount + net_fee, fee_rate) + ).then(result => { result.fee = parseFloat((net_fee + (result.input_size * fee_rate)).toFixed(8)); result.fee_rate = fee_rate; resolve(result); @@ -416,14 +433,14 @@ }) } - function addOutputs(tx, receivers, amounts, change_addr) { + function addOutputs(tx, receivers, amounts, change_address) { let size = 0; for (let i in receivers) { tx.addoutput(receivers[i], amounts[i]); size += _sizePerOutput(receivers[i]); } - tx.addoutput(change_addr, 0); - size += _sizePerOutput(change_addr); + tx.addoutput(change_address, 0); + size += _sizePerOutput(change_address); return size; } @@ -464,9 +481,9 @@ } */ - btcOperator.sendTx = function (senders, privkeys, receivers, amounts, fee, change_addr = null) { + btcOperator.sendTx = function (senders, privkeys, receivers, amounts, fee = null, options = {}) { return new Promise((resolve, reject) => { - createSignedTx(senders, privkeys, receivers, amounts, fee, change_addr).then(result => { + createSignedTx(senders, privkeys, receivers, amounts, fee, options).then(result => { debugger; broadcastTx(result.transaction.serialize()) .then(txid => resolve(txid)) @@ -475,7 +492,7 @@ }) } - const createSignedTx = btcOperator.createSignedTx = function (senders, privkeys, receivers, amounts, fee = null, change_addr = null) { + const createSignedTx = btcOperator.createSignedTx = function (senders, privkeys, receivers, amounts, fee = null, options = {}) { return new Promise((resolve, reject) => { try { ({ @@ -489,7 +506,7 @@ receivers, amounts, fee, - change_addr + change_address: options.change_address })); } catch (e) { return reject(e) @@ -504,7 +521,7 @@ if (redeemScripts.includes(null)) //TODO: segwit return reject("Unable to get redeem-script"); //create transaction - createTransaction(senders, redeemScripts, receivers, amounts, fee, change_addr || senders[0]).then(result => { + createTransaction(senders, redeemScripts, receivers, amounts, fee, options.change_address || senders[0], options.fee_from_receiver).then(result => { let tx = result.transaction; console.debug("Unsigned:", tx.serialize()); new Set(wif_keys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/))); //Sign the tx using private key WIF @@ -514,7 +531,7 @@ }) } - btcOperator.createTx = function (senders, receivers, amounts, fee = null, change_addr = null) { + btcOperator.createTx = function (senders, receivers, amounts, fee = null, options = {}) { return new Promise((resolve, reject) => { try { ({ @@ -526,7 +543,7 @@ receivers, amounts, fee, - change_addr + change_address: options.change_address })); } catch (e) { return reject(e) @@ -535,7 +552,7 @@ if (redeemScripts.includes(null)) //TODO: segwit return reject("Unable to get redeem-script"); //create transaction - createTransaction(senders, redeemScripts, receivers, amounts, fee, change_addr || senders[0]).then(result => { + createTransaction(senders, redeemScripts, receivers, amounts, fee, options.change_address || senders[0], options.fee_from_receiver).then(result => { result.tx_hex = result.transaction.serialize(); delete result.transaction; resolve(result); @@ -543,7 +560,7 @@ }) } - btcOperator.createMultiSigTx = function (sender, redeemScript, receivers, amounts, fee = null) { + btcOperator.createMultiSigTx = function (sender, redeemScript, receivers, amounts, fee = null, options = {}) { return new Promise((resolve, reject) => { //validate tx parameters if (validateAddress(sender) !== "multisig") @@ -561,13 +578,14 @@ } = validateTxParameters({ receivers, amounts, - fee + fee, + change_address: options.change_address })); } catch (e) { return reject(e) } //create transaction - createTransaction([sender], [redeemScript], receivers, amounts, fee, sender).then(result => { + createTransaction([sender], [redeemScript], receivers, amounts, fee, options.change_address || sender, options.fee_from_receiver).then(result => { result.tx_hex = result.transaction.serialize(); delete result.transaction; resolve(result); @@ -696,7 +714,7 @@ } btcOperator.getTx = txid => new Promise((resolve, reject) => { - fetch_api(`tx/BTC/${txid}`) + fetch_api(`get_tx/BTC/${txid}`) .then(result => resolve(result.data)) .catch(error => reject(error)) }); From b7254bc3ac5f8d4f4d544da3dc96a92f9fb6fc6c Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 20 Nov 2022 19:46:22 +0530 Subject: [PATCH 231/289] btcOperator v1.0.13c bug fix Fixed: tx outputs with 0 value (such as change amount) not removed --- btcOperator.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index 85ae761..0f2786a 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //btcOperator v1.0.13b +(function (EXPORTS) { //btcOperator v1.0.13c /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -346,7 +346,7 @@ return reject("Send amount is less than fee"); } - tx.outs = tx.outs.filter(o => o.value !== 0); //remove all output with value 0 + tx.outs = tx.outs.filter(o => o.value != 0); //remove all output with value 0 result.output_size = output_size; result.output_amount = total_amount - (fee_from_receiver ? result.fee : 0); result.total_size = BASE_TX_SIZE + output_size + result.input_size; From 7a6a02f2b6f85a46a43611874501aa83f4499c32 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 24 Nov 2022 03:25:35 +0530 Subject: [PATCH 232/289] Update lib.js - support for multisig-bech32 (p2wsh) --- lib.js | 1512 ++++++++++++++++++++++++++++++++++---------------------- 1 file changed, 910 insertions(+), 602 deletions(-) diff --git a/lib.js b/lib.js index b435194..2234db8 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function(GLOBAL) { //lib v1.3.1 +(function (GLOBAL) { //lib v1.3.2 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -6,16 +6,16 @@ */ GLOBAL.cryptocoin = (typeof floGlobals === 'undefined' ? null : floGlobals.blockchain) || 'FLO'; - const getRandomBytes = (function() { + const getRandomBytes = (function () { if (typeof require === 'function') { const crypto = require('crypto'); - return function(buf) { + return function (buf) { var bytes = crypto.randomBytes(buf.length); buf.set(bytes); return buf; } } else if (GLOBAL.crypto && GLOBAL.crypto.getRandomValues) { - return function(buf) { + return function (buf) { return GLOBAL.crypto.getRandomValues(buf); } } else @@ -23,14 +23,14 @@ })(); - GLOBAL.securedMathRandom = (function() { + GLOBAL.securedMathRandom = (function () { if (typeof require === 'function') { const crypto = require('crypto'); - return function() { + return function () { return crypto.randomBytes(4).readUInt32LE() / 0xffffffff; } } else if (GLOBAL.crypto && GLOBAL.crypto.getRandomValues) { - return function() { + return function () { return (GLOBAL.crypto.getRandomValues(new Uint32Array(1))[0] / 0xffffffff); } } else @@ -38,7 +38,7 @@ })(); //Crypto.js - (function() { + (function () { // Global Crypto object var Crypto = GLOBAL.Crypto = {}; /*! @@ -47,7 +47,7 @@ * Copyright (c) 2009-2013, Jeff Mott. All rights reserved. * http://code.google.com/p/crypto-js/wiki/License */ - (function() { + (function () { var base64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; @@ -55,17 +55,17 @@ var util = Crypto.util = { // Bit-wise rotate left - rotl: function(n, b) { + rotl: function (n, b) { return (n << b) | (n >>> (32 - b)); }, // Bit-wise rotate right - rotr: function(n, b) { + rotr: function (n, b) { return (n << (32 - b)) | (n >>> b); }, // Swap big-endian to little-endian and vice versa - endian: function(n) { + endian: function (n) { // If number given, swap endian if (n.constructor == Number) { @@ -81,28 +81,28 @@ }, // Generate an array of any length of random bytes - randomBytes: function(n) { + randomBytes: function (n) { for (var bytes = []; n > 0; n--) bytes.push(Math.floor(securedMathRandom() * 256)); return bytes; }, // Convert a byte array to big-endian 32-bit words - bytesToWords: function(bytes) { + bytesToWords: function (bytes) { for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) words[b >>> 5] |= (bytes[i] & 0xFF) << (24 - b % 32); return words; }, // Convert big-endian 32-bit words to a byte array - wordsToBytes: function(words) { + wordsToBytes: function (words) { for (var bytes = [], b = 0; b < words.length * 32; b += 8) bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); return bytes; }, // Convert a byte array to a hex string - bytesToHex: function(bytes) { + bytesToHex: function (bytes) { for (var hex = [], i = 0; i < bytes.length; i++) { hex.push((bytes[i] >>> 4).toString(16)); hex.push((bytes[i] & 0xF).toString(16)); @@ -111,14 +111,14 @@ }, // Convert a hex string to a byte array - hexToBytes: function(hex) { + hexToBytes: function (hex) { for (var bytes = [], c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16)); return bytes; }, // Convert a byte array to a base-64 string - bytesToBase64: function(bytes) { + bytesToBase64: function (bytes) { for (var base64 = [], i = 0; i < bytes.length; i += 3) { var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; for (var j = 0; j < 4; j++) { @@ -132,7 +132,7 @@ }, // Convert a base-64 string to a byte array - base64ToBytes: function(base64) { + base64ToBytes: function (base64) { // Remove non-base-64 characters base64 = base64.replace(/[^A-Z0-9+\/]/ig, ""); @@ -154,12 +154,12 @@ var UTF8 = charenc.UTF8 = { // Convert a string to a byte array - stringToBytes: function(str) { + stringToBytes: function (str) { return Binary.stringToBytes(unescape(encodeURIComponent(str))); }, // Convert a byte array to a string - bytesToString: function(bytes) { + bytesToString: function (bytes) { return decodeURIComponent(escape(Binary.bytesToString(bytes))); } @@ -169,14 +169,14 @@ var Binary = charenc.Binary = { // Convert a string to a byte array - stringToBytes: function(str) { + stringToBytes: function (str) { for (var bytes = [], i = 0; i < str.length; i++) bytes.push(str.charCodeAt(i) & 0xFF); return bytes; }, // Convert a byte array to a string - bytesToString: function(bytes) { + bytesToString: function (bytes) { for (var str = [], i = 0; i < bytes.length; i++) str.push(String.fromCharCode(bytes[i])); return str.join(""); @@ -192,7 +192,7 @@ * (c) 2009-2012 by Jeff Mott. All rights reserved. * http://code.google.com/p/crypto-js/wiki/License */ - (function() { + (function () { // Shortcuts var C = Crypto, @@ -202,15 +202,15 @@ Binary = charenc.Binary; // Public API - var SHA1 = C.SHA1 = function(message, options) { + var SHA1 = C.SHA1 = function (message, options) { var digestbytes = util.wordsToBytes(SHA1._sha1(message)); return options && options.asBytes ? digestbytes : options && options.asString ? Binary.bytesToString(digestbytes) : - util.bytesToHex(digestbytes); + util.bytesToHex(digestbytes); }; // The core - SHA1._sha1 = function(message) { + SHA1._sha1 = function (message) { // Convert to byte array if (message.constructor == String) message = UTF8.stringToBytes(message); @@ -247,9 +247,9 @@ var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + ( j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 : - j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 : - j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 : - (H1 ^ H2 ^ H3) - 899497514); + j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 : + j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 : + (H1 ^ H2 ^ H3) - 899497514); H4 = H3; H3 = H2; @@ -285,7 +285,7 @@ * (c) 2009-2012 by Jeff Mott. All rights reserved. * http://code.google.com/p/crypto-js/wiki/License */ - (function() { + (function () { // Shortcuts var C = Crypto, @@ -294,7 +294,7 @@ UTF8 = charenc.UTF8, Binary = charenc.Binary; - C.HMAC = function(hasher, message, key, options) { + C.HMAC = function (hasher, message, key, options) { // Convert to byte arrays if (message.constructor == String) message = UTF8.stringToBytes(message); @@ -323,7 +323,7 @@ return options && options.asBytes ? hmacbytes : options && options.asString ? Binary.bytesToString(hmacbytes) : - util.bytesToHex(hmacbytes); + util.bytesToHex(hmacbytes); }; @@ -337,7 +337,7 @@ * (c) 2009-2012 by Jeff Mott. All rights reserved. * http://code.google.com/p/crypto-js/wiki/License */ - (function() { + (function () { var d = Crypto, k = d.util, g = d.charenc, @@ -353,11 +353,11 @@ 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ], - e = d.SHA256 = function(b, c) { + e = d.SHA256 = function (b, c) { var f = k.wordsToBytes(e._sha256(b)); return c && c.asBytes ? f : c && c.asString ? a.bytesToString(f) : k.bytesToHex(f) }; - e._sha256 = function(a) { + e._sha256 = function (a) { a.constructor == String && (a = b.stringToBytes(a)); var e = k.bytesToWords(a), f = a.length * 8, @@ -380,7 +380,7 @@ for (h = 0; h < 64; h++) { h < 16 ? d[h] = e[h + t] : (l = d[h - 15], j = d[h - 2], d[h] = ((l << 25 | l >>> 7) ^ (l << 14 | l >>> 18) ^ l >>> 3) + (d[h - 7] >>> 0) + ((j << 15 | j >>> 17) ^ - (j << 13 | j >>> 19) ^ j >>> 10) + (d[h - 16] >>> 0)); + (j << 13 | j >>> 19) ^ j >>> 10) + (d[h - 16] >>> 0)); j = f & g ^ f & m ^ g & m; var u = (f << 30 | f >>> 2) ^ (f << 19 | f >>> 13) ^ (f << 10 | f >>> 22); l = (s >>> 0) + ((i << 26 | i >>> 6) ^ (i << 21 | i >>> 11) ^ (i << 7 | i >>> 25)) + @@ -409,13 +409,13 @@ e._blocksize = 16; e._digestsize = 32 })(); - (function() { + (function () { var d = Crypto, k = d.util, g = d.charenc, b = g.UTF8, a = g.Binary; - d.HMAC = function(c, e, d, g) { + d.HMAC = function (c, e, d, g) { e.constructor == String && (e = b.stringToBytes(e)); d.constructor == String && (d = b.stringToBytes(d)); d.length > c._blocksize * 4 && (d = c(d, { @@ -434,7 +434,7 @@ })(); //SecureRandom.js - (function() { + (function () { /*! @@ -449,7 +449,7 @@ */ // Constructor function of Global SecureRandom object - var sr = GLOBAL.SecureRandom = function() {}; + var sr = GLOBAL.SecureRandom = function () { }; // Properties sr.state; @@ -465,7 +465,7 @@ // public method // ba: byte array - sr.prototype.nextBytes = function(ba) { + sr.prototype.nextBytes = function (ba) { var i; if (getRandomBytes && GLOBAL.Uint8Array) { try { @@ -486,11 +486,11 @@ // Mix in the current time (w/milliseconds) into the pool // NOTE: this method should be called from body click/keypress event handlers to increase entropy - sr.seedTime = function() { + sr.seedTime = function () { sr.seedInt(new Date().getTime()); } - sr.getByte = function() { + sr.getByte = function () { if (sr.state == null) { sr.seedTime(); sr.state = sr.ArcFour(); // Plug in your RNG constructor here @@ -505,7 +505,7 @@ } // Mix in a 32-bit integer into the pool - sr.seedInt = function(x) { + sr.seedInt = function (x) { sr.seedInt8(x); sr.seedInt8((x >> 8)); sr.seedInt8((x >> 16)); @@ -513,19 +513,19 @@ } // Mix in a 16-bit integer into the pool - sr.seedInt16 = function(x) { + sr.seedInt16 = function (x) { sr.seedInt8(x); sr.seedInt8((x >> 8)); } // Mix in a 8-bit integer into the pool - sr.seedInt8 = function(x) { + sr.seedInt8 = function (x) { sr.pool[sr.pptr++] ^= x & 255; if (sr.pptr >= sr.poolSize) sr.pptr -= sr.poolSize; } // Arcfour is a PRNG - sr.ArcFour = function() { + sr.ArcFour = function () { function Arcfour() { this.i = 0; this.j = 0; @@ -610,7 +610,7 @@ } entropyStr += pluginsStr + mimeTypesStr; // cookies and storage: 1 bit - entropyStr += navigator.cookieEnabled + typeof(sessionStorage) + typeof(localStorage); + entropyStr += navigator.cookieEnabled + typeof (sessionStorage) + typeof (localStorage); // language: ~7 bit entropyStr += navigator.language; // history: ~2 bit @@ -628,7 +628,7 @@ })(); //ripemd160.js - (function() { + (function () { /* CryptoJS v3.1.2 @@ -677,7 +677,7 @@ var hl = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]; var hr = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]; - var bytesToWords = function(bytes) { + var bytesToWords = function (bytes) { var words = []; for (var i = 0, b = 0; i < bytes.length; i++, b += 8) { words[b >>> 5] |= bytes[i] << (24 - b % 32); @@ -685,7 +685,7 @@ return words; }; - var wordsToBytes = function(words) { + var wordsToBytes = function (words) { var bytes = []; for (var b = 0; b < words.length * 32; b += 8) { bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); @@ -693,7 +693,7 @@ return bytes; }; - var processBlock = function(H, M, offset) { + var processBlock = function (H, M, offset) { // Swap endian for (var i = 0; i < 16; i++) { @@ -829,7 +829,7 @@ })(); //BigInteger.js - (function() { + (function () { // Upstream 'BigInteger' here: // Original Author: http://www-cs-students.stanford.edu/~tjw/jsbn/ // Follows 'jsbn' on Github: https://github.com/jasondavies/jsbn @@ -854,7 +854,7 @@ if (a != null) if ("number" == typeof a) this.fromNumber(a, b, c); else if (b == null && "string" != typeof a) this.fromString(a, 256); - else this.fromString(a, b); + else this.fromString(a, b); }; // Bits per digit @@ -1000,7 +1000,7 @@ // (protected) copy this to r - BigInteger.prototype.copyTo = function(r) { + BigInteger.prototype.copyTo = function (r) { for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; @@ -1008,7 +1008,7 @@ // (protected) set from integer value x, -DV <= x < DV - BigInteger.prototype.fromInt = function(x) { + BigInteger.prototype.fromInt = function (x) { this.t = 1; this.s = (x < 0) ? -1 : 0; if (x > 0) this[0] = x; @@ -1017,7 +1017,7 @@ }; // (protected) set from string and radix - BigInteger.prototype.fromString = function(s, b) { + BigInteger.prototype.fromString = function (s, b) { var k; if (b == 16) k = 4; else if (b == 8) k = 3; @@ -1061,13 +1061,13 @@ // (protected) clamp off excess high words - BigInteger.prototype.clamp = function() { + BigInteger.prototype.clamp = function () { var c = this.s & this.DM; while (this.t > 0 && this[this.t - 1] == c) --this.t; }; // (protected) r = this << n*DB - BigInteger.prototype.dlShiftTo = function(n, r) { + BigInteger.prototype.dlShiftTo = function (n, r) { var i; for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; for (i = n - 1; i >= 0; --i) r[i] = 0; @@ -1076,7 +1076,7 @@ }; // (protected) r = this >> n*DB - BigInteger.prototype.drShiftTo = function(n, r) { + BigInteger.prototype.drShiftTo = function (n, r) { for (var i = n; i < this.t; ++i) r[i - n] = this[i]; r.t = Math.max(this.t - n, 0); r.s = this.s; @@ -1084,7 +1084,7 @@ // (protected) r = this << n - BigInteger.prototype.lShiftTo = function(n, r) { + BigInteger.prototype.lShiftTo = function (n, r) { var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << cbs) - 1; @@ -1104,7 +1104,7 @@ // (protected) r = this >> n - BigInteger.prototype.rShiftTo = function(n, r) { + BigInteger.prototype.rShiftTo = function (n, r) { r.s = this.s; var ds = Math.floor(n / this.DB); if (ds >= this.t) { @@ -1126,7 +1126,7 @@ // (protected) r = this - a - BigInteger.prototype.subTo = function(a, r) { + BigInteger.prototype.subTo = function (a, r) { var i = 0, c = 0, m = Math.min(a.t, this.t); @@ -1162,7 +1162,7 @@ // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. - BigInteger.prototype.multiplyTo = function(a, r) { + BigInteger.prototype.multiplyTo = function (a, r) { var x = this.abs(), y = a.abs(); var i = x.t; @@ -1176,7 +1176,7 @@ // (protected) r = this^2, r != this (HAC 14.16) - BigInteger.prototype.squareTo = function(r) { + BigInteger.prototype.squareTo = function (r) { var x = this.abs(); var i = r.t = 2 * x.t; while (--i >= 0) r[i] = 0; @@ -1196,7 +1196,7 @@ // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. - BigInteger.prototype.divRemTo = function(m, q, r) { + BigInteger.prototype.divRemTo = function (m, q, r) { var pm = m.abs(); if (pm.t <= 0) return; var pt = this.abs(); @@ -1265,7 +1265,7 @@ // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. - BigInteger.prototype.invDigit = function() { + BigInteger.prototype.invDigit = function () { if (this.t < 1) return 0; var x = this[0]; if ((x & 1) == 0) return 0; @@ -1282,13 +1282,13 @@ // (protected) true iff this is even - BigInteger.prototype.isEven = function() { + BigInteger.prototype.isEven = function () { return ((this.t > 0) ? (this[0] & 1) : this.s) == 0; }; // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) - BigInteger.prototype.exp = function(e, z) { + BigInteger.prototype.exp = function (e, z) { if (e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), @@ -1309,7 +1309,7 @@ // (public) return string representation in given radix - BigInteger.prototype.toString = function(b) { + BigInteger.prototype.toString = function (b) { if (this.s < 0) return "-" + this.negate().toString(b); var k; if (b == 16) k = 4; @@ -1348,19 +1348,19 @@ // (public) -this - BigInteger.prototype.negate = function() { + BigInteger.prototype.negate = function () { var r = nbi(); BigInteger.ZERO.subTo(this, r); return r; }; // (public) |this| - BigInteger.prototype.abs = function() { + BigInteger.prototype.abs = function () { return (this.s < 0) ? this.negate() : this; }; // (public) return + if this > a, - if this < a, 0 if equal - BigInteger.prototype.compareTo = function(a) { + BigInteger.prototype.compareTo = function (a) { var r = this.s - a.s; if (r != 0) return r; var i = this.t; @@ -1372,13 +1372,13 @@ } // (public) return the number of bits in "this" - BigInteger.prototype.bitLength = function() { + BigInteger.prototype.bitLength = function () { if (this.t <= 0) return 0; return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); }; // (public) this mod a - BigInteger.prototype.mod = function(a) { + BigInteger.prototype.mod = function (a) { var r = nbi(); this.abs().divRemTo(a, null, r); if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); @@ -1386,7 +1386,7 @@ } // (public) this^e % m, 0 <= e < 2^32 - BigInteger.prototype.modPowInt = function(e, m) { + BigInteger.prototype.modPowInt = function (e, m) { var z; if (e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); @@ -1468,12 +1468,12 @@ // (protected) return x s.t. r^x < DV - BigInteger.prototype.chunkSize = function(r) { + BigInteger.prototype.chunkSize = function (r) { return Math.floor(Math.LN2 * this.DB / Math.log(r)); }; // (protected) convert to radix string - BigInteger.prototype.toRadix = function(b) { + BigInteger.prototype.toRadix = function (b) { if (b == null) b = 10; if (this.signum() == 0 || b < 2 || b > 36) return "0"; var cs = this.chunkSize(b); @@ -1491,7 +1491,7 @@ }; // (protected) convert from radix string - BigInteger.prototype.fromRadix = function(s, b) { + BigInteger.prototype.fromRadix = function (s, b) { this.fromInt(0); if (b == null) b = 10; var cs = this.chunkSize(b); @@ -1521,7 +1521,7 @@ }; // (protected) alternate constructor - BigInteger.prototype.fromNumber = function(a, b, c) { + BigInteger.prototype.fromNumber = function (a, b, c) { if ("number" == typeof b) { // new BigInteger(int,int,RNG) if (a < 2) this.fromInt(1); @@ -1548,7 +1548,7 @@ }; // (protected) r = this op a (bitwise) - BigInteger.prototype.bitwiseTo = function(a, op, r) { + BigInteger.prototype.bitwiseTo = function (a, op, r) { var i, f, m = Math.min(a.t, this.t); for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); if (a.t < this.t) { @@ -1565,14 +1565,14 @@ }; // (protected) this op (1<= 0, 1 < n < DV - BigInteger.prototype.dMultiply = function(n) { + BigInteger.prototype.dMultiply = function (n) { this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); ++this.t; this.clamp(); }; // (protected) this += n << w words, this >= 0 - BigInteger.prototype.dAddOffset = function(n, w) { + BigInteger.prototype.dAddOffset = function (n, w) { if (n == 0) return; while (this.t <= w) this[this.t++] = 0; this[w] += n; @@ -1626,7 +1626,7 @@ // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. - BigInteger.prototype.multiplyLowerTo = function(a, n, r) { + BigInteger.prototype.multiplyLowerTo = function (a, n, r) { var i = Math.min(this.t + a.t, n); r.s = 0; // assumes a,this >= 0 r.t = i; @@ -1640,7 +1640,7 @@ // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. - BigInteger.prototype.multiplyUpperTo = function(a, n, r) { + BigInteger.prototype.multiplyUpperTo = function (a, n, r) { --n; var i = r.t = this.t + a.t - n; r.s = 0; // assumes a,this >= 0 @@ -1652,7 +1652,7 @@ }; // (protected) this % n, n < 2^26 - BigInteger.prototype.modInt = function(n) { + BigInteger.prototype.modInt = function (n) { if (n <= 0) return 0; var d = this.DV % n, r = (this.s < 0) ? n - 1 : 0; @@ -1665,7 +1665,7 @@ // (protected) true if probably prime (HAC 4.24, Miller-Rabin) - BigInteger.prototype.millerRabin = function(t) { + BigInteger.prototype.millerRabin = function (t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if (k <= 0) return false; @@ -1692,14 +1692,14 @@ // (public) - BigInteger.prototype.clone = function() { + BigInteger.prototype.clone = function () { var r = nbi(); this.copyTo(r); return r; }; // (public) return value as integer - BigInteger.prototype.intValue = function() { + BigInteger.prototype.intValue = function () { if (this.s < 0) { if (this.t == 1) return this[0] - this.DV; else if (this.t == 0) return -1; @@ -1711,17 +1711,17 @@ // (public) return value as byte - BigInteger.prototype.byteValue = function() { + BigInteger.prototype.byteValue = function () { return (this.t == 0) ? this.s : (this[0] << 24) >> 24; }; // (public) return value as short (assumes DB>=16) - BigInteger.prototype.shortValue = function() { + BigInteger.prototype.shortValue = function () { return (this.t == 0) ? this.s : (this[0] << 16) >> 16; }; // (public) 0 if this == 0, 1 if this > 0 - BigInteger.prototype.signum = function() { + BigInteger.prototype.signum = function () { if (this.s < 0) return -1; else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; else return 1; @@ -1729,7 +1729,7 @@ // (public) convert to bigendian byte array - BigInteger.prototype.toByteArray = function() { + BigInteger.prototype.toByteArray = function () { var i = this.t, r = new Array(); r[0] = this.s; @@ -1757,13 +1757,13 @@ return r; }; - BigInteger.prototype.equals = function(a) { + BigInteger.prototype.equals = function (a) { return (this.compareTo(a) == 0); }; - BigInteger.prototype.min = function(a) { + BigInteger.prototype.min = function (a) { return (this.compareTo(a) < 0) ? this : a; }; - BigInteger.prototype.max = function(a) { + BigInteger.prototype.max = function (a) { return (this.compareTo(a) > 0) ? this : a; }; @@ -1771,7 +1771,7 @@ function op_and(x, y) { return x & y; } - BigInteger.prototype.and = function(a) { + BigInteger.prototype.and = function (a) { var r = nbi(); this.bitwiseTo(a, op_and, r); return r; @@ -1781,7 +1781,7 @@ function op_or(x, y) { return x | y; } - BigInteger.prototype.or = function(a) { + BigInteger.prototype.or = function (a) { var r = nbi(); this.bitwiseTo(a, op_or, r); return r; @@ -1791,7 +1791,7 @@ function op_xor(x, y) { return x ^ y; } - BigInteger.prototype.xor = function(a) { + BigInteger.prototype.xor = function (a) { var r = nbi(); this.bitwiseTo(a, op_xor, r); return r; @@ -1801,14 +1801,14 @@ function op_andnot(x, y) { return x & ~y; } - BigInteger.prototype.andNot = function(a) { + BigInteger.prototype.andNot = function (a) { var r = nbi(); this.bitwiseTo(a, op_andnot, r); return r; }; // (public) ~this - BigInteger.prototype.not = function() { + BigInteger.prototype.not = function () { var r = nbi(); for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; r.t = this.t; @@ -1817,7 +1817,7 @@ }; // (public) this << n - BigInteger.prototype.shiftLeft = function(n) { + BigInteger.prototype.shiftLeft = function (n) { var r = nbi(); if (n < 0) this.rShiftTo(-n, r); else this.lShiftTo(n, r); @@ -1825,7 +1825,7 @@ }; // (public) this >> n - BigInteger.prototype.shiftRight = function(n) { + BigInteger.prototype.shiftRight = function (n) { var r = nbi(); if (n < 0) this.lShiftTo(-n, r); else this.rShiftTo(n, r); @@ -1833,7 +1833,7 @@ }; // (public) returns index of lowest 1-bit (or -1 if none) - BigInteger.prototype.getLowestSetBit = function() { + BigInteger.prototype.getLowestSetBit = function () { for (var i = 0; i < this.t; ++i) if (this[i] != 0) return i * this.DB + lbit(this[i]); if (this.s < 0) return this.t * this.DB; @@ -1841,7 +1841,7 @@ }; // (public) return number of set bits - BigInteger.prototype.bitCount = function() { + BigInteger.prototype.bitCount = function () { var r = 0, x = this.s & this.DM; for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); @@ -1849,56 +1849,56 @@ }; // (public) true iff nth bit is set - BigInteger.prototype.testBit = function(n) { + BigInteger.prototype.testBit = function (n) { var j = Math.floor(n / this.DB); if (j >= this.t) return (this.s != 0); return ((this[j] & (1 << (n % this.DB))) != 0); }; // (public) this | (1<= 1-.5^t - BigInteger.prototype.isProbablePrime = function(t) { + BigInteger.prototype.isProbablePrime = function (t) { var i, x = this.abs(); if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { for (i = 0; i < lowprimes.length; ++i) @@ -2105,7 +2105,7 @@ // JSBN-specific extension // (public) this^2 - BigInteger.prototype.square = function() { + BigInteger.prototype.square = function () { var r = nbi(); this.squareTo(r); return r; @@ -2133,13 +2133,13 @@ * This returns the absolute of the contained value in big endian * form. A value of zero results in an empty array. */ - BigInteger.prototype.toByteArrayUnsigned = function() { + BigInteger.prototype.toByteArrayUnsigned = function () { var ba = this.abs().toByteArray(); if (ba.length) { if (ba[0] == 0) { ba = ba.slice(1); } - return ba.map(function(v) { + return ba.map(function (v) { return (v < 0) ? v + 256 : v; }); } else { @@ -2154,7 +2154,7 @@ * This function will interpret a byte array as a big integer in big * endian notation and ignore leading zeros. */ - BigInteger.fromByteArrayUnsigned = function(ba) { + BigInteger.fromByteArrayUnsigned = function (ba) { if (!ba.length) { return ba.valueOf(0); } else if (ba[0] & 0x80) { @@ -2190,7 +2190,7 @@ * 62300 => 0x00f35c * -62300 => 0x80f35c */ - BigInteger.prototype.toByteArraySigned = function() { + BigInteger.prototype.toByteArraySigned = function () { var val = this.abs().toByteArrayUnsigned(); var neg = this.compareTo(BigInteger.ZERO) < 0; @@ -2214,7 +2214,7 @@ * * For details on the format please see BigInteger.toByteArraySigned. */ - BigInteger.fromByteArraySigned = function(ba) { + BigInteger.fromByteArraySigned = function (ba) { // Check for negative value if (ba[0] & 0x80) { // Remove sign bit @@ -2236,21 +2236,21 @@ var Classic = GLOBAL.Classic = function Classic(m) { this.m = m; } - Classic.prototype.convert = function(x) { + Classic.prototype.convert = function (x) { if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; }; - Classic.prototype.revert = function(x) { + Classic.prototype.revert = function (x) { return x; }; - Classic.prototype.reduce = function(x) { + Classic.prototype.reduce = function (x) { x.divRemTo(this.m, null, x); }; - Classic.prototype.mulTo = function(x, y, r) { + Classic.prototype.mulTo = function (x, y, r) { x.multiplyTo(y, r); this.reduce(r); }; - Classic.prototype.sqrTo = function(x, r) { + Classic.prototype.sqrTo = function (x, r) { x.squareTo(r); this.reduce(r); }; @@ -2269,7 +2269,7 @@ this.mt2 = 2 * m.t; } // xR mod m - Montgomery.prototype.convert = function(x) { + Montgomery.prototype.convert = function (x) { var r = nbi(); x.abs().dlShiftTo(this.m.t, r); r.divRemTo(this.m, null, r); @@ -2277,14 +2277,14 @@ return r; } // x/R mod m - Montgomery.prototype.revert = function(x) { + Montgomery.prototype.revert = function (x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }; // x = x/R mod m (HAC 14.32) - Montgomery.prototype.reduce = function(x) { + Montgomery.prototype.reduce = function (x) { while (x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for (var i = 0; i < this.m.t; ++i) { @@ -2305,12 +2305,12 @@ if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); }; // r = "xy/R mod m"; x,y != r - Montgomery.prototype.mulTo = function(x, y, r) { + Montgomery.prototype.mulTo = function (x, y, r) { x.multiplyTo(y, r); this.reduce(r); }; // r = "x^2/R mod m"; x != r - Montgomery.prototype.sqrTo = function(x, r) { + Montgomery.prototype.sqrTo = function (x, r) { x.squareTo(r); this.reduce(r); }; @@ -2320,17 +2320,17 @@ // A "null" reducer - var NullExp = GLOBAL.NullExp = function NullExp() {} - NullExp.prototype.convert = function(x) { + var NullExp = GLOBAL.NullExp = function NullExp() { } + NullExp.prototype.convert = function (x) { return x; }; - NullExp.prototype.revert = function(x) { + NullExp.prototype.revert = function (x) { return x; }; - NullExp.prototype.mulTo = function(x, y, r) { + NullExp.prototype.mulTo = function (x, y, r) { x.multiplyTo(y, r); }; - NullExp.prototype.sqrTo = function(x, r) { + NullExp.prototype.sqrTo = function (x, r) { x.squareTo(r); }; @@ -2347,7 +2347,7 @@ this.mu = this.r2.divide(m); this.m = m; } - Barrett.prototype.convert = function(x) { + Barrett.prototype.convert = function (x) { if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); else if (x.compareTo(this.m) < 0) return x; else { @@ -2357,11 +2357,11 @@ return r; } }; - Barrett.prototype.revert = function(x) { + Barrett.prototype.revert = function (x) { return x; }; // x = x mod m (HAC 14.42) - Barrett.prototype.reduce = function(x) { + Barrett.prototype.reduce = function (x) { x.drShiftTo(this.m.t - 1, this.r2); if (x.t > this.m.t + 1) { x.t = this.m.t + 1; @@ -2374,12 +2374,12 @@ while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); }; // r = x*y mod m; x,y != r - Barrett.prototype.mulTo = function(x, y, r) { + Barrett.prototype.mulTo = function (x, y, r) { x.multiplyTo(y, r); this.reduce(r); }; // r = x^2 mod m; x != r - Barrett.prototype.sqrTo = function(x, r) { + Barrett.prototype.sqrTo = function (x, r) { x.squareTo(r); this.reduce(r); }; @@ -2395,7 +2395,7 @@ })(); //ellipticcurve.js - (function() { + (function () { /*! * Basic Javascript Elliptic Curve implementation * Ported loosely from BouncyCastle's Java EC code @@ -2405,53 +2405,53 @@ * http://www-cs-students.stanford.edu/~tjw/jsbn/LICENSE */ // Constructor function of Global EllipticCurve object - var ec = GLOBAL.EllipticCurve = function() {}; + var ec = GLOBAL.EllipticCurve = function () { }; // ---------------- // ECFieldElementFp constructor // q instanceof BigInteger // x instanceof BigInteger - ec.FieldElementFp = function(q, x) { + ec.FieldElementFp = function (q, x) { this.x = x; // TODO if(x.compareTo(q) >= 0) error this.q = q; }; - ec.FieldElementFp.prototype.equals = function(other) { + ec.FieldElementFp.prototype.equals = function (other) { if (other == this) return true; return (this.q.equals(other.q) && this.x.equals(other.x)); }; - ec.FieldElementFp.prototype.toBigInteger = function() { + ec.FieldElementFp.prototype.toBigInteger = function () { return this.x; }; - ec.FieldElementFp.prototype.negate = function() { + ec.FieldElementFp.prototype.negate = function () { return new ec.FieldElementFp(this.q, this.x.negate().mod(this.q)); }; - ec.FieldElementFp.prototype.add = function(b) { + ec.FieldElementFp.prototype.add = function (b) { return new ec.FieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); }; - ec.FieldElementFp.prototype.subtract = function(b) { + ec.FieldElementFp.prototype.subtract = function (b) { return new ec.FieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); }; - ec.FieldElementFp.prototype.multiply = function(b) { + ec.FieldElementFp.prototype.multiply = function (b) { return new ec.FieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); }; - ec.FieldElementFp.prototype.square = function() { + ec.FieldElementFp.prototype.square = function () { return new ec.FieldElementFp(this.q, this.x.square().mod(this.q)); }; - ec.FieldElementFp.prototype.divide = function(b) { + ec.FieldElementFp.prototype.divide = function (b) { return new ec.FieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod( this.q)); }; - ec.FieldElementFp.prototype.getByteLength = function() { + ec.FieldElementFp.prototype.getByteLength = function () { return Math.floor((this.toBigInteger().bitLength() + 7) / 8); }; @@ -2463,7 +2463,7 @@ * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * Ported to JavaScript by bitaddress.org */ - ec.FieldElementFp.prototype.sqrt = function() { + ec.FieldElementFp.prototype.sqrt = function () { if (!this.q.testBit(0)) throw new Error("even value of q"); // p mod 4 == 3 @@ -2491,7 +2491,7 @@ P = new BigInteger(this.q.bitLength(), rand); } while (P.compareTo(this.q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, - this.q).equals(qMinusOne))); + this.q).equals(qMinusOne))); var result = ec.FieldElementFp.fastLucasSequence(this.q, P, Q, k); @@ -2515,7 +2515,7 @@ * contribution from Simon Greatrix */ - (function(C) { + (function (C) { // Create pad namespace var C_pad = C.pad = {}; @@ -2528,7 +2528,7 @@ } // Remove padding when the final byte gives the number of padding bytes. - var _unpadLength = function(cipher, message, alg, padding) { + var _unpadLength = function (cipher, message, alg, padding) { var pad = message.pop(); if (pad == 0) { throw new Error("Invalid zero-length padding specified for " + alg + @@ -2552,8 +2552,8 @@ // No-operation padding, used for stream ciphers C_pad.NoPadding = { - pad: function(cipher, message) {}, - unpad: function(cipher, message) {} + pad: function (cipher, message) { }, + unpad: function (cipher, message) { } }; // Zero Padding. @@ -2561,7 +2561,7 @@ // If the message is not an exact number of blocks, the final block is // completed with 0x00 bytes. There is no unpadding. C_pad.ZeroPadding = { - pad: function(cipher, message) { + pad: function (cipher, message) { var blockSizeInBytes = cipher._blocksize * 4; var reqd = message.length % blockSizeInBytes; if (reqd != 0) { @@ -2571,7 +2571,7 @@ } }, - unpad: function(cipher, message) { + unpad: function (cipher, message) { while (message[message.length - 1] == 0) { message.pop(); } @@ -2583,7 +2583,7 @@ // Pads the plain text with an 0x80 byte followed by as many 0x00 // bytes are required to complete the block. C_pad.iso7816 = { - pad: function(cipher, message) { + pad: function (cipher, message) { var reqd = _requiredPadding(cipher, message); message.push(0x80); for (; reqd > 1; reqd--) { @@ -2591,7 +2591,7 @@ } }, - unpad: function(cipher, message) { + unpad: function (cipher, message) { var padLength; for (padLength = cipher._blocksize * 4; padLength > 0; padLength--) { var b = message.pop(); @@ -2612,7 +2612,7 @@ // The final block is padded with zeros except for the last byte of the // last block which contains the number of padding bytes. C_pad.ansix923 = { - pad: function(cipher, message) { + pad: function (cipher, message) { var reqd = _requiredPadding(cipher, message); for (var i = 1; i < reqd; i++) { message.push(0x00); @@ -2620,7 +2620,7 @@ message.push(reqd); }, - unpad: function(cipher, message) { + unpad: function (cipher, message) { _unpadLength(cipher, message, "ANSI X.923", 0); } }; @@ -2630,7 +2630,7 @@ // The final block is padded with random bytes except for the last // byte of the last block which contains the number of padding bytes. C_pad.iso10126 = { - pad: function(cipher, message) { + pad: function (cipher, message) { var reqd = _requiredPadding(cipher, message); for (var i = 1; i < reqd; i++) { message.push(Math.floor(securedMathRandom() * 256)); @@ -2638,7 +2638,7 @@ message.push(reqd); }, - unpad: function(cipher, message) { + unpad: function (cipher, message) { _unpadLength(cipher, message, "ISO 10126", undefined); } }; @@ -2649,14 +2649,14 @@ // value of each added byte is the number of bytes that are added, // i.e. N bytes, each of value N are added. C_pad.pkcs7 = { - pad: function(cipher, message) { + pad: function (cipher, message) { var reqd = _requiredPadding(cipher, message); for (var i = 0; i < reqd; i++) { message.push(reqd); } }, - unpad: function(cipher, message) { + unpad: function (cipher, message) { _unpadLength(cipher, message, "PKCS 7", message[message.length - 1]); } }; @@ -2667,19 +2667,19 @@ /** * Mode base "class". */ - var Mode = C_mode.Mode = function(padding) { + var Mode = C_mode.Mode = function (padding) { if (padding) { this._padding = padding; } }; Mode.prototype = { - encrypt: function(cipher, m, iv) { + encrypt: function (cipher, m, iv) { this._padding.pad(cipher, m); this._doEncrypt(cipher, m, iv); }, - decrypt: function(cipher, m, iv) { + decrypt: function (cipher, m, iv) { this._doDecrypt(cipher, m, iv); this._padding.unpad(cipher, m); }, @@ -2696,7 +2696,7 @@ * * ECB does not require an initialization vector. */ - var ECB = C_mode.ECB = function() { + var ECB = C_mode.ECB = function () { // Call parent constructor Mode.apply(this, arguments); }; @@ -2705,14 +2705,14 @@ var ECB_prototype = ECB.prototype = new Mode; // Concrete steps for Mode template - ECB_prototype._doEncrypt = function(cipher, m, iv) { + ECB_prototype._doEncrypt = function (cipher, m, iv) { var blockSizeInBytes = cipher._blocksize * 4; // Encrypt each block for (var offset = 0; offset < m.length; offset += blockSizeInBytes) { cipher._encryptblock(m, offset); } }; - ECB_prototype._doDecrypt = function(cipher, c, iv) { + ECB_prototype._doDecrypt = function (cipher, c, iv) { var blockSizeInBytes = cipher._blocksize * 4; // Decrypt each block for (var offset = 0; offset < c.length; offset += blockSizeInBytes) { @@ -2721,7 +2721,7 @@ }; // ECB never uses an IV - ECB_prototype.fixOptions = function(options) { + ECB_prototype.fixOptions = function (options) { options.iv = []; }; @@ -2732,7 +2732,7 @@ * The first block is XORed with the IV. Subsequent blocks are XOR with the * previous cipher output. */ - var CBC = C_mode.CBC = function() { + var CBC = C_mode.CBC = function () { // Call parent constructor Mode.apply(this, arguments); }; @@ -2741,7 +2741,7 @@ var CBC_prototype = CBC.prototype = new Mode; // Concrete steps for Mode template - CBC_prototype._doEncrypt = function(cipher, m, iv) { + CBC_prototype._doEncrypt = function (cipher, m, iv) { var blockSizeInBytes = cipher._blocksize * 4; // Encrypt each block @@ -2759,7 +2759,7 @@ cipher._encryptblock(m, offset); } }; - CBC_prototype._doDecrypt = function(cipher, c, iv) { + CBC_prototype._doDecrypt = function (cipher, c, iv) { var blockSizeInBytes = cipher._blocksize * 4; // At the start, the previously crypted block is the IV @@ -2789,7 +2789,7 @@ * * This is a stream cipher mode and does not require padding. */ - var CFB = C_mode.CFB = function() { + var CFB = C_mode.CFB = function () { // Call parent constructor Mode.apply(this, arguments); }; @@ -2801,7 +2801,7 @@ CFB_prototype._padding = C_pad.NoPadding; // Concrete steps for Mode template - CFB_prototype._doEncrypt = function(cipher, m, iv) { + CFB_prototype._doEncrypt = function (cipher, m, iv) { var blockSizeInBytes = cipher._blocksize * 4, keystream = iv.slice(0); @@ -2815,7 +2815,7 @@ keystream[j] = m[i]; } }; - CFB_prototype._doDecrypt = function(cipher, c, iv) { + CFB_prototype._doDecrypt = function (cipher, c, iv) { var blockSizeInBytes = cipher._blocksize * 4, keystream = iv.slice(0); @@ -2840,7 +2840,7 @@ * * This is a stream cipher mode and does not require padding. */ - var OFB = C_mode.OFB = function() { + var OFB = C_mode.OFB = function () { // Call parent constructor Mode.apply(this, arguments); }; @@ -2852,7 +2852,7 @@ OFB_prototype._padding = C_pad.NoPadding; // Concrete steps for Mode template - OFB_prototype._doEncrypt = function(cipher, m, iv) { + OFB_prototype._doEncrypt = function (cipher, m, iv) { var blockSizeInBytes = cipher._blocksize * 4, keystream = iv.slice(0); @@ -2880,7 +2880,7 @@ * * This is a stream cipher mode and does not require padding. */ - var CTR = C_mode.CTR = function() { + var CTR = C_mode.CTR = function () { // Call parent constructor Mode.apply(this, arguments); }; @@ -2891,7 +2891,7 @@ // Override padding CTR_prototype._padding = C_pad.NoPadding; - CTR_prototype._doEncrypt = function(cipher, m, iv) { + CTR_prototype._doEncrypt = function (cipher, m, iv) { var blockSizeInBytes = cipher._blocksize * 4; var counter = iv.slice(0); @@ -2930,7 +2930,7 @@ * Copyright (c) 2009-2013, Jeff Mott. All rights reserved. * http://code.google.com/p/crypto-js/wiki/License */ - (function() { + (function () { // Shortcuts var C = Crypto, @@ -2939,7 +2939,7 @@ UTF8 = charenc.UTF8, Binary = charenc.Binary; - C.PBKDF2 = function(password, salt, keylen, options) { + C.PBKDF2 = function (password, salt, keylen, options) { // Convert to byte arrays if (password.constructor == String) password = UTF8.stringToBytes(password); @@ -2975,7 +2975,7 @@ return options && options.asBytes ? derivedKeyBytes : options && options.asString ? Binary.bytesToString(derivedKeyBytes) : - util.bytesToHex(derivedKeyBytes); + util.bytesToHex(derivedKeyBytes); }; @@ -3003,7 +3003,7 @@ * THE SOFTWARE. */ // https://github.com/cheongwy/node-scrypt-js - (function() { + (function () { var MAX_VALUE = 2147483647; var workerUrl = null; @@ -3015,7 +3015,7 @@ * p = parallelization cost * */ - GLOBAL.Crypto_scrypt = function(passwd, salt, N, r, p, dkLen, callback) { + GLOBAL.Crypto_scrypt = function (passwd, salt, N, r, p, dkLen, callback) { if (N == 0 || (N & (N - 1)) != 0) throw Error("N must be > 0 and a power of 2"); if (N > MAX_VALUE / 128 / r) throw Error("Parameter N is too large"); @@ -3032,7 +3032,7 @@ try { var i = 0; var worksDone = 0; - var makeWorker = function() { + var makeWorker = function () { if (!workerUrl) { var code = '(' + scryptCore.toString() + ')()'; var blob; @@ -3051,7 +3051,7 @@ workerUrl = URL.createObjectURL(blob); } var worker = new Worker(workerUrl); - worker.onmessage = function(event) { + worker.onmessage = function (event) { var Bi = event.data[0], Bslice = event.data[1]; worksDone++; @@ -3079,7 +3079,7 @@ workers[1].postMessage([N, r, p, B, i++]); } } catch (e) { - GLOBAL.setTimeout(function() { + GLOBAL.setTimeout(function () { scryptCore(); callback(Crypto.PBKDF2(passwd, B, dkLen, PBKDF2_opts)); }, 0); @@ -3091,7 +3091,7 @@ V = []; if (typeof B === 'undefined') { - onmessage = function(event) { + onmessage = function (event) { var data = event.data; var N = data[0], r = data[1], @@ -3363,7 +3363,7 @@ * Copyright (c) 2009-2013, Jeff Mott. All rights reserved. * http://code.google.com/p/crypto-js/wiki/License */ - (function() { + (function () { // Shortcuts var C = Crypto, @@ -3442,11 +3442,11 @@ // Inner state var state = [ - [], - [], - [], - [] - ], + [], + [], + [], + [] + ], keylength, nrounds, keyschedule; @@ -3457,7 +3457,7 @@ * Public API */ - encrypt: function(message, password, options) { + encrypt: function (message, password, options) { options = options || {}; @@ -3472,8 +3472,8 @@ // Convert to bytes if message is a string m = ( message.constructor == String ? - UTF8.stringToBytes(message) : - message + UTF8.stringToBytes(message) : + message ), // Generate random IV @@ -3482,12 +3482,12 @@ // Generate key k = ( password.constructor == String ? - // Derive key from pass-phrase - C.PBKDF2(password, iv, 32, { - asBytes: true - }) : - // else, assume byte array representing cryptographic key - password + // Derive key from pass-phrase + C.PBKDF2(password, iv, 32, { + asBytes: true + }) : + // else, assume byte array representing cryptographic key + password ); // Encrypt @@ -3500,7 +3500,7 @@ }, - decrypt: function(ciphertext, password, options) { + decrypt: function (ciphertext, password, options) { options = options || {}; @@ -3515,8 +3515,8 @@ // Convert to bytes if ciphertext is a string c = ( ciphertext.constructor == String ? - util.base64ToBytes(ciphertext) : - ciphertext + util.base64ToBytes(ciphertext) : + ciphertext ), // Separate IV and message @@ -3525,12 +3525,12 @@ // Generate key k = ( password.constructor == String ? - // Derive key from pass-phrase - C.PBKDF2(password, iv, 32, { - asBytes: true - }) : - // else, assume byte array representing cryptographic key - password + // Derive key from pass-phrase + C.PBKDF2(password, iv, 32, { + asBytes: true + }) : + // else, assume byte array representing cryptographic key + password ); // Decrypt @@ -3549,7 +3549,7 @@ _blocksize: 4, - _encryptblock: function(m, offset) { + _encryptblock: function (m, offset) { // Set input for (var row = 0; row < AES._blocksize; row++) { @@ -3626,7 +3626,7 @@ }, - _decryptblock: function(c, offset) { + _decryptblock: function (c, offset) { // Set input for (var row = 0; row < AES._blocksize; row++) { @@ -3708,14 +3708,14 @@ * Private methods */ - _init: function(k) { + _init: function (k) { keylength = k.length / 4; nrounds = keylength + 6; AES._keyexpansion(k); }, // Generate a key schedule - _keyexpansion: function(k) { + _keyexpansion: function (k) { keyschedule = []; @@ -3779,7 +3779,7 @@ * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * Ported to JavaScript by bitaddress.org */ - ec.FieldElementFp.fastLucasSequence = function(p, P, Q, k) { + ec.FieldElementFp.fastLucasSequence = function (p, P, Q, k) { // TODO Research and apply "common-multiplicand multiplication here" var n = k.bitLength(); @@ -3822,7 +3822,7 @@ // ---------------- // ECPointFp constructor - ec.PointFp = function(curve, x, y, z, compressed) { + ec.PointFp = function (curve, x, y, z, compressed) { this.curve = curve; this.x = x; this.y = y; @@ -3838,7 +3838,7 @@ this.compressed = !!compressed; }; - ec.PointFp.prototype.getX = function() { + ec.PointFp.prototype.getX = function () { if (this.zinv == null) { this.zinv = this.z.modInverse(this.curve.q); } @@ -3847,7 +3847,7 @@ return this.curve.fromBigInteger(r); }; - ec.PointFp.prototype.getY = function() { + ec.PointFp.prototype.getY = function () { if (this.zinv == null) { this.zinv = this.z.modInverse(this.curve.q); } @@ -3856,7 +3856,7 @@ return this.curve.fromBigInteger(r); }; - ec.PointFp.prototype.equals = function(other) { + ec.PointFp.prototype.equals = function (other) { if (other == this) return true; if (this.isInfinity()) return other.isInfinity(); if (other.isInfinity()) return this.isInfinity(); @@ -3871,16 +3871,16 @@ return v.equals(BigInteger.ZERO); }; - ec.PointFp.prototype.isInfinity = function() { + ec.PointFp.prototype.isInfinity = function () { if ((this.x == null) && (this.y == null)) return true; return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); }; - ec.PointFp.prototype.negate = function() { + ec.PointFp.prototype.negate = function () { return new ec.PointFp(this.curve, this.x, this.y.negate(), this.z); }; - ec.PointFp.prototype.add = function(b) { + ec.PointFp.prototype.add = function (b) { if (this.isInfinity()) return b; if (b.isInfinity()) return this; @@ -3922,7 +3922,7 @@ z3); }; - ec.PointFp.prototype.twice = function() { + ec.PointFp.prototype.twice = function () { if (this.isInfinity()) return this; if (this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); @@ -3957,7 +3957,7 @@ // Simple NAF (Non-Adjacent Form) multiplication algorithm // TODO: modularize the multiplication algorithm - ec.PointFp.prototype.multiply = function(k) { + ec.PointFp.prototype.multiply = function (k) { if (this.isInfinity()) return this; if (k.signum() == 0) return this.curve.getInfinity(); @@ -3983,7 +3983,7 @@ }; // Compute this*j + x*k (simultaneous multiplication) - ec.PointFp.prototype.multiplyTwo = function(j, x, k) { + ec.PointFp.prototype.multiplyTwo = function (j, x, k) { var i; if (j.bitLength() > k.bitLength()) i = j.bitLength() - 1; @@ -4013,7 +4013,7 @@ // patched by bitaddress.org and Casascius for use with Bitcoin.ECKey // patched by coretechs to support compressed public keys - ec.PointFp.prototype.getEncoded = function(compressed) { + ec.PointFp.prototype.getEncoded = function (compressed) { var x = this.getX().toBigInteger(); var y = this.getY().toBigInteger(); var len = 32; // integerToBytes will zero pad if integer is less than 32 bytes. 32 bytes length is required by the Bitcoin protocol. @@ -4033,7 +4033,7 @@ return enc; }; - ec.PointFp.decodeFrom = function(curve, enc) { + ec.PointFp.decodeFrom = function (curve, enc) { var type = enc[0]; var dataLen = enc.length - 1; @@ -4053,7 +4053,7 @@ return new ec.PointFp(curve, curve.fromBigInteger(x), curve.fromBigInteger(y)); }; - ec.PointFp.prototype.add2D = function(b) { + ec.PointFp.prototype.add2D = function (b) { if (this.isInfinity()) return b; if (b.isInfinity()) return this; @@ -4076,7 +4076,7 @@ return new ec.PointFp(this.curve, x3, y3); }; - ec.PointFp.prototype.twice2D = function() { + ec.PointFp.prototype.twice2D = function () { if (this.isInfinity()) return this; if (this.y.toBigInteger().signum() == 0) { // if y1 == 0, then (x1, y1) == (x1, -y1) @@ -4094,7 +4094,7 @@ return new ec.PointFp(this.curve, x3, y3); }; - ec.PointFp.prototype.multiply2D = function(k) { + ec.PointFp.prototype.multiply2D = function (k) { if (this.isInfinity()) return this; if (k.signum() == 0) return this.curve.getInfinity(); @@ -4119,7 +4119,7 @@ return R; }; - ec.PointFp.prototype.isOnCurve = function() { + ec.PointFp.prototype.isOnCurve = function () { var x = this.getX().toBigInteger(); var y = this.getY().toBigInteger(); var a = this.curve.getA().toBigInteger(); @@ -4130,7 +4130,7 @@ return lhs.equals(rhs); }; - ec.PointFp.prototype.toString = function() { + ec.PointFp.prototype.toString = function () { return '(' + this.getX().toBigInteger().toString() + ',' + this.getY().toBigInteger().toString() + ')'; }; @@ -4140,7 +4140,7 @@ * * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive */ - ec.PointFp.prototype.validate = function() { + ec.PointFp.prototype.validate = function () { var n = this.curve.getQ(); // Check Q != O @@ -4177,7 +4177,7 @@ // ---------------- // ECCurveFp constructor - ec.CurveFp = function(q, a, b) { + ec.CurveFp = function (q, a, b) { this.q = q; this.a = this.fromBigInteger(a); this.b = this.fromBigInteger(b); @@ -4185,38 +4185,38 @@ this.reducer = new Barrett(this.q); } - ec.CurveFp.prototype.getQ = function() { + ec.CurveFp.prototype.getQ = function () { return this.q; }; - ec.CurveFp.prototype.getA = function() { + ec.CurveFp.prototype.getA = function () { return this.a; }; - ec.CurveFp.prototype.getB = function() { + ec.CurveFp.prototype.getB = function () { return this.b; }; - ec.CurveFp.prototype.equals = function(other) { + ec.CurveFp.prototype.equals = function (other) { if (other == this) return true; return (this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); }; - ec.CurveFp.prototype.getInfinity = function() { + ec.CurveFp.prototype.getInfinity = function () { return this.infinity; }; - ec.CurveFp.prototype.fromBigInteger = function(x) { + ec.CurveFp.prototype.fromBigInteger = function (x) { return new ec.FieldElementFp(this.q, x); }; - ec.CurveFp.prototype.reduce = function(x) { + ec.CurveFp.prototype.reduce = function (x) { this.reducer.reduce(x); }; // for now, work with hex strings because they're easier in JS // compressed support added by bitaddress.org - ec.CurveFp.prototype.decodePointHex = function(s) { + ec.CurveFp.prototype.decodePointHex = function (s) { var firstByte = parseInt(s.substr(0, 2), 16); switch (firstByte) { // first byte case 0: @@ -4243,7 +4243,7 @@ } }; - ec.CurveFp.prototype.encodePointHex = function(p) { + ec.CurveFp.prototype.encodePointHex = function (p) { if (p.isInfinity()) return "00"; var xHex = p.getX().toBigInteger().toString(16); var yHex = p.getY().toBigInteger().toString(16); @@ -4265,7 +4265,7 @@ * Number yTilde * BigInteger X1 */ - ec.CurveFp.prototype.decompressPoint = function(yTilde, X1) { + ec.CurveFp.prototype.decompressPoint = function (yTilde, X1) { var x = this.fromBigInteger(X1); var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); var beta = alpha.sqrt(); @@ -4281,11 +4281,11 @@ }; - ec.fromHex = function(s) { + ec.fromHex = function (s) { return new BigInteger(s, 16); }; - ec.integerToBytes = function(i, len) { + ec.integerToBytes = function (i, len) { var bytes = i.toByteArrayUnsigned(); if (len < bytes.length) { bytes = bytes.slice(bytes.length - len); @@ -4300,29 +4300,29 @@ // Named EC curves // ---------------- // X9ECParameters constructor - ec.X9Parameters = function(curve, g, n, h) { + ec.X9Parameters = function (curve, g, n, h) { this.curve = curve; this.g = g; this.n = n; this.h = h; } - ec.X9Parameters.prototype.getCurve = function() { + ec.X9Parameters.prototype.getCurve = function () { return this.curve; }; - ec.X9Parameters.prototype.getG = function() { + ec.X9Parameters.prototype.getG = function () { return this.g; }; - ec.X9Parameters.prototype.getN = function() { + ec.X9Parameters.prototype.getN = function () { return this.n; }; - ec.X9Parameters.prototype.getH = function() { + ec.X9Parameters.prototype.getH = function () { return this.h; }; // secp256k1 is the Curve used by Bitcoin ec.secNamedCurves = { // used by Bitcoin - "secp256k1": function() { + "secp256k1": function () { // p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 var p = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"); var a = BigInteger.ZERO; @@ -4338,16 +4338,16 @@ }; // secp256k1 called by Bitcoin's ECKEY - ec.getSECCurveByName = function(name) { + ec.getSECCurveByName = function (name) { if (ec.secNamedCurves[name] == undefined) return null; return ec.secNamedCurves[name](); } })(); //bitTrx.js - (function() { + (function () { - var bitjs = GLOBAL.bitjs = function() {}; + var bitjs = GLOBAL.bitjs = function () { }; function ascii_to_hexa(str) { var arr1 = []; @@ -4364,7 +4364,7 @@ bitjs.compressed = false; /* provide a privkey and return an WIF */ - bitjs.privkey2wif = function(h) { + bitjs.privkey2wif = function (h) { var r = Crypto.util.hexToBytes(h); if (bitjs.compressed == true) { @@ -4383,7 +4383,7 @@ } /* convert a wif key back to a private key */ - bitjs.wif2privkey = function(wif) { + bitjs.wif2privkey = function (wif) { var compressed = false; var decode = B58.decode(wif); var key = decode.slice(0, decode.length - 4); @@ -4399,7 +4399,7 @@ } /* convert a wif to a pubkey */ - bitjs.wif2pubkey = function(wif) { + bitjs.wif2pubkey = function (wif) { var compressed = bitjs.compressed; var r = bitjs.wif2privkey(wif); bitjs.compressed = r['compressed']; @@ -4412,7 +4412,7 @@ } /* convert a wif to a address */ - bitjs.wif2address = function(wif) { + bitjs.wif2address = function (wif) { var r = bitjs.wif2pubkey(wif); return { 'address': bitjs.pubkey2address(r['pubkey']), @@ -4421,7 +4421,7 @@ } /* generate a public key from a private key */ - bitjs.newPubkey = function(hash) { + bitjs.newPubkey = function (hash) { var privateKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(hash)); var curve = EllipticCurve.getSECCurveByName("secp256k1"); @@ -4447,7 +4447,7 @@ } /* provide a public key and return address */ - bitjs.pubkey2address = function(h, byte) { + bitjs.pubkey2address = function (h, byte) { var r = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(h), { asBytes: true })); @@ -4461,7 +4461,7 @@ return B58.encode(r.concat(checksum)); } - bitjs.transaction = function() { + bitjs.transaction = function () { var btrx = {}; btrx.version = 2; //flochange look at this version btrx.inputs = []; @@ -4470,7 +4470,7 @@ btrx.floData = ""; //flochange .. look at this - btrx.addinput = function(txid, index, scriptPubKey, sequence) { + btrx.addinput = function (txid, index, scriptPubKey, sequence) { var o = {}; o.outpoint = { 'hash': txid, @@ -4482,7 +4482,7 @@ return this.inputs.push(o); } - btrx.addoutput = function(address, value) { + btrx.addoutput = function (address, value) { var o = {}; var buf = []; var addrDecoded = btrx.addressDecode(address); @@ -4498,14 +4498,14 @@ } - btrx.addflodata = function(txcomments) { // flochange - this whole function needs to be done + btrx.addflodata = function (txcomments) { // flochange - this whole function needs to be done this.floData = txcomments; return this.floData; //flochange .. returning the txcomments -- check if the function return will assign } // Only standard addresses - btrx.addressDecode = function(address) { + btrx.addressDecode = function (address) { var bytes = B58.decode(address); var front = bytes.slice(0, bytes.length - 4); var back = bytes.slice(bytes.length - 4); @@ -4520,7 +4520,7 @@ } /* generate the transaction hash to sign from a transaction input */ - btrx.transactionHash = function(index, sigHashType) { + btrx.transactionHash = function (index, sigHashType) { var clone = bitjs.clone(this); var shType = sigHashType || 1; @@ -4602,7 +4602,7 @@ } /* generate a signature from a transaction hash */ - btrx.transactionSig = function(index, wif, sigHashType, txhash) { + btrx.transactionSig = function (index, wif, sigHashType, txhash) { function serializeSig(r, s) { var rBa = r.toByteArraySigned(); @@ -4658,7 +4658,7 @@ } // https://tools.ietf.org/html/rfc6979#section-3.2 - btrx.deterministicK = function(wif, hash, badrs) { + btrx.deterministicK = function (wif, hash, badrs) { // if r or s were invalid when this function was used in signing, // we do not want to actually compute r, s here for efficiency, so, // we can increment badrs. explained at end of RFC 6979 section 3.2 @@ -4741,7 +4741,7 @@ }; /* sign a "standard" input */ - btrx.signinput = function(index, wif, sigHashType) { + btrx.signinput = function (index, wif, sigHashType) { var key = bitjs.wif2pubkey(wif); var shType = sigHashType || 1; var signature = this.transactionSig(index, wif, shType); @@ -4757,7 +4757,7 @@ } /* sign inputs */ - btrx.sign = function(wif, sigHashType) { + btrx.sign = function (wif, sigHashType) { var shType = sigHashType || 1; for (var i = 0; i < this.inputs.length; i++) { this.signinput(i, wif, shType); @@ -4767,7 +4767,7 @@ /* serialize a transaction */ - btrx.serialize = function() { + btrx.serialize = function () { var buffer = []; buffer = buffer.concat(bitjs.numToBytes(parseInt(this.version), 4)); @@ -4820,7 +4820,7 @@ } - bitjs.numToBytes = function(num, bytes) { + bitjs.numToBytes = function (num, bytes) { if (typeof bytes === "undefined") bytes = 8; if (bytes == 0) { return []; @@ -4831,7 +4831,7 @@ } } - bitjs.numToByteArray = function(num) { + bitjs.numToByteArray = function (num) { if (num <= 256) { return [num]; } else { @@ -4839,7 +4839,7 @@ } } - bitjs.numToVarInt = function(num) { + bitjs.numToVarInt = function (num) { if (num < 253) { return [num]; } else if (num < 65536) { @@ -4851,14 +4851,14 @@ } } - bitjs.bytesToNum = function(bytes) { + bitjs.bytesToNum = function (bytes) { if (bytes.length == 0) return 0; else return bytes[0] + 256 * bitjs.bytesToNum(bytes.slice(1)); } /* clone an object */ - bitjs.clone = function(obj) { - if (obj == null || typeof(obj) != 'object') return obj; + bitjs.clone = function (obj) { + if (obj == null || typeof (obj) != 'object') return obj; var temp = new obj.constructor(); for (var key in obj) { @@ -4882,7 +4882,7 @@ * * Ported to JavaScript by Stefan Thomas. */ - encode: function(input) { + encode: function (input) { var bi = BigInteger.fromByteArrayUnsigned(input); var chars = []; @@ -4911,7 +4911,7 @@ * * Ported to JavaScript by Stefan Thomas. */ - decode: function(input) { + decode: function (input) { var bi = BigInteger.valueOf(0); var leadingZerosNum = 0; for (var i = input.length - 1; i >= 0; i--) { @@ -4939,7 +4939,7 @@ })(); //Bitcoin.js - (function() { + (function () { /* Copyright (c) 2011 Stefan Thomas @@ -4965,7 +4965,7 @@ * * Ported to JavaScript by Stefan Thomas. */ - encode: function(input) { + encode: function (input) { var bi = BigInteger.fromByteArrayUnsigned(input); var chars = []; @@ -4994,7 +4994,7 @@ * * Ported to JavaScript by Stefan Thomas. */ - decode: function(input) { + decode: function (input) { var bi = BigInteger.valueOf(0); var leadingZerosNum = 0; for (var i = input.length - 1; i >= 0; i--) { @@ -5019,7 +5019,7 @@ }; //https://raw.github.com/bitcoinjs/bitcoinjs-lib/09e8c6e184d6501a0c2c59d73ca64db5c0d3eb95/src/address.js - Bitcoin.Address = function(bytes) { + Bitcoin.Address = function (bytes) { if (GLOBAL.cryptocoin == "FLO") this.version = 0x23; // FLO mainnet public address else if (GLOBAL.cryptocoin == "FLO_TEST") @@ -5037,7 +5037,7 @@ * * Returns the address as a base58-encoded string in the standardized format. */ - Bitcoin.Address.prototype.toString = function(version = null) { + Bitcoin.Address.prototype.toString = function (version = null) { // Get a copy of the hash var hash = this.hash.slice(0); @@ -5052,14 +5052,14 @@ return Bitcoin.Base58.encode(bytes); }; - Bitcoin.Address.prototype.getHashBase64 = function() { + Bitcoin.Address.prototype.getHashBase64 = function () { return Crypto.util.bytesToBase64(this.hash); }; /** * Parse a Bitcoin address contained in a string. */ - Bitcoin.Address.decodeString = function(string, version) { + Bitcoin.Address.decodeString = function (string, version) { var bytes = Bitcoin.Base58.decode(string); var hash = bytes.slice(0, 21); var checksum = Crypto.SHA256(Crypto.SHA256(hash, { @@ -5082,7 +5082,7 @@ return hash; }; //https://raw.github.com/bitcoinjs/bitcoinjs-lib/e90780d3d3b8fc0d027d2bcb38b80479902f223e/src/ecdsa.js - Bitcoin.ECDSA = (function() { + Bitcoin.ECDSA = (function () { var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); var rng = new SecureRandom(); @@ -5115,12 +5115,12 @@ }; var ECDSA = { - getBigRandom: function(limit) { + getBigRandom: function (limit) { return new BigInteger(limit.bitLength(), rng) .mod(limit.subtract(BigInteger.ONE)) .add(BigInteger.ONE); }, - sign: function(hash, priv) { + sign: function (hash, priv) { var d = priv; var n = ecparams.getN(); var e = BigInteger.fromByteArrayUnsigned(hash); @@ -5137,7 +5137,7 @@ return ECDSA.serializeSig(r, s); }, - verify: function(hash, sig, pubkey) { + verify: function (hash, sig, pubkey) { var r, s; if (Bitcoin.Util.isArray(sig)) { var obj = ECDSA.parseSig(sig); @@ -5163,7 +5163,7 @@ return ECDSA.verifyRaw(e, r, s, Q); }, - verifyRaw: function(e, r, s, Q) { + verifyRaw: function (e, r, s, Q) { var n = ecparams.getN(); var G = ecparams.getG(); @@ -5196,7 +5196,7 @@ * * Takes two BigIntegers representing r and s and returns a byte array. */ - serializeSig: function(r, s) { + serializeSig: function (r, s) { var rBa = r.toByteArraySigned(); var sBa = s.toByteArraySigned(); @@ -5225,7 +5225,7 @@ * s: BigInteger * } */ - parseSig: function(sig) { + parseSig: function (sig) { var cursor; if (sig[0] != 0x30) throw new Error("Signature not a valid DERSequence"); @@ -5254,7 +5254,7 @@ }; }, - parseSigCompact: function(sig) { + parseSigCompact: function (sig) { if (sig.length !== 65) { throw "Signature has the wrong length"; } @@ -5285,7 +5285,7 @@ * * http://www.secg.org/download/aid-780/sec1-v2.pdf */ - recoverPubKey: function(r, s, hash, i) { + recoverPubKey: function (r, s, hash, i) { // The recovery parameter i has two bits. i = i & 3; @@ -5356,14 +5356,14 @@ * This function simply tries all four cases and returns the value * that resulted in a successful pubkey recovery. */ - calcPubkeyRecoveryParam: function(address, r, s, hash) { + calcPubkeyRecoveryParam: function (address, r, s, hash) { for (var i = 0; i < 4; i++) { try { var pubkey = Bitcoin.ECDSA.recoverPubKey(r, s, hash, i); if (pubkey.getBitcoinAddress().toString() == address) { return i; } - } catch (e) {} + } catch (e) { } } throw "Unable to find valid recovery factor"; } @@ -5371,11 +5371,11 @@ return ECDSA; })(); - Bitcoin.KeyPool = (function() { - var KeyPool = function() { + Bitcoin.KeyPool = (function () { + var KeyPool = function () { this.keyArray = []; - this.push = function(item) { + this.push = function (item) { if (item == null || item.priv == null) return; var doAdd = true; // prevent duplicates from being added to the array @@ -5389,24 +5389,24 @@ if (doAdd) this.keyArray.push(item); }; - this.reset = function() { + this.reset = function () { this.keyArray = []; }; - this.getArray = function() { + this.getArray = function () { // copy array return this.keyArray.slice(0); }; - this.setArray = function(ka) { + this.setArray = function (ka) { this.keyArray = ka; }; - this.length = function() { + this.length = function () { return this.keyArray.length; }; - this.toString = function() { + this.toString = function () { var keyPoolString = "# = " + this.length() + "\n"; var pool = this.getArray(); for (var index in pool) { @@ -5427,17 +5427,17 @@ return new KeyPool(); })(); - Bitcoin.Bip38Key = (function() { - var Bip38 = function(address, encryptedKey) { + Bitcoin.Bip38Key = (function () { + var Bip38 = function (address, encryptedKey) { this.address = address; this.priv = encryptedKey; }; - Bip38.prototype.getBitcoinAddress = function() { + Bip38.prototype.getBitcoinAddress = function () { return this.address; }; - Bip38.prototype.toString = function() { + Bip38.prototype.toString = function () { return this.priv; }; @@ -5445,12 +5445,12 @@ })(); //https://raw.github.com/pointbiz/bitcoinjs-lib/9b2f94a028a7bc9bed94e0722563e9ff1d8e8db8/src/eckey.js - Bitcoin.ECKey = (function() { + Bitcoin.ECKey = (function () { var ECDSA = Bitcoin.ECDSA; var KeyPool = Bitcoin.KeyPool; var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); - var ECKey = function(input) { + var ECKey = function (input) { if (!input) { // Generate new key var n = ecparams.getN(); @@ -5533,7 +5533,7 @@ /** * Set whether the public key should be returned compressed or not. */ - ECKey.prototype.setError = function(err) { + ECKey.prototype.setError = function (err) { this.error = err; this.priv = null; return this; @@ -5542,7 +5542,7 @@ /** * Set whether the public key should be returned compressed or not. */ - ECKey.prototype.setCompressed = function(v) { + ECKey.prototype.setCompressed = function (v) { this.compressed = !!v; if (this.pubPoint) this.pubPoint.compressed = this.compressed; return this; @@ -5551,7 +5551,7 @@ /* * Return public key as a byte array in DER encoding */ - ECKey.prototype.getPub = function() { + ECKey.prototype.getPub = function () { if (this.compressed) { if (this.pubComp) return this.pubComp; return this.pubComp = this.getPubPoint().getEncoded(1); @@ -5564,7 +5564,7 @@ /** * Return public point as ECPoint object. */ - ECKey.prototype.getPubPoint = function() { + ECKey.prototype.getPubPoint = function () { if (!this.pubPoint) { this.pubPoint = ecparams.getG().multiply(this.priv); this.pubPoint.compressed = this.compressed; @@ -5572,7 +5572,7 @@ return this.pubPoint; }; - ECKey.prototype.getPubKeyHex = function() { + ECKey.prototype.getPubKeyHex = function () { if (this.compressed) { if (this.pubKeyHexComp) return this.pubKeyHexComp; return this.pubKeyHexComp = Crypto.util.bytesToHex(this.getPub()).toString().toUpperCase(); @@ -5588,7 +5588,7 @@ * This is calculated as RIPE160(SHA256([encoded pubkey])) and returned as * a byte array. */ - ECKey.prototype.getPubKeyHash = function() { + ECKey.prototype.getPubKeyHash = function () { if (this.compressed) { if (this.pubKeyHashComp) return this.pubKeyHashComp; return this.pubKeyHashComp = Bitcoin.Util.sha256ripe160(this.getPub()); @@ -5598,7 +5598,7 @@ } }; - ECKey.prototype.getBitcoinAddress = function() { + ECKey.prototype.getBitcoinAddress = function () { var hash = this.getPubKeyHash(); var addr = new Bitcoin.Address(hash); return addr.toString(); @@ -5607,7 +5607,7 @@ /* * Takes a public point as a hex string or byte array */ - ECKey.prototype.setPub = function(pub) { + ECKey.prototype.setPub = function (pub) { // byte array if (Bitcoin.Util.isArray(pub)) { pub = Crypto.util.bytesToHex(pub).toString().toUpperCase(); @@ -5619,7 +5619,7 @@ }; // Sipa Private Key Wallet Import Format - ECKey.prototype.getBitcoinWalletImportFormat = function() { + ECKey.prototype.getBitcoinWalletImportFormat = function () { var bytes = this.getBitcoinPrivateKeyByteArray(); if (bytes == null) return ""; bytes.unshift(ECKey.privateKeyPrefix); // prepend 0x80 byte @@ -5635,16 +5635,16 @@ }; // Private Key Hex Format - ECKey.prototype.getBitcoinHexFormat = function() { + ECKey.prototype.getBitcoinHexFormat = function () { return Crypto.util.bytesToHex(this.getBitcoinPrivateKeyByteArray()).toString().toUpperCase(); }; // Private Key Base64 Format - ECKey.prototype.getBitcoinBase64Format = function() { + ECKey.prototype.getBitcoinBase64Format = function () { return Crypto.util.bytesToBase64(this.getBitcoinPrivateKeyByteArray()); }; - ECKey.prototype.getBitcoinPrivateKeyByteArray = function() { + ECKey.prototype.getBitcoinPrivateKeyByteArray = function () { if (this.priv == null) return null; // Get a copy of private key as a byte array var bytes = this.priv.toByteArrayUnsigned(); @@ -5653,7 +5653,7 @@ return bytes; }; - ECKey.prototype.toString = function(format) { + ECKey.prototype.toString = function (format) { format = format || ""; if (format.toString().toLowerCase() == "base64" || format.toString().toLowerCase() == "b64") { return this.getBitcoinBase64Format(); @@ -5666,18 +5666,18 @@ } }; - ECKey.prototype.sign = function(hash) { + ECKey.prototype.sign = function (hash) { return ECDSA.sign(hash, this.priv); }; - ECKey.prototype.verify = function(hash, sig) { + ECKey.prototype.verify = function (hash, sig) { return ECDSA.verify(hash, sig, this.getPub()); }; /** * Parse a wallet import format private key contained in a string. */ - ECKey.decodeWalletImportFormat = function(privStr) { + ECKey.decodeWalletImportFormat = function (privStr) { var bytes = Bitcoin.Base58.decode(privStr); var hash = bytes.slice(0, 33); var checksum = Crypto.SHA256(Crypto.SHA256(hash, { @@ -5704,7 +5704,7 @@ /** * Parse a compressed wallet import format private key contained in a string. */ - ECKey.decodeCompressedWalletImportFormat = function(privStr) { + ECKey.decodeCompressedWalletImportFormat = function (privStr) { var bytes = Bitcoin.Base58.decode(privStr); var hash = bytes.slice(0, 34); var checksum = Crypto.SHA256(Crypto.SHA256(hash, { @@ -5729,13 +5729,13 @@ }; // 64 characters [0-9A-F] - ECKey.isHexFormat = function(key) { + ECKey.isHexFormat = function (key) { key = key.toString(); return /^[A-Fa-f0-9]{64}$/.test(key); }; // 51 characters base58, always starts with a '5' - ECKey.isWalletImportFormat = function(key) { + ECKey.isWalletImportFormat = function (key) { key = key.toString(); return (ECKey.privateKeyPrefix == 0x80) ? (/^5[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{50}$/.test(key)) : @@ -5743,7 +5743,7 @@ }; // 52 characters base58 - ECKey.isCompressedWalletImportFormat = function(key) { + ECKey.isCompressedWalletImportFormat = function (key) { key = key.toString(); return (ECKey.privateKeyPrefix == 0x80) ? (/^[LK][123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(key)) : @@ -5751,19 +5751,19 @@ }; // 44 characters - ECKey.isBase64Format = function(key) { + ECKey.isBase64Format = function (key) { key = key.toString(); return (/^[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789=+\/]{44}$/.test(key)); }; // 99 characters, 1=1, if using dice convert 6 to 0 - ECKey.isBase6Format = function(key) { + ECKey.isBase6Format = function (key) { key = key.toString(); return (/^[012345]{99}$/.test(key)); }; // 22, 26 or 30 characters, always starts with an 'S' - ECKey.isMiniFormat = function(key) { + ECKey.isMiniFormat = function (key) { key = key.toString(); var validChars22 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21}$/.test(key); var validChars26 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{25}$/.test(key); @@ -5783,13 +5783,13 @@ /** * Cross-browser compatibility version of Array.isArray. */ - isArray: Array.isArray || function(o) { + isArray: Array.isArray || function (o) { return Object.prototype.toString.call(o) === '[object Array]'; }, /** * Create an array of a certain length filled with a specific value. */ - makeFilledArray: function(len, val) { + makeFilledArray: function (len, val) { var array = []; var i = 0; while (i < len) { @@ -5804,7 +5804,7 @@ * * Returns a byte array. */ - numToVarInt: function(i) { + numToVarInt: function (i) { if (i < 0xfd) { // unsigned char return [i]; @@ -5822,7 +5822,7 @@ /** * Parse a Bitcoin value byte array, returning a BigInteger. */ - valueToBigInt: function(valueBuffer) { + valueToBigInt: function (valueBuffer) { if (valueBuffer instanceof BigInteger) return valueBuffer; // Prepend zero byte to prevent interpretation as negative integer @@ -5840,7 +5840,7 @@ * 900.99998888 * 34.00 */ - formatValue: function(valueBuffer) { + formatValue: function (valueBuffer) { var value = this.valueToBigInt(valueBuffer).toString(); var integerPart = value.length > 8 ? value.substr(0, value.length - 8) : '0'; var decimalPart = value.length > 8 ? value.substr(value.length - 8) : value; @@ -5856,7 +5856,7 @@ * the parsed value back to the user to make sure we understood his input * correctly. */ - parseValue: function(valueString) { + parseValue: function (valueString) { // TODO: Detect other number formats (e.g. comma as decimal separator) var valueComp = valueString.split('.'); var integralPart = valueComp[0]; @@ -5874,7 +5874,7 @@ * Takes an arbitrary byte array as inputs and returns the hash as a byte * array. */ - sha256ripe160: function(data) { + sha256ripe160: function (data) { return ripemd160(Crypto.SHA256(data, { asBytes: true }), { @@ -5882,7 +5882,7 @@ }); }, // double sha256 - dsha256: function(data) { + dsha256: function (data) { return Crypto.SHA256(Crypto.SHA256(data, { asBytes: true }), { @@ -5890,7 +5890,7 @@ }); }, // duck typing method - hasMethods: function(obj /*, method list as strings */ ) { + hasMethods: function (obj /*, method list as strings */) { var i = 1, methodName; while ((methodName = arguments[i++])) { @@ -5904,15 +5904,15 @@ })(); //ellipticCurveEncryption.js - (function() { - (function(ellipticCurveType) { + (function () { + (function (ellipticCurveType) { //Defining Elliptic Encryption Object - var ellipticEncryption = GLOBAL.ellipticCurveEncryption = function() {}; + var ellipticEncryption = GLOBAL.ellipticCurveEncryption = function () { }; ellipticEncryption.rng = new SecureRandom(); - ellipticEncryption.getCurveParameters = function(curveName) { + ellipticEncryption.getCurveParameters = function (curveName) { //Default is secp256k1 curveName = typeof curveName !== 'undefined' ? curveName : "secp256k1"; @@ -5940,38 +5940,38 @@ ellipticEncryption.selectedCurve = ellipticEncryption.getCurveParameters(ellipticCurveType); - ellipticEncryption.get_curve = function() { + ellipticEncryption.get_curve = function () { return new EllipticCurve.CurveFp(new BigInteger(this.selectedCurve.Q), new BigInteger(this.selectedCurve.A), new BigInteger(this.selectedCurve.B)); } - ellipticEncryption.get_G = function(curve) { + ellipticEncryption.get_G = function (curve) { return new EllipticCurve.PointFp(curve, curve.fromBigInteger(new BigInteger(this.selectedCurve.GX)), curve.fromBigInteger(new BigInteger(this.selectedCurve.GY))); } - ellipticEncryption.pick_rand = function() { + ellipticEncryption.pick_rand = function () { var n = new BigInteger(this.selectedCurve.N); var n1 = n.subtract(BigInteger.ONE); var r = new BigInteger(n.bitLength(), this.rng); return r.mod(n1).add(BigInteger.ONE); } - ellipticEncryption.senderRandom = function() { + ellipticEncryption.senderRandom = function () { var r = this.pick_rand(); return r.toString(); }; - ellipticEncryption.receiverRandom = function() { + ellipticEncryption.receiverRandom = function () { //This is receivers private key. For now we will use random. CHANGE IT LATER var r = this.pick_rand(); return r.toString(); } - ellipticEncryption.senderPublicString = function(senderPrivateKey) { + ellipticEncryption.senderPublicString = function (senderPrivateKey) { var senderKeyECData = {}; @@ -5987,7 +5987,7 @@ //In real life ellipticEncryption.receiverPublicString is the public key of the receiver. //you don't have to run receiverRandom and the bottom function - ellipticEncryption.receiverPublicString = function(receiverPublicKey) { + ellipticEncryption.receiverPublicString = function (receiverPublicKey) { var receiverKeyECData = {}; @@ -6001,7 +6001,7 @@ return receiverKeyECData; } - ellipticEncryption.senderSharedKeyDerivation = function(receiverPublicStringXValue, + ellipticEncryption.senderSharedKeyDerivation = function (receiverPublicStringXValue, receiverPublicStringYValue, senderPrivateKey) { var senderDerivedKey = {}; @@ -6018,7 +6018,7 @@ return senderDerivedKey; } - ellipticEncryption.receiverSharedKeyDerivation = function(senderPublicStringXValue, + ellipticEncryption.receiverSharedKeyDerivation = function (senderPublicStringXValue, senderPublicStringYValue, receiverPrivateKey) { var receiverDerivedKey = {}; @@ -6039,17 +6039,17 @@ })(); //sha512.js - (function() { + (function () { /* - A JavaScript implementation of the SHA family of hashes, as defined in FIPS - PUB 180-2 as well as the corresponding HMAC implementation as defined in - FIPS PUB 198a + A JavaScript implementation of the SHA family of hashes, as defined in FIPS + PUB 180-2 as well as the corresponding HMAC implementation as defined in + FIPS PUB 198a - Copyright Brian Turek 2008-2012 - Distributed under the BSD License - See http://caligatio.github.com/jsSHA/ for more information + Copyright Brian Turek 2008-2012 + Distributed under the BSD License + See http://caligatio.github.com/jsSHA/ for more information - Several functions taken from Paul Johnson + Several functions taken from Paul Johnson */ function n(a) { throw a; @@ -6128,7 +6128,7 @@ }; try { a.hasOwnProperty("outputUpper") && (b.outputUpper = a.outputUpper), a.hasOwnProperty("b64Pad") && (b.b64Pad = a.b64Pad) - } catch (d) {} + } catch (d) { } "boolean" !== typeof b.outputUpper && n("Invalid outputUpper formatting option"); "string" !== typeof b.b64Pad && n("Invalid b64Pad formatting option"); return b @@ -6215,12 +6215,12 @@ var h, f, g, k, m, j, A, C, K, e, L, v, l, M, t, p, y, z, r, N, O, P, Q, R, c, S, w = [], T, D; "SHA-384" === d || "SHA-512" === d ? (L = 80, h = (b + 128 >>> 10 << 5) + 31, M = 32, t = 2, c = s, p = Z, y = aa, z = ba, r = X, N = Y, O = V, P = W, R = U, Q = J, S = [new c(1116352408, 3609767458), new c(1899447441, 602891725), new c(3049323471, 3964484399), new c(3921009573, 2173295548), new c(961987163, 4081628472), new c(1508970993, 3053834265), new c(2453635748, 2937671579), new c(2870763221, 3664609560), new c(3624381080, 2734883394), new c(310598401, 1164996542), new c(607225278, 1323610764), - new c(1426881987, 3590304994), new c(1925078388, 4068182383), new c(2162078206, 991336113), new c(2614888103, 633803317), new c(3248222580, 3479774868), new c(3835390401, 2666613458), new c(4022224774, 944711139), new c(264347078, 2341262773), new c(604807628, 2007800933), new c(770255983, 1495990901), new c(1249150122, 1856431235), new c(1555081692, 3175218132), new c(1996064986, 2198950837), new c(2554220882, 3999719339), new c(2821834349, 766784016), new c(2952996808, 2566594879), new c(3210313671, 3203337956), new c(3336571891, - 1034457026), new c(3584528711, 2466948901), new c(113926993, 3758326383), new c(338241895, 168717936), new c(666307205, 1188179964), new c(773529912, 1546045734), new c(1294757372, 1522805485), new c(1396182291, 2643833823), new c(1695183700, 2343527390), new c(1986661051, 1014477480), new c(2177026350, 1206759142), new c(2456956037, 344077627), new c(2730485921, 1290863460), new c(2820302411, 3158454273), new c(3259730800, 3505952657), new c(3345764771, 106217008), new c(3516065817, 3606008344), new c(3600352804, 1432725776), new c(4094571909, + new c(1426881987, 3590304994), new c(1925078388, 4068182383), new c(2162078206, 991336113), new c(2614888103, 633803317), new c(3248222580, 3479774868), new c(3835390401, 2666613458), new c(4022224774, 944711139), new c(264347078, 2341262773), new c(604807628, 2007800933), new c(770255983, 1495990901), new c(1249150122, 1856431235), new c(1555081692, 3175218132), new c(1996064986, 2198950837), new c(2554220882, 3999719339), new c(2821834349, 766784016), new c(2952996808, 2566594879), new c(3210313671, 3203337956), new c(3336571891, + 1034457026), new c(3584528711, 2466948901), new c(113926993, 3758326383), new c(338241895, 168717936), new c(666307205, 1188179964), new c(773529912, 1546045734), new c(1294757372, 1522805485), new c(1396182291, 2643833823), new c(1695183700, 2343527390), new c(1986661051, 1014477480), new c(2177026350, 1206759142), new c(2456956037, 344077627), new c(2730485921, 1290863460), new c(2820302411, 3158454273), new c(3259730800, 3505952657), new c(3345764771, 106217008), new c(3516065817, 3606008344), new c(3600352804, 1432725776), new c(4094571909, 1467031594), new c(275423344, 851169720), new c(430227734, 3100823752), new c(506948616, 1363258195), new c(659060556, 3750685593), new c(883997877, 3785050280), new c(958139571, 3318307427), new c(1322822218, 3812723403), new c(1537002063, 2003034995), new c(1747873779, 3602036899), new c(1955562222, 1575990012), new c(2024104815, 1125592928), new c(2227730452, 2716904306), new c(2361852424, 442776044), new c(2428436474, 593698344), new c(2756734187, 3733110249), new c(3204031479, 2999351573), new c(3329325298, 3815920427), new c(3391569614, - 3928383900), new c(3515267271, 566280711), new c(3940187606, 3454069534), new c(4118630271, 4000239992), new c(116418474, 1914138554), new c(174292421, 2731055270), new c(289380356, 3203993006), new c(460393269, 320620315), new c(685471733, 587496836), new c(852142971, 1086792851), new c(1017036298, 365543100), new c(1126000580, 2618297676), new c(1288033470, 3409855158), new c(1501505948, 4234509866), new c(1607167915, 987167468), new c(1816402316, 1246189591) + 3928383900), new c(3515267271, 566280711), new c(3940187606, 3454069534), new c(4118630271, 4000239992), new c(116418474, 1914138554), new c(174292421, 2731055270), new c(289380356, 3203993006), new c(460393269, 320620315), new c(685471733, 587496836), new c(852142971, 1086792851), new c(1017036298, 365543100), new c(1126000580, 2618297676), new c(1288033470, 3409855158), new c(1501505948, 4234509866), new c(1607167915, 987167468), new c(1816402316, 1246189591) ], e = "SHA-384" === d ? [new c(3418070365, 3238371032), new c(1654270250, 914150663), - new c(2438529370, 812702999), new c(355462360, 4144912697), new c(1731405415, 4290775857), new c(41048885895, 1750603025), new c(3675008525, 1694076839), new c(1203062813, 3204075428) + new c(2438529370, 812702999), new c(355462360, 4144912697), new c(1731405415, 4290775857), new c(41048885895, 1750603025), new c(3675008525, 1694076839), new c(1203062813, 3204075428) ] : [new c(1779033703, 4089235720), new c(3144134277, 2227873595), new c(1013904242, 4271175723), new c(2773480762, 1595750129), new c(1359893119, 2917565137), new c(2600822924, 725511199), new c(528734635, 4215389547), new c(1541459225, 327033209)]) : n("Unexpected error in SHA-2 implementation"); a[b >>> 5] |= 128 << 24 - b % 32; a[h] = b; @@ -6246,11 +6246,11 @@ e[7] = p(A, e[7]) } "SHA-384" === d ? D = [e[0].a, e[0].b, e[1].a, e[1].b, e[2].a, e[2].b, e[3].a, e[3].b, e[4].a, e[4].b, e[5].a, e[5].b] : "SHA-512" === d ? D = [e[0].a, e[0].b, - e[1].a, e[1].b, e[2].a, e[2].b, e[3].a, e[3].b, e[4].a, e[4].b, e[5].a, e[5].b, e[6].a, e[6].b, e[7].a, e[7].b + e[1].a, e[1].b, e[2].a, e[2].b, e[3].a, e[3].b, e[4].a, e[4].b, e[5].a, e[5].b, e[6].a, e[6].b, e[7].a, e[7].b ] : n("Unexpected error in SHA-2 implementation"); return D } - GLOBAL.jsSHA = function(a, b, d) { + GLOBAL.jsSHA = function (a, b, d) { var h = q, f = q, g = 0, @@ -6260,7 +6260,7 @@ m = "undefined" !== typeof d ? d : 8; 8 === m || 16 === m || n("charSize must be 8 or 16"); "HEX" === b ? (0 !== a.length % 2 && n("srcString of HEX type must be in byte increments"), j = x(a), g = j.binLen, k = j.value) : "ASCII" === b || "TEXT" === b ? (j = u(a, m), g = j.binLen, k = j.value) : "B64" === b ? (j = B(a), g = j.binLen, k = j.value) : n("inputFormat must be HEX, TEXT, ASCII, or B64"); - this.getHash = function(a, b, d) { + this.getHash = function (a, b, d) { var e = q, m = k.slice(), j = ""; @@ -6275,10 +6275,10 @@ n("format must be HEX or B64") } "SHA-384" === - a ? (q === h && (h = $(m, g, a)), j = e(h, G(d))) : "SHA-512" === a ? (q === f && (f = $(m, g, a)), j = e(f, G(d))) : n("Chosen SHA variant is not supported"); + a ? (q === h && (h = $(m, g, a)), j = e(h, G(d))) : "SHA-512" === a ? (q === f && (f = $(m, g, a)), j = e(f, G(d))) : n("Chosen SHA variant is not supported"); return j }; - this.getHMAC = function(a, b, d, e, f) { + this.getHMAC = function (a, b, d, e, f) { var h, l, j, t, p, y = [], z = [], r = q; @@ -6306,13 +6306,13 @@ })(); //coin.js - (function() { + (function () { /* - Coinjs 0.01 beta by OutCast3k{at}gmail.com - A bitcoin framework. - http://github.com/OutCast3k/coinjs or http://coinb.in/coinjs - */ - var coinjs = GLOBAL.coinjs = function() {}; + Coinjs 0.01 beta by OutCast3k{at}gmail.com + A bitcoin framework. + http://github.com/OutCast3k/coinjs or http://coinb.in/coinjs + */ + var coinjs = GLOBAL.coinjs = function () { }; /* public vars */ coinjs.pub = 0x00; @@ -6343,7 +6343,7 @@ /* start of address functions */ /* generate a private and public keypair, with address and WIF address */ - coinjs.newKeys = function(input) { + coinjs.newKeys = function (input) { var privkey = (input) ? Crypto.SHA256(input) : this.newPrivkey(); var pubkey = this.newPubkey(privkey); return { @@ -6356,7 +6356,7 @@ } /* generate a new random private key */ - coinjs.newPrivkey = function() { + coinjs.newPrivkey = function () { var x = GLOBAL.location; x += (GLOBAL.screen.height * GLOBAL.screen.width * GLOBAL.screen.colorDepth); x += coinjs.random(64); @@ -6387,7 +6387,7 @@ } /* generate a public key from a private key */ - coinjs.newPubkey = function(hash) { + coinjs.newPubkey = function (hash) { var privateKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(hash)); var curve = EllipticCurve.getSECCurveByName("secp256k1"); @@ -6413,7 +6413,7 @@ } /* provide a public key and return address */ - coinjs.pubkey2address = function(h, byte) { + coinjs.pubkey2address = function (h, byte) { var r = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(h), { asBytes: true })); @@ -6428,7 +6428,7 @@ } /* provide a scripthash and return address */ - coinjs.scripthash2address = function(h) { + coinjs.scripthash2address = function (h) { var x = Crypto.util.hexToBytes(h); x.unshift(coinjs.pub); var r = x; @@ -6442,7 +6442,7 @@ } /* new multisig address, provide the pubkeys AND required signatures to release the funds */ - coinjs.pubkeys2MultisigAddress = function(pubkeys, required) { + coinjs.pubkeys2MultisigAddress = function (pubkeys, required) { var s = coinjs.script(); s.writeOp(81 + (required * 1) - 1); //OP_1 for (var i = 0; i < pubkeys.length; ++i) { @@ -6478,13 +6478,27 @@ }; } + //Return a Bech32 address for the multisig. Format is same as above + coinjs.pubkeys2MultisigAddressBech32 = function (pubkeys, required) { + var r = coinjs.pubkeys2MultisigAddress(pubkeys, required); + var program = Crypto.SHA256(Crypto.util.hexToBytes(r.redeemScript), { + asBytes: true + }); + var address = coinjs.bech32_encode(coinjs.bech32.hrp, [coinjs.bech32.version].concat(coinjs.bech32_convert(program, 8, 5, true))); + return { + 'address': address, + 'redeemScript': r.redeemScript, + 'size': r.size + }; + } + /* new time locked address, provide the pubkey and time necessary to unlock the funds. when time is greater than 500000000, it should be a unix timestamp (seconds since epoch), otherwise it should be the block height required before this transaction can be released. may throw a string on failure! */ - coinjs.simpleHodlAddress = function(pubkey, checklocktimeverify) { + coinjs.simpleHodlAddress = function (pubkey, checklocktimeverify) { if (checklocktimeverify < 0) { throw "Parameter for OP_CHECKLOCKTIMEVERIFY is negative."; @@ -6524,7 +6538,7 @@ } /* create a new segwit address */ - coinjs.segwitAddress = function(pubkey) { + coinjs.segwitAddress = function (pubkey) { var keyhash = [0x00, 0x14].concat(ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubkey), { asBytes: true }), { @@ -6553,7 +6567,7 @@ } /* create a new segwit bech32 encoded address */ - coinjs.bech32Address = function(pubkey) { + coinjs.bech32Address = function (pubkey) { var program = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubkey), { asBytes: true }), { @@ -6567,8 +6581,20 @@ }; } + coinjs.multisigBech32Address = function (raw_redeemscript) { + var program = Crypto.SHA256(Crypto.util.hexToBytes(raw_redeemscript), { + asBytes: true + }); + var address = coinjs.bech32_encode(coinjs.bech32.hrp, [coinjs.bech32.version].concat(coinjs.bech32_convert(program, 8, 5, true))); + return { + 'address': address, + 'type': 'multisigBech32', + 'redeemscript': Crypto.util.bytesToHex(program) + }; + } + /* extract the redeemscript from a bech32 address */ - coinjs.bech32redeemscript = function(address) { + coinjs.bech32redeemscript = function (address) { var r = false; var decode = coinjs.bech32_decode(address); if (decode) { @@ -6579,7 +6605,7 @@ } /* provide a privkey and return an WIF */ - coinjs.privkey2wif = function(h) { + coinjs.privkey2wif = function (h) { var r = Crypto.util.hexToBytes(h); if (coinjs.compressed == true) { @@ -6598,7 +6624,7 @@ } /* convert a wif key back to a private key */ - coinjs.wif2privkey = function(wif) { + coinjs.wif2privkey = function (wif) { var compressed = false; var decode = coinjs.base58decode(wif); var key = decode.slice(0, decode.length - 4); @@ -6614,7 +6640,7 @@ } /* convert a wif to a pubkey */ - coinjs.wif2pubkey = function(wif) { + coinjs.wif2pubkey = function (wif) { var compressed = coinjs.compressed; var r = coinjs.wif2privkey(wif); coinjs.compressed = r['compressed']; @@ -6627,7 +6653,7 @@ } /* convert a wif to a address */ - coinjs.wif2address = function(wif) { + coinjs.wif2address = function (wif) { var r = coinjs.wif2pubkey(wif); return { 'address': coinjs.pubkey2address(r['pubkey']), @@ -6636,7 +6662,7 @@ } /* decode or validate an address and return the hash */ - coinjs.addressDecode = function(addr) { + coinjs.addressDecode = function (addr) { try { var bytes = coinjs.base58decode(addr); var front = bytes.slice(0, bytes.length - 4); @@ -6658,6 +6684,9 @@ } else if (o.version == coinjs.multisig) { // multisig address o.type = 'multisig'; + } else if (o.version == coinjs.multisigBech32) { // multisigBech32 added + o.type = 'multisigBech32'; + } else if (o.version == coinjs.priv) { // wifkey o.type = 'wifkey'; @@ -6698,11 +6727,16 @@ } } catch (e) { let bech32rs = coinjs.bech32redeemscript(addr); - if (bech32rs) { + if (bech32rs && bech32rs.length == 40) { return { 'type': 'bech32', 'redeemscript': bech32rs }; + } else if (bech32rs && bech32rs.length == 64) { + return { + 'type': 'multisigBech32', + 'redeemscript': bech32rs + }; } else { return false; } @@ -6710,13 +6744,13 @@ } /* retreive the balance from a given address */ - coinjs.addressBalance = function(address, callback) { - coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=bal&address=' + address + '&r=' + securedMathRandom(), callback, "GET"); + coinjs.addressBalance = function (address, callback) { + coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=bal&address=' + address + '&r=' + Math.random(), callback, "GET"); } /* decompress an compressed public key */ - coinjs.pubkeydecompress = function(pubkey) { - if ((typeof(pubkey) == 'string') && pubkey.match(/^[a-f0-9]+$/i)) { + coinjs.pubkeydecompress = function (pubkey) { + if ((typeof (pubkey) == 'string') && pubkey.match(/^[a-f0-9]+$/i)) { var curve = EllipticCurve.getSECCurveByName("secp256k1"); try { var pt = curve.curve.decodePointHex(pubkey); @@ -6735,7 +6769,7 @@ return false; } - coinjs.bech32_polymod = function(values) { + coinjs.bech32_polymod = function (values) { var chk = 1; var BECH32_GENERATOR = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; for (var p = 0; p < values.length; ++p) { @@ -6750,7 +6784,7 @@ return chk; } - coinjs.bech32_hrpExpand = function(hrp) { + coinjs.bech32_hrpExpand = function (hrp) { var ret = []; var p; for (p = 0; p < hrp.length; ++p) { @@ -6763,11 +6797,11 @@ return ret; } - coinjs.bech32_verifyChecksum = function(hrp, data) { + coinjs.bech32_verifyChecksum = function (hrp, data) { return coinjs.bech32_polymod(coinjs.bech32_hrpExpand(hrp).concat(data)) === 1; } - coinjs.bech32_createChecksum = function(hrp, data) { + coinjs.bech32_createChecksum = function (hrp, data) { var values = coinjs.bech32_hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]); var mod = coinjs.bech32_polymod(values) ^ 1; var ret = []; @@ -6777,7 +6811,7 @@ return ret; } - coinjs.bech32_encode = function(hrp, data) { + coinjs.bech32_encode = function (hrp, data) { var combined = data.concat(coinjs.bech32_createChecksum(hrp, data)); var ret = hrp + '1'; for (var p = 0; p < combined.length; ++p) { @@ -6786,7 +6820,7 @@ return ret; } - coinjs.bech32_decode = function(bechString) { + coinjs.bech32_decode = function (bechString) { var p; var has_lower = false; var has_upper = false; @@ -6827,7 +6861,7 @@ }; } - coinjs.bech32_convert = function(data, inBits, outBits, pad) { + coinjs.bech32_convert = function (data, inBits, outBits, pad) { var value = 0; var bits = 0; var maxV = (1 << outBits) - 1; @@ -6855,7 +6889,7 @@ return result; } - coinjs.testdeterministicK = function() { + coinjs.testdeterministicK = function () { // https://github.com/bitpay/bitcore/blob/9a5193d8e94b0bd5b8e7f00038e7c0b935405a03/test/crypto/ecdsa.js // Line 21 and 22 specify digest hash and privkey for the first 2 test vectors. // Line 96-117 tells expected result. @@ -6863,81 +6897,81 @@ var tx = coinjs.transaction(); var test_vectors = [{ - 'message': 'test data', - 'privkey': 'fee0a1f7afebf9d2a5a80c0c98a31c709681cce195cbcd06342b517970c0be1e', - 'k_bad00': 'fcce1de7a9bcd6b2d3defade6afa1913fb9229e3b7ddf4749b55c4848b2a196e', - 'k_bad01': '727fbcb59eb48b1d7d46f95a04991fc512eb9dbf9105628e3aec87428df28fd8', - 'k_bad15': '398f0e2c9f79728f7b3d84d447ac3a86d8b2083c8f234a0ffa9c4043d68bd258' - }, - { - 'message': 'Everything should be made as simple as possible, but not simpler.', - 'privkey': '0000000000000000000000000000000000000000000000000000000000000001', - 'k_bad00': 'ec633bd56a5774a0940cb97e27a9e4e51dc94af737596a0c5cbb3d30332d92a5', - 'k_bad01': 'df55b6d1b5c48184622b0ead41a0e02bfa5ac3ebdb4c34701454e80aabf36f56', - 'k_bad15': 'def007a9a3c2f7c769c75da9d47f2af84075af95cadd1407393dc1e26086ef87' - }, - { - 'message': 'Satoshi Nakamoto', - 'privkey': '0000000000000000000000000000000000000000000000000000000000000002', - 'k_bad00': 'd3edc1b8224e953f6ee05c8bbf7ae228f461030e47caf97cde91430b4607405e', - 'k_bad01': 'f86d8e43c09a6a83953f0ab6d0af59fb7446b4660119902e9967067596b58374', - 'k_bad15': '241d1f57d6cfd2f73b1ada7907b199951f95ef5ad362b13aed84009656e0254a' - }, - { - 'message': 'Diffie Hellman', - 'privkey': '7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f', - 'k_bad00': 'c378a41cb17dce12340788dd3503635f54f894c306d52f6e9bc4b8f18d27afcc', - 'k_bad01': '90756c96fef41152ac9abe08819c4e95f16da2af472880192c69a2b7bac29114', - 'k_bad15': '7b3f53300ab0ccd0f698f4d67db87c44cf3e9e513d9df61137256652b2e94e7c' - }, - { - 'message': 'Japan', - 'privkey': '8080808080808080808080808080808080808080808080808080808080808080', - 'k_bad00': 'f471e61b51d2d8db78f3dae19d973616f57cdc54caaa81c269394b8c34edcf59', - 'k_bad01': '6819d85b9730acc876fdf59e162bf309e9f63dd35550edf20869d23c2f3e6d17', - 'k_bad15': 'd8e8bae3ee330a198d1f5e00ad7c5f9ed7c24c357c0a004322abca5d9cd17847' - }, - { - 'message': 'Bitcoin', - 'privkey': 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140', - 'k_bad00': '36c848ffb2cbecc5422c33a994955b807665317c1ce2a0f59c689321aaa631cc', - 'k_bad01': '4ed8de1ec952a4f5b3bd79d1ff96446bcd45cabb00fc6ca127183e14671bcb85', - 'k_bad15': '56b6f47babc1662c011d3b1f93aa51a6e9b5f6512e9f2e16821a238d450a31f8' - }, - { - 'message': 'i2FLPP8WEus5WPjpoHwheXOMSobUJVaZM1JPMQZq', - 'privkey': 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140', - 'k_bad00': '6e9b434fcc6bbb081a0463c094356b47d62d7efae7da9c518ed7bac23f4e2ed6', - 'k_bad01': 'ae5323ae338d6117ce8520a43b92eacd2ea1312ae514d53d8e34010154c593bb', - 'k_bad15': '3eaa1b61d1b8ab2f1ca71219c399f2b8b3defa624719f1e96fe3957628c2c4ea' - }, - { - 'message': 'lEE55EJNP7aLrMtjkeJKKux4Yg0E8E1SAJnWTCEh', - 'privkey': '3881e5286abc580bb6139fe8e83d7c8271c6fe5e5c2d640c1f0ed0e1ee37edc9', - 'k_bad00': '5b606665a16da29cc1c5411d744ab554640479dd8abd3c04ff23bd6b302e7034', - 'k_bad01': 'f8b25263152c042807c992eacd2ac2cc5790d1e9957c394f77ea368e3d9923bd', - 'k_bad15': 'ea624578f7e7964ac1d84adb5b5087dd14f0ee78b49072aa19051cc15dab6f33' - }, - { - 'message': '2SaVPvhxkAPrayIVKcsoQO5DKA8Uv5X/esZFlf+y', - 'privkey': '7259dff07922de7f9c4c5720d68c9745e230b32508c497dd24cb95ef18856631', - 'k_bad00': '3ab6c19ab5d3aea6aa0c6da37516b1d6e28e3985019b3adb388714e8f536686b', - 'k_bad01': '19af21b05004b0ce9cdca82458a371a9d2cf0dc35a813108c557b551c08eb52e', - 'k_bad15': '117a32665fca1b7137a91c4739ac5719fec0cf2e146f40f8e7c21b45a07ebc6a' - }, - { - 'message': '00A0OwO2THi7j5Z/jp0FmN6nn7N/DQd6eBnCS+/b', - 'privkey': '0d6ea45d62b334777d6995052965c795a4f8506044b4fd7dc59c15656a28f7aa', - 'k_bad00': '79487de0c8799158294d94c0eb92ee4b567e4dc7ca18addc86e49d31ce1d2db6', - 'k_bad01': '9561d2401164a48a8f600882753b3105ebdd35e2358f4f808c4f549c91490009', - 'k_bad15': 'b0d273634129ff4dbdf0df317d4062a1dbc58818f88878ffdb4ec511c77976c0' - } + 'message': 'test data', + 'privkey': 'fee0a1f7afebf9d2a5a80c0c98a31c709681cce195cbcd06342b517970c0be1e', + 'k_bad00': 'fcce1de7a9bcd6b2d3defade6afa1913fb9229e3b7ddf4749b55c4848b2a196e', + 'k_bad01': '727fbcb59eb48b1d7d46f95a04991fc512eb9dbf9105628e3aec87428df28fd8', + 'k_bad15': '398f0e2c9f79728f7b3d84d447ac3a86d8b2083c8f234a0ffa9c4043d68bd258' + }, + { + 'message': 'Everything should be made as simple as possible, but not simpler.', + 'privkey': '0000000000000000000000000000000000000000000000000000000000000001', + 'k_bad00': 'ec633bd56a5774a0940cb97e27a9e4e51dc94af737596a0c5cbb3d30332d92a5', + 'k_bad01': 'df55b6d1b5c48184622b0ead41a0e02bfa5ac3ebdb4c34701454e80aabf36f56', + 'k_bad15': 'def007a9a3c2f7c769c75da9d47f2af84075af95cadd1407393dc1e26086ef87' + }, + { + 'message': 'Satoshi Nakamoto', + 'privkey': '0000000000000000000000000000000000000000000000000000000000000002', + 'k_bad00': 'd3edc1b8224e953f6ee05c8bbf7ae228f461030e47caf97cde91430b4607405e', + 'k_bad01': 'f86d8e43c09a6a83953f0ab6d0af59fb7446b4660119902e9967067596b58374', + 'k_bad15': '241d1f57d6cfd2f73b1ada7907b199951f95ef5ad362b13aed84009656e0254a' + }, + { + 'message': 'Diffie Hellman', + 'privkey': '7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f', + 'k_bad00': 'c378a41cb17dce12340788dd3503635f54f894c306d52f6e9bc4b8f18d27afcc', + 'k_bad01': '90756c96fef41152ac9abe08819c4e95f16da2af472880192c69a2b7bac29114', + 'k_bad15': '7b3f53300ab0ccd0f698f4d67db87c44cf3e9e513d9df61137256652b2e94e7c' + }, + { + 'message': 'Japan', + 'privkey': '8080808080808080808080808080808080808080808080808080808080808080', + 'k_bad00': 'f471e61b51d2d8db78f3dae19d973616f57cdc54caaa81c269394b8c34edcf59', + 'k_bad01': '6819d85b9730acc876fdf59e162bf309e9f63dd35550edf20869d23c2f3e6d17', + 'k_bad15': 'd8e8bae3ee330a198d1f5e00ad7c5f9ed7c24c357c0a004322abca5d9cd17847' + }, + { + 'message': 'Bitcoin', + 'privkey': 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140', + 'k_bad00': '36c848ffb2cbecc5422c33a994955b807665317c1ce2a0f59c689321aaa631cc', + 'k_bad01': '4ed8de1ec952a4f5b3bd79d1ff96446bcd45cabb00fc6ca127183e14671bcb85', + 'k_bad15': '56b6f47babc1662c011d3b1f93aa51a6e9b5f6512e9f2e16821a238d450a31f8' + }, + { + 'message': 'i2FLPP8WEus5WPjpoHwheXOMSobUJVaZM1JPMQZq', + 'privkey': 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140', + 'k_bad00': '6e9b434fcc6bbb081a0463c094356b47d62d7efae7da9c518ed7bac23f4e2ed6', + 'k_bad01': 'ae5323ae338d6117ce8520a43b92eacd2ea1312ae514d53d8e34010154c593bb', + 'k_bad15': '3eaa1b61d1b8ab2f1ca71219c399f2b8b3defa624719f1e96fe3957628c2c4ea' + }, + { + 'message': 'lEE55EJNP7aLrMtjkeJKKux4Yg0E8E1SAJnWTCEh', + 'privkey': '3881e5286abc580bb6139fe8e83d7c8271c6fe5e5c2d640c1f0ed0e1ee37edc9', + 'k_bad00': '5b606665a16da29cc1c5411d744ab554640479dd8abd3c04ff23bd6b302e7034', + 'k_bad01': 'f8b25263152c042807c992eacd2ac2cc5790d1e9957c394f77ea368e3d9923bd', + 'k_bad15': 'ea624578f7e7964ac1d84adb5b5087dd14f0ee78b49072aa19051cc15dab6f33' + }, + { + 'message': '2SaVPvhxkAPrayIVKcsoQO5DKA8Uv5X/esZFlf+y', + 'privkey': '7259dff07922de7f9c4c5720d68c9745e230b32508c497dd24cb95ef18856631', + 'k_bad00': '3ab6c19ab5d3aea6aa0c6da37516b1d6e28e3985019b3adb388714e8f536686b', + 'k_bad01': '19af21b05004b0ce9cdca82458a371a9d2cf0dc35a813108c557b551c08eb52e', + 'k_bad15': '117a32665fca1b7137a91c4739ac5719fec0cf2e146f40f8e7c21b45a07ebc6a' + }, + { + 'message': '00A0OwO2THi7j5Z/jp0FmN6nn7N/DQd6eBnCS+/b', + 'privkey': '0d6ea45d62b334777d6995052965c795a4f8506044b4fd7dc59c15656a28f7aa', + 'k_bad00': '79487de0c8799158294d94c0eb92ee4b567e4dc7ca18addc86e49d31ce1d2db6', + 'k_bad01': '9561d2401164a48a8f600882753b3105ebdd35e2358f4f808c4f549c91490009', + 'k_bad15': 'b0d273634129ff4dbdf0df317d4062a1dbc58818f88878ffdb4ec511c77976c0' + } ]; var result_txt = '\n----------------------\nResults\n----------------------\n\n'; for (i = 0; i < test_vectors.length; i++) { - var hash = Crypto.SHA256(test_vectors[i]['message'].split('').map(function(c) { + var hash = Crypto.SHA256(test_vectors[i]['message'].split('').map(function (c) { return c.charCodeAt(0); }), { asBytes: true @@ -6973,17 +7007,17 @@ }; /* start of hd functions, thanks bip32.org */ - coinjs.hd = function(data) { + coinjs.hd = function (data) { var r = {}; /* some hd value parsing */ - r.parse = function() { + r.parse = function () { var bytes = []; // some quick validation - if (typeof(data) == 'string') { + if (typeof (data) == 'string') { var decoded = coinjs.base58decode(data); if (decoded.length == 82) { var checksum = decoded.slice(78, 82); @@ -7044,7 +7078,7 @@ } // extend prv/pub key - r.extend = function() { + r.extend = function () { var hd = coinjs.hd(); return hd.make({ 'depth': (this.depth * 1) + 1, @@ -7057,7 +7091,7 @@ } // derive from path - r.derive_path = function(path) { + r.derive_path = function (path) { if (path == 'm' || path == 'M' || path == 'm\'' || path == 'M\'') return this; @@ -7085,7 +7119,7 @@ } // derive key from index - r.derive = function(i) { + r.derive = function (i) { i = (i) ? i : 0; var blob = (Crypto.util.hexToBytes(this.keys.pubkey)).concat(coinjs.numToBytes(i, 4).reverse()); @@ -7153,7 +7187,7 @@ } // make a master hd xprv/xpub - r.master = function(pass) { + r.master = function (pass) { var seed = (pass) ? Crypto.SHA256(pass) : coinjs.newPrivkey(); var hasher = new jsSHA(seed, 'HEX'); var I = hasher.getHMAC("Bitcoin seed", "TEXT", "SHA-512", "HEX"); @@ -7173,7 +7207,7 @@ } // encode data to a base58 string - r.make = function(data) { // { (int) depth, (array) parent_fingerprint, (int) child_index, (byte array) chain_code, (hex str) privkey, (hex str) pubkey} + r.make = function (data) { // { (int) depth, (array) parent_fingerprint, (int) child_index, (byte array) chain_code, (hex str) privkey, (hex str) pubkey} var k = []; //depth @@ -7228,7 +7262,7 @@ /* start of script functions */ - coinjs.script = function(data) { + coinjs.script = function (data) { var r = {}; if (!data) { @@ -7244,7 +7278,7 @@ } /* parse buffer array */ - r.parse = function() { + r.parse = function () { var self = this; r.chunks = []; @@ -7286,7 +7320,7 @@ }; /* decode the redeemscript of a multisignature transaction */ - r.decodeRedeemScript = function(script) { + r.decodeRedeemScript = function (script) { var r = false; try { var s = coinjs.script(Crypto.util.hexToBytes(script)); @@ -7328,11 +7362,39 @@ return r; } + /* decode the redeemscript of a multisignature transaction for Bech32*/ + r.decodeRedeemScriptBech32 = function (script) { + var r = false; + try { + var s = coinjs.script(Crypto.util.hexToBytes(script)); + if ((s.chunks.length >= 3) && s.chunks[s.chunks.length - 1] == 174) { //OP_CHECKMULTISIG + r = {}; + r.signaturesRequired = s.chunks[0] - 80; + var pubkeys = []; + for (var i = 1; i < s.chunks.length - 2; i++) { + pubkeys.push(Crypto.util.bytesToHex(s.chunks[i])); + } + r.pubkeys = pubkeys; + var multi = coinjs.pubkeys2MultisigAddressBech32(pubkeys, r.signaturesRequired); + r.address = multi['address']; + r.type = 'multisig__'; // using __ for now to differentiat from the other object .type == "multisig" + var rs = Crypto.util.bytesToHex(s.buffer); + r.redeemscript = rs; + + } + + } catch (e) { + // console.log(e); + r = false; + } + return r; + } + /* create output script to spend */ - r.spendToScript = function(address) { + r.spendToScript = function (address) { var addr = coinjs.addressDecode(address); var s = coinjs.script(); - if (addr.type == "bech32") { + if (addr.type == "bech32" || addr.type == "multisigBech32") { s.writeOp(0); s.writeBytes(Crypto.util.hexToBytes(addr.redeemscript)); } else if (addr.version == coinjs.multisig) { // multisig address @@ -7350,7 +7412,7 @@ } /* geneate a (script) pubkey hash of the address - used for when signing */ - r.pubkeyHash = function(address) { + r.pubkeyHash = function (address) { var addr = coinjs.addressDecode(address); var s = coinjs.script(); s.writeOp(118); //OP_DUP @@ -7362,14 +7424,14 @@ } /* write to buffer */ - r.writeOp = function(op) { + r.writeOp = function (op) { this.buffer.push(op); this.chunks.push(op); return true; } /* write bytes to buffer */ - r.writeBytes = function(data) { + r.writeBytes = function (data) { if (data.length < 76) { //OP_PUSHDATA1 this.buffer.push(data.length); } else if (data.length <= 0xff) { @@ -7398,7 +7460,7 @@ /* start of transaction functions */ /* create a new transaction object */ - coinjs.transaction = function() { + coinjs.transaction = function () { var r = {}; r.version = 1; @@ -7410,7 +7472,7 @@ r.block = null; /* add an input to a transaction */ - r.addinput = function(txid, index, script, sequence) { + r.addinput = function (txid, index, script, sequence) { var o = {}; o.outpoint = { 'hash': txid, @@ -7422,7 +7484,7 @@ } /* add an output to a transaction */ - r.addoutput = function(address, value) { + r.addoutput = function (address, value) { var o = {}; o.value = new BigInteger('' + Math.round((value * 1) * 1e8), 10); var s = coinjs.script(); @@ -7432,7 +7494,7 @@ } /* add two outputs for stealth addresses to a transaction */ - r.addstealth = function(stealth, value) { + r.addstealth = function (stealth, value) { var ephemeralKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(coinjs.newPrivkey())); var curve = EllipticCurve.getSECCurveByName("secp256k1"); @@ -7474,7 +7536,7 @@ } /* add data to a transaction */ - r.adddata = function(data) { + r.adddata = function (data) { var r = false; if (((data.match(/^[a-f0-9]+$/gi)) && data.length < 160) && (data.length % 2) == 0) { var s = coinjs.script(); @@ -7489,19 +7551,19 @@ } /* list unspent transactions */ - r.listUnspent = function(address, callback) { - coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=unspent&address=' + address + '&r=' + securedMathRandom(), callback, "GET"); + r.listUnspent = function (address, callback) { + coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=unspent&address=' + address + '&r=' + Math.random(), callback, "GET"); } /* list transaction data */ - r.getTransaction = function(txid, callback) { - coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=bitcoin&request=gettransaction&txid=' + txid + '&r=' + securedMathRandom(), callback, "GET"); + r.getTransaction = function (txid, callback) { + coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=bitcoin&request=gettransaction&txid=' + txid + '&r=' + Math.random(), callback, "GET"); } /* add unspent to transaction */ - r.addUnspent = function(address, callback, script, segwit, sequence) { + r.addUnspent = function (address, callback, script, segwit, sequence) { var self = this; - this.listUnspent(address, function(data) { + this.listUnspent(address, function (data) { var s = coinjs.script(); var value = 0; var total = 0; @@ -7525,7 +7587,7 @@ var n = u.getElementsByTagName("tx_output_n")[0].childNodes[0].nodeValue; var scr = script || u.getElementsByTagName("script")[0].childNodes[0].nodeValue; - if (segwit) { + if (segwit) { //also for MULTISIG_BECH32 (p2wsh-multisig)(script = raw_redeemscript; for p2wsh-multisig) /* this is a small hack to include the value with the redeemscript to make the signing procedure smoother. It is not standard and removed during the signing procedure. */ @@ -7554,23 +7616,23 @@ } /* add unspent and sign */ - r.addUnspentAndSign = function(wif, callback) { + r.addUnspentAndSign = function (wif, callback) { var self = this; var address = coinjs.wif2address(wif); - self.addUnspent(address['address'], function(data) { + self.addUnspent(address['address'], function (data) { self.sign(wif); return callback(data); }); } /* broadcast a transaction */ - r.broadcast = function(callback, txhex) { + r.broadcast = function (callback, txhex) { var tx = txhex || this.serialize(); coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=bitcoin&request=sendrawtransaction', callback, "POST", ["rawtx=" + tx]); } /* generate the transaction hash to sign from a transaction input */ - r.transactionHash = function(index, sigHashType) { + r.transactionHash = function (index, sigHashType) { var clone = coinjs.clone(this); var shType = sigHashType || 1; @@ -7588,7 +7650,7 @@ if ((clone.ins) && clone.ins[index]) { /* SIGHASH : For more info on sig hashs see https://en.bitcoin.it/wiki/OP_CHECKSIG - and https://bitcoin.org/en/developer-guide#signature-hash-type */ + and https://bitcoin.org/en/developer-guide#signature-hash-type */ if (shType == 1) { //SIGHASH_ALL 0x01 @@ -7654,7 +7716,7 @@ } /* generate a segwit transaction hash to sign from a transaction input */ - r.transactionHashSegWitV0 = function(index, sigHashType) { + r.transactionHashSegWitV0 = function (index, sigHashType) { /* Notice: coinb.in by default, deals with segwit transactions in a non-standard way. Segwit transactions require that input values are included in the transaction hash. @@ -7664,7 +7726,7 @@ // start redeem script check var extract = this.extractScriptKey(index); - if (extract['type'] != 'segwit') { + if (extract['type'] != 'segwit' && extract['type'] != 'multisig_bech32') { return { 'result': 0, 'fail': 'redeemscript', @@ -7693,6 +7755,8 @@ scriptcode = scriptcode.slice(1); scriptcode.unshift(25, 118, 169); scriptcode.push(136, 172); + } else if (scriptcode[0] > 80) { + scriptcode.unshift(scriptcode.length) } var value = coinjs.numToBytes(extract['value'], 8); @@ -7784,7 +7848,7 @@ } /* extract the scriptSig, used in the transactionHash() function */ - r.extractScriptKey = function(index) { + r.extractScriptKey = function (index) { if (this.ins[index]) { if ((this.ins[index].script.chunks.length == 5) && this.ins[index].script.chunks[4] == 172 && coinjs.isArray(this.ins[index].script.chunks[2])) { //OP_CHECKSIG // regular scriptPubkey (not signed) @@ -7855,11 +7919,26 @@ 'signatures': 0, 'script': Crypto.util.bytesToHex(this.ins[index].script.buffer) }; + } else if (this.ins[index].script.chunks.length == 3 && this.ins[index].script.chunks[0][0] >= 80 && this.ins[index].script.chunks[0][this.ins[index].script.chunks[0].length - 1] == 174 && this.ins[index].script.chunks[1] == 0) { //OP_CHECKMULTISIG_BECH32 + // multisig bech32 script + let last_index = this.ins[index].script.chunks.length - 1; + var value = -1; + if (last_index >= 2 && this.ins[index].script.chunks[last_index].length == 8) { + value = coinjs.bytesToNum(this.ins[index].script.chunks[last_index]); // value found encoded in transaction (THIS IS NON STANDARD) + } + var sigcount = (!this.witness[index]) ? 0 : this.witness[index].length - 2; + return { + 'type': 'multisig_bech32', + 'signed': 'false', + 'signatures': sigcount, + 'script': Crypto.util.bytesToHex(this.ins[index].script.chunks[0]), + 'value': value + }; } else if (this.ins[index].script.chunks.length == 0) { // empty //bech32 witness check - var signed = ((this.witness[index]) && this.witness[index].length == 2) ? 'true' : 'false'; - var sigs = (signed == 'true') ? 1 : 0; + var signed = ((this.witness[index]) && this.witness[index].length >= 2) ? 'true' : 'false'; + var sigs = (signed == 'true') ? (!this.witness[index][0] ? this.witness[index].length - 2 : 1) : 0; return { 'type': 'empty', 'signed': signed, @@ -7881,7 +7960,7 @@ } /* generate a signature from a transaction hash */ - r.transactionSig = function(index, wif, sigHashType, txhash) { + r.transactionSig = function (index, wif, sigHashType, txhash) { function serializeSig(r, s) { var rBa = r.toByteArraySigned(); @@ -7937,7 +8016,7 @@ } // https://tools.ietf.org/html/rfc6979#section-3.2 - r.deterministicK = function(wif, hash, badrs) { + r.deterministicK = function (wif, hash, badrs) { // if r or s were invalid when this function was used in signing, // we do not want to actually compute r, s here for efficiency, so, // we can increment badrs. explained at end of RFC 6979 section 3.2 @@ -8015,7 +8094,7 @@ }; /* sign a "standard" input */ - r.signinput = function(index, wif, sigHashType) { + r.signinput = function (index, wif, sigHashType) { var key = coinjs.wif2pubkey(wif); var shType = sigHashType || 1; var signature = this.transactionSig(index, wif, shType); @@ -8027,7 +8106,7 @@ } /* signs a time locked / hodl input */ - r.signhodl = function(index, wif, sigHashType) { + r.signhodl = function (index, wif, sigHashType) { var shType = sigHashType || 1; var signature = this.transactionSig(index, wif, shType); var redeemScript = this.ins[index].script.buffer @@ -8038,8 +8117,73 @@ return true; } + r.signmultisig_bech32 = function (index, wif, sigHashType) { + + function scriptListPubkey(redeemScript) { + var r = {}; + for (var i = 1; i < redeemScript.chunks.length - 2; i++) { + r[i] = Crypto.util.hexToBytes(coinjs.pubkeydecompress(Crypto.util.bytesToHex(redeemScript.chunks[i]))); + } + return r; + } + + function scriptListSigs(sigList) { + let r = {}; + var c = 0; + if (Array.isArray(sigList)) { + for (let i = 1; i < sigList.length - 1; i++) { + c++; + r[c] = Crypto.util.hexToBytes(sigList[i]); + } + } + return r; + } + + var redeemScript = Crypto.util.bytesToHex(this.ins[index].script.chunks[0]); //redeemScript + + if (!coinjs.isArray(this.witness)) { + this.witness = new Array(this.ins.length); + this.witness.fill([]); + } + + var pubkeyList = scriptListPubkey(coinjs.script(redeemScript)); + var sigsList = scriptListSigs(this.witness[index]); + let decode_rs = coinjs.script().decodeRedeemScriptBech32(redeemScript); + + var shType = sigHashType || 1; + var txhash = this.transactionHashSegWitV0(index, shType); + + if (txhash.result == 1 && decode_rs.pubkeys.includes(coinjs.wif2pubkey(wif)['pubkey'])) { + + var segwitHash = Crypto.util.hexToBytes(txhash.hash); + var signature = Crypto.util.hexToBytes(this.transactionSig(index, wif, shType, segwitHash)); //CHECK THIS + + sigsList[coinjs.countObject(sigsList) + 1] = signature; + + var w = []; + + for (let x in pubkeyList) { + for (let y in sigsList) { + var sighash = this.transactionHashSegWitV0(index, sigsList[y].slice(-1)[0] * 1).hash + sighash = Crypto.util.hexToBytes(sighash); + if (coinjs.verifySignature(sighash, sigsList[y], pubkeyList[x])) { + w.push((Crypto.util.bytesToHex(sigsList[y]))) + } + } + } + + // when enough signatures collected, remove any non standard data we store, i.e. input value + if (w.length >= decode_rs.signaturesRequired) { + this.ins[index].script = coinjs.script(); + } + w.unshift(0); + w.push(redeemScript); + this.witness[index] = w; + } + } + /* sign a multisig input */ - r.signmultisig = function(index, wif, sigHashType) { + r.signmultisig = function (index, wif, sigHashType) { function scriptListPubkey(redeemScript) { var r = {}; @@ -8094,7 +8238,7 @@ } /* sign segwit input */ - r.signsegwit = function(index, wif, sigHashType) { + r.signsegwit = function (index, wif, sigHashType) { var shType = sigHashType || 1; var wif2 = coinjs.wif2pubkey(wif); @@ -8169,7 +8313,7 @@ } /* sign inputs */ - r.sign = function(wif, sigHashType) { + r.sign = function (wif, sigHashType) { var shType = sigHashType || 1; for (var i = 0; i < this.ins.length; i++) { var d = this.extractScriptKey(i); @@ -8187,6 +8331,9 @@ } else if (d['type'] == 'multisig') { this.signmultisig(i, wif, shType); + } else if (d['type'] == 'multisig_bech32' && d['signed'] == "false") { + this.signmultisig_bech32(i, wif, shType); + } else if (d['type'] == 'segwit') { this.signsegwit(i, wif, shType); @@ -8198,7 +8345,7 @@ } /* serialize a transaction */ - r.serialize = function() { + r.serialize = function () { var buffer = []; buffer = buffer.concat(coinjs.numToBytes(parseInt(this.version), 4)); @@ -8240,8 +8387,65 @@ return Crypto.util.bytesToHex(buffer); } + //Utility funtion added to directly compute signatures without transaction index + r.transactionSigNoIndex = function (wif, sigHashType, txhash) { + + function serializeSig(r, s) { + var rBa = r.toByteArraySigned(); + var sBa = s.toByteArraySigned(); + + var sequence = []; + sequence.push(0x02); // INTEGER + sequence.push(rBa.length); + sequence = sequence.concat(rBa); + + sequence.push(0x02); // INTEGER + sequence.push(sBa.length); + sequence = sequence.concat(sBa); + + sequence.unshift(sequence.length); + sequence.unshift(0x30); // SEQUENCE + + return sequence; + } + + var shType = sigHashType || 1; + var hash = Crypto.util.hexToBytes(txhash); + + if (hash) { + var curve = EllipticCurve.getSECCurveByName("secp256k1"); + var key = coinjs.wif2privkey(wif); + var priv = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(key['privkey'])); + var n = curve.getN(); + var e = BigInteger.fromByteArrayUnsigned(hash); + + var badrs = 0 + do { + var k = this.deterministicK(wif, hash, badrs); + var G = curve.getG(); + var Q = G.multiply(k); + var r = Q.getX().toBigInteger().mod(n); + var s = k.modInverse(n).multiply(e.add(priv.multiply(r))).mod(n); + badrs++ + } while (r.compareTo(BigInteger.ZERO) <= 0 || s.compareTo(BigInteger.ZERO) <= 0); + + // Force lower s values per BIP62 + var halfn = n.shiftRight(1); + if (s.compareTo(halfn) > 0) { + s = n.subtract(s); + }; + + var sig = serializeSig(r, s); + sig.push(parseInt(shType, 10)); + + return Crypto.util.bytesToHex(sig); + } else { + return false; + } + } + /* deserialize a transaction */ - r.deserialize = function(buffer) { + r.deserialize = function (buffer) { if (typeof buffer == "string") { buffer = Crypto.util.hexToBytes(buffer) } @@ -8249,13 +8453,13 @@ var pos = 0; var witness = false; - var readAsInt = function(bytes) { + var readAsInt = function (bytes) { if (bytes == 0) return 0; pos++; return buffer[pos - 1] + readAsInt(bytes - 1) * 256; } - var readVarInt = function() { + var readVarInt = function () { pos++; if (buffer[pos - 1] < 253) { return buffer[pos - 1]; @@ -8263,12 +8467,12 @@ return readAsInt(buffer[pos - 1] - 251); } - var readBytes = function(bytes) { + var readBytes = function (bytes) { pos += bytes; return buffer.slice(pos - bytes, pos); } - var readVarString = function() { + var readVarString = function () { var size = readVarInt(); return readBytes(size); } @@ -8322,7 +8526,7 @@ return obj; } - r.size = function() { + r.size = function () { return ((this.serialize()).length / 2).toFixed(0); } @@ -8331,7 +8535,7 @@ /* start of signature vertification functions */ - coinjs.verifySignature = function(hash, sig, pubkey) { + coinjs.verifySignature = function (hash, sig, pubkey) { function parseSig(sig) { var cursor; @@ -8386,7 +8590,7 @@ return coinjs.verifySignatureRaw(e, r, s, Q); } - coinjs.verifySignatureRaw = function(e, r, s, Q) { + coinjs.verifySignatureRaw = function (e, r, s, Q) { var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); var n = ecparams.getN(); var G = ecparams.getG(); @@ -8412,7 +8616,7 @@ /* start of privates functions */ /* base58 encode function */ - coinjs.base58encode = function(buffer) { + coinjs.base58encode = function (buffer) { var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; var base = BigInteger.valueOf(58); @@ -8435,7 +8639,7 @@ } /* base58 decode function */ - coinjs.base58decode = function(buffer) { + coinjs.base58decode = function (buffer) { var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; var base = BigInteger.valueOf(58); var validRegex = /^[1-9A-HJ-NP-Za-km-z]+$/; @@ -8459,7 +8663,7 @@ } /* raw ajax function to avoid needing bigger frame works like jquery, mootools etc */ - coinjs.ajax = function(u, f, m, a) { + coinjs.ajax = function (u, f, m, a) { var x = false; try { x = new ActiveXObject('Msxml2.XMLHTTP') @@ -8476,7 +8680,7 @@ } x.open(m, u, true); - x.onreadystatechange = function() { + x.onreadystatechange = function () { if ((x.readyState == 4) && f) f(x.responseText); }; @@ -8489,8 +8693,8 @@ } /* clone an object */ - coinjs.clone = function(obj) { - if (obj == null || typeof(obj) != 'object') return obj; + coinjs.clone = function (obj) { + if (obj == null || typeof (obj) != 'object') return obj; var temp = new obj.constructor(); for (var key in obj) { @@ -8501,7 +8705,7 @@ return temp; } - coinjs.numToBytes = function(num, bytes) { + coinjs.numToBytes = function (num, bytes) { if (typeof bytes === "undefined") bytes = 8; if (bytes == 0) { return []; @@ -8515,13 +8719,13 @@ function scriptNumSize(i) { return i > 0x7fffffff ? 5 : i > 0x7fffff ? 4 : - i > 0x7fff ? 3 : - i > 0x7f ? 2 : - i > 0x00 ? 1 : - 0; + i > 0x7fff ? 3 : + i > 0x7f ? 2 : + i > 0x00 ? 1 : + 0; } - coinjs.numToScriptNumBytes = function(_number) { + coinjs.numToScriptNumBytes = function (_number) { var value = Math.abs(_number); var size = scriptNumSize(value); var result = []; @@ -8539,7 +8743,7 @@ return result; } - coinjs.numToVarInt = function(num) { + coinjs.numToVarInt = function (num) { if (num < 253) { return [num]; } else if (num < 65536) { @@ -8551,12 +8755,12 @@ } } - coinjs.bytesToNum = function(bytes) { + coinjs.bytesToNum = function (bytes) { if (bytes.length == 0) return 0; else return bytes[0] + 256 * coinjs.bytesToNum(bytes.slice(1)); } - coinjs.uint = function(f, size) { + coinjs.uint = function (f, size) { if (f.length < size) throw new Error("not enough data"); var n = 0; @@ -8567,11 +8771,11 @@ return n; } - coinjs.isArray = function(o) { + coinjs.isArray = function (o) { return Object.prototype.toString.call(o) === '[object Array]'; } - coinjs.countObject = function(obj) { + coinjs.countObject = function (obj) { var count = 0; var i; for (i in obj) { @@ -8582,12 +8786,116 @@ return count; } - coinjs.random = function(length) { + //Nine utility functions added for generating transaction hashes and verification of signatures + coinjs.changeEndianness = (string) => { + const result = []; + let len = string.length - 2; + while (len >= 0) { + result.push(string.substr(len, 2)); + len -= 2; + } + return result.join(''); + } + + coinjs.getTransactionHash = function (transaction_in_hex, changeOutputEndianess) { + var x1, x2, x3, x4, x5; + x1 = Crypto.util.hexToBytes(transaction_in_hex); + x2 = Crypto.SHA256(x1); + x3 = Crypto.util.hexToBytes(x2); + x4 = Crypto.SHA256(x3); + x5 = coinjs.changeEndianness(x4); + if (changeOutputEndianess == true) { x5 = x5 } else if ((typeof changeOutputEndianess == 'undefined') || (changeOutputEndianess == false)) { x5 = x4 }; + return x5; + } + + coinjs.compressedToUncompressed = function (compressed) { + var t1, t2; + var curve = EllipticCurve.getSECCurveByName("secp256k1"); + t1 = curve.curve.decodePointHex(compressed); + t2 = curve.curve.encodePointHex(t1); + return t2; + } + + coinjs.uncompressedToCompressed = function (uncompressed) { + var t1, t2, t3; + t1 = uncompressed.charAt(uncompressed.length - 1) + t2 = parseInt(t1, 10); + //Check if the last digit is odd + if (t2 % 2 == 1) { t3 = "03"; } else { t3 = "02" }; + return t3 + uncompressed.substr(2, 64); + } + + coinjs.verifySignatureHex = function (hashHex, sigHex, pubHexCompressed) { + var h1, s1, p1, p2; + h1 = Crypto.util.hexToBytes(hashHex); + s1 = Crypto.util.hexToBytes(sigHex); + p1 = coinjs.compressedToUncompressed(pubHexCompressed); + p2 = Crypto.util.hexToBytes(p1); + + return coinjs.verifySignature(h1, s1, p2); + } + + coinjs.generateBitcoinSignature = function (private_key, hash, sighash_type_int = 1) { + var wif, tx1; + if (private_key.length < 60) { wif = private_key } else { wif = coinjs.privkey2wif(private_key) }; + tx1 = coinjs.transaction(); + return tx1.transactionSigNoIndex(wif, sighash_type_int, hash); + } + + coinjs.dSHA256 = function (data) { + var t1, t2, t3; + t1 = Crypto.SHA256(Crypto.util.hexToBytes(data)); + t2 = Crypto.util.hexToBytes(t1); + t3 = Crypto.SHA256(t2); + return t3; + } + + coinjs.fromBitcoinAmountFormat = function (data) { + var x1, x2, x3; + x1 = coinjs.changeEndianness(data); + x2 = parseInt(x1, 16); + x3 = x2 / (10 ** 8); + return x3; + } + + coinjs.toBitcoinAmountFormat = function (countBitcoin) { + var t2, t3, t4, t5; + t2 = countBitcoin * 10 ** 8; + t3 = t2.toString(16); + t4 = coinjs.changeEndianness(t3); + t5 = t4.padEnd(16, "0"); + return t5; + } + + coinjs.scriptcodeCreatorBasic = function (scriptpubkey) { + var t1, t2, t3, t4; + if (scriptpubkey.substr(0, 4) == "0014") { + //Scriptpubkey case + t1 = scriptpubkey.slice(2); + t2 = "1976a9" + t1 + "88ac"; + } else { + //Redeemscript case + t3 = (scriptpubkey.length) / 2; + t4 = t3.toString(16); + t2 = t4 + scriptpubkey; + } + return t2; + } + + coinjs.ripemd160sha256 = function (data) { + var t1, t2; + + t1 = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(data), { asBytes: true }), { asBytes: true }); + t2 = Crypto.util.bytesToHex(t1) + return t2; + } + + coinjs.random = function (length) { var r = ""; var l = length || 25; var chars = "!$%^&*()_+{}:@~?><|\./;'#][=-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; for (let x = 0; x < l; x++) { - r += chars.charAt(Math.floor(securedMathRandom() * 62)); + r += chars.charAt(Math.floor(Math.random() * 62)); } return r; } @@ -8595,7 +8903,7 @@ })(); //secrets.js - (function() { + (function () { //Shamir Secret Share by Alexander Stetsyuk - released under MIT License var SecretShare = GLOBAL.shamirSecretShare = {}; @@ -8623,7 +8931,7 @@ var config = {}; /** @expose **/ - SecretShare.getConfig = function() { + SecretShare.getConfig = function () { return { 'bits': config.bits, 'unsafePRNG': config.unsafePRNG @@ -8632,7 +8940,7 @@ function init(bits) { if (bits && (typeof bits !== 'number' || bits % 1 !== 0 || bits < defaults.minBits || bits > - defaults.maxBits)) { + defaults.maxBits)) { throw new Error('Number of bits must be an integer between ' + defaults.minBits + ' and ' + defaults.maxBits + ', inclusive.') } @@ -8695,7 +9003,7 @@ // node.js crypto.randomBytes() if (typeof require === 'function') { - return function(bits) { + return function (bits) { var bytes = Math.ceil(bits / 8), str = null; @@ -8709,7 +9017,7 @@ // browsers with window.crypto.getRandomValues() if (GLOBAL['crypto'] && typeof GLOBAL['crypto']['getRandomValues'] === 'function' && typeof GLOBAL['Uint32Array'] === 'function') { crypto = GLOBAL['crypto']; - return function(bits) { + return function (bits) { var elems = Math.ceil(bits / 32), str = null, arr = new GLOBAL['Uint32Array'](elems); @@ -8730,7 +9038,7 @@ var bitsPerNum = 32; var max = Math.pow(2, bitsPerNum) - 1; - return function(bits) { + return function (bits) { var elems = Math.ceil(bits / bitsPerNum); var arr = [], str = null; @@ -8755,7 +9063,7 @@ // Set the PRNG to use. If no RNG function is supplied, pick a default using getRNG() /** @expose **/ - SecretShare.setRNG = function(rng, alert) { + SecretShare.setRNG = function (rng, alert) { if (!isInited()) { this.init(); } @@ -8764,7 +9072,7 @@ // test the RNG (5 times) if (typeof rng !== 'function' || typeof rng(config.bits) !== 'string' || !parseInt(rng(config.bits), - 2) || rng(config.bits).length > config.bits || rng(config.bits).length < config.bits) { + 2) || rng(config.bits).length > config.bits || rng(config.bits).length < config.bits) { throw new Error( "Random number generator is invalid. Supply an RNG of the form function(bits){} that returns a string containing 'bits' number of random 1's and 0's." ) @@ -8782,7 +9090,7 @@ // Generates a random bits-length number string using the PRNG /** @expose **/ - SecretShare.random = function(bits) { + SecretShare.random = function (bits) { if (!isSetRNG()) { this.setRNG(); } @@ -8802,7 +9110,7 @@ // requiring `threshold` number of shares to reconstruct the secret. // Optionally, zero-pads the secret to a length that is a multiple of padLength before sharing. /** @expose **/ - SecretShare.share = function(secret, numShares, threshold, padLength, withoutPrefix) { + SecretShare.share = function (secret, numShares, threshold, padLength, withoutPrefix) { if (!isInited()) { this.init(); } @@ -8873,7 +9181,7 @@ // Note: no error-checking at this stage! If `secrets` is NOT // a NUMBER less than 2^bits-1, the output will be incorrect! /** @expose **/ - SecretShare._getShares = function(secret, numShares, threshold) { + SecretShare._getShares = function (secret, numShares, threshold) { var shares = []; var coeffs = [secret]; @@ -8920,7 +9228,7 @@ var bits = parseInt(share[0], 36); if (bits && (typeof bits !== 'number' || bits % 1 !== 0 || bits < defaults.minBits || bits > - defaults.maxBits)) { + defaults.maxBits)) { throw new Error('Number of bits must be an integer between ' + defaults.minBits + ' and ' + defaults.maxBits + ', inclusive.') } @@ -8995,14 +9303,14 @@ // Combine `shares` Array into the original secret /** @expose **/ - SecretShare.combine = function(shares) { + SecretShare.combine = function (shares) { return combine(0, shares); }; // Generate a new share with id `id` (a number between 1 and 2^bits-1) // `id` can be a Number or a String in the default radix (16) /** @expose **/ - SecretShare.newShare = function(id, shares) { + SecretShare.newShare = function (id, shares) { if (typeof id === 'string') { id = parseInt(id, config.radix); } @@ -9041,7 +9349,7 @@ product = -1; // fix for a zero product term, after which the sum should be sum^0 = sum, not sum^1 break; } - product = (product + config.logs[at ^ x[j]] - config.logs[x[i] ^ x[j]] + config.max /* to make sure it's not negative */ ) % + product = (product + config.logs[at ^ x[j]] - config.logs[x[i] ^ x[j]] + config.max /* to make sure it's not negative */) % config.max; } @@ -9108,7 +9416,7 @@ // Each character of the input string is represented by // `bytesPerChar` bytes in the output string. /** @expose **/ - SecretShare.str2hex = function(str, bytesPerChar) { + SecretShare.str2hex = function (str, bytesPerChar) { if (typeof str !== 'string') { throw new Error('Input must be a character string.'); } @@ -9142,7 +9450,7 @@ // Converts a given HEX number string to a UTF16 character string. /** @expose **/ - SecretShare.hex2str = function(str, bytesPerChar) { + SecretShare.hex2str = function (str, bytesPerChar) { if (typeof str !== 'string') { throw new Error('Input must be a hexadecimal string.'); } @@ -9168,7 +9476,7 @@ })(); //kbucket.js - (function() { + (function () { // Kademlia DHT K-bucket implementation as a binary tree. // by 'Tristan Slominski' under 'MIT License' GLOBAL.BuildKBucket = function KBucket(options = {}) { @@ -9181,7 +9489,7 @@ this.arbiter = options.arbiter || this.arbiter this.metadata = Object.assign({}, options.metadata) - this.createNode = function() { + this.createNode = function () { return { contacts: [], dontSplit: false, @@ -9190,12 +9498,12 @@ } } - this.ensureInt8 = function(name, val) { + this.ensureInt8 = function (name, val) { if (!(val instanceof Uint8Array)) throw new TypeError(name + ' is not a Uint8Array') } - this.arrayEquals = function(array1, array2) { + this.arrayEquals = function (array1, array2) { if (array1 === array2) return true if (array1.length !== array2.length) @@ -9209,11 +9517,11 @@ this.ensureInt8('option.localNodeId as parameter 1', this.localNodeId) this.root = this.createNode() - this.arbiter = function(incumbent, candidate) { + this.arbiter = function (incumbent, candidate) { return incumbent.vectorClock > candidate.vectorClock ? incumbent : candidate } - this.distance = function(firstId, secondId) { + this.distance = function (firstId, secondId) { let distance = 0 let i = 0 const min = Math.min(firstId.length, secondId.length) @@ -9224,7 +9532,7 @@ return distance } - this.add = function(contact) { + this.add = function (contact) { this.ensureInt8('contact.id', (contact || {}).id) let bitIndex = 0 let node = this.root @@ -9245,7 +9553,7 @@ return this.add(contact) } - this.closest = function(id, n = Infinity) { + this.closest = function (id, n = Infinity) { this.ensureInt8('id', id) if ((!Number.isInteger(n) && n !== Infinity) || n <= 0) throw new TypeError('n is not positive number') @@ -9266,7 +9574,7 @@ .map(a => a[1]) } - this.count = function() { + this.count = function () { let count = 0 for (const nodes = [this.root]; nodes.length > 0;) { const node = nodes.pop() @@ -9278,7 +9586,7 @@ return count } - this._determineNode = function(node, id, bitIndex) { + this._determineNode = function (node, id, bitIndex) { const bytesDescribedByBitIndex = bitIndex >> 3 const bitIndexWithinByte = bitIndex % 8 if ((id.length <= bytesDescribedByBitIndex) && (bitIndexWithinByte !== 0)) @@ -9289,7 +9597,7 @@ return node.left } - this.get = function(id) { + this.get = function (id) { this.ensureInt8('id', id) let bitIndex = 0 let node = this.root @@ -9299,14 +9607,14 @@ return index >= 0 ? node.contacts[index] : null } - this._indexOf = function(node, id) { + this._indexOf = function (node, id) { for (let i = 0; i < node.contacts.length; ++i) if (this.arrayEquals(node.contacts[i].id, id)) return i return -1 } - this.remove = function(id) { + this.remove = function (id) { this.ensureInt8('the id as parameter 1', id) let bitIndex = 0 let node = this.root @@ -9318,7 +9626,7 @@ return this } - this._split = function(node, bitIndex) { + this._split = function (node, bitIndex) { node.left = this.createNode() node.right = this.createNode() for (const contact of node.contacts) @@ -9329,7 +9637,7 @@ otherNode.dontSplit = true } - this.toArray = function() { + this.toArray = function () { let result = [] for (const nodes = [this.root]; nodes.length > 0;) { const node = nodes.pop() @@ -9341,7 +9649,7 @@ return result } - this._update = function(node, index, contact) { + this._update = function (node, index, contact) { if (!this.arrayEquals(node.contacts[index].id, contact.id)) throw new Error('wrong index for _update') const incumbent = node.contacts[index] From aebda7ec80d3bce49998f5b621f8bcb8afa7e2da Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 24 Nov 2022 03:25:52 +0530 Subject: [PATCH 233/289] btcOperator v1.0.14: multisig-bech32 (p2wsh) --- btcOperator.js | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index 0f2786a..d1f57fa 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //btcOperator v1.0.13c +(function (EXPORTS) { //btcOperator v1.0.14 /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -102,7 +102,7 @@ if (!addr) return undefined; let type = coinjs.addressDecode(addr).type; - if (["standard", "multisig", "bech32"].includes(type)) + if (["standard", "multisig", "bech32", "multisigBech32"].includes(type)) return type; else return false; @@ -398,6 +398,7 @@ return reject("Insufficient Balance"); let addr = senders[rec_args.n], rs = redeemScripts[rec_args.n]; + let addr_type = coinjs.addressDecode(addr).type; let size_per_input = _sizePerInput(addr, rs); fetch_api(`get_tx_unspent/BTC/${addr}`).then(result => { let utxos = result.data.txs; @@ -408,14 +409,14 @@ var script; if (!rs || !rs.length) //legacy script script = utxos[i].script_hex; - else if (((rs.match(/^00/) && rs.length == 44)) || (rs.length == 40 && rs.match(/^[a-f0-9]+$/gi))) { - //redeemScript for segwit/bech32 + else if (((rs.match(/^00/) && rs.length == 44)) || (rs.length == 40 && rs.match(/^[a-f0-9]+$/gi)) || addr_type === 'multisigBech32') { + //redeemScript for segwit/bech32 and multisig (bech32) let s = coinjs.script(); s.writeBytes(Crypto.util.hexToBytes(rs)); s.writeOp(0); s.writeBytes(coinjs.numToBytes((utxos[i].value * SATOSHI_IN_BTC).toFixed(0), 8)); script = Crypto.util.bytesToHex(s.buffer); - } else //redeemScript for multisig + } else //redeemScript for multisig (segwit) script = rs; tx.addinput(utxos[i].txid, utxos[i].output_no, script, 0xfffffffd /*sequence*/); //0xfffffffd for Replace-by-fee //update track values From a71c851cc2705a1689713e3e2ba22d4db42d5c9a Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 27 Nov 2022 02:47:02 +0530 Subject: [PATCH 234/289] btcOperator v1.0.14a - Added multisig-bech32 to auto-fee calc - Fixed: createMultiSigTx not working with bech32 sender - Fixed: checkSigned for multisig-bech32 --- btcOperator.js | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index d1f57fa..9efd6ee 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //btcOperator v1.0.14 +(function (EXPORTS) { //btcOperator v1.0.14a /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -108,12 +108,15 @@ return false; } - btcOperator.multiSigAddress = function (pubKeys, minRequired) { + btcOperator.multiSigAddress = function (pubKeys, minRequired, bech32 = true) { if (!Array.isArray(pubKeys)) throw "pubKeys must be an array of public keys"; else if (pubKeys.length < minRequired) throw "minimum required should be less than the number of pubKeys"; - return coinjs.pubkeys2MultisigAddress(pubKeys, minRequired); + if (bech32) + return coinjs.pubkeys2MultisigAddressBech32(pubKeys, minRequired); + else + return coinjs.pubkeys2MultisigAddress(pubKeys, minRequired); } //convert from one blockchain to another blockchain (target version) @@ -222,11 +225,13 @@ BASE_INPUT_SIZE = 41, LEGACY_INPUT_SIZE = 107, BECH32_INPUT_SIZE = 27, + BECH32_MULTISIG_INPUT_SIZE = 35, SEGWIT_INPUT_SIZE = 59, MULTISIG_INPUT_SIZE_ES = 351, BASE_OUTPUT_SIZE = 9, LEGACY_OUTPUT_SIZE = 25, BECH32_OUTPUT_SIZE = 23, + BECH32_MULTISIG_OUTPUT_SIZE = 34, SEGWIT_OUTPUT_SIZE = 23; function _redeemScript(addr, key) { @@ -249,6 +254,8 @@ return BASE_INPUT_SIZE + LEGACY_INPUT_SIZE; case "bech32": return BASE_INPUT_SIZE + BECH32_INPUT_SIZE; + case "multisigBech32": + return BASE_INPUT_SIZE + BECH32_MULTISIG_INPUT_SIZE; case "multisig": switch (coinjs.script().decodeRedeemScript(rs).type) { case "segwit__": @@ -269,6 +276,8 @@ return BASE_OUTPUT_SIZE + LEGACY_OUTPUT_SIZE; case "bech32": return BASE_OUTPUT_SIZE + BECH32_OUTPUT_SIZE; + case "multisigBech32": + return BASE_OUTPUT_SIZE + BECH32_MULTISIG_OUTPUT_SIZE; case "multisig": return BASE_OUTPUT_SIZE + SEGWIT_OUTPUT_SIZE; default: @@ -564,11 +573,14 @@ btcOperator.createMultiSigTx = function (sender, redeemScript, receivers, amounts, fee = null, options = {}) { return new Promise((resolve, reject) => { //validate tx parameters - if (validateAddress(sender) !== "multisig") + let addr_type = validateAddress(sender); + if (!(["multisig", "multisigBech32"].includes(addr_type))) return reject("Invalid sender (multisig):" + sender); else { let script = coinjs.script(); - let decode = script.decodeRedeemScript(redeemScript); + let decode = (addr_type == "multisig") ? + script.decodeRedeemScript(redeemScript) : + script.decodeRedeemScriptBech32(redeemScript); if (!decode || decode.address !== sender) return reject("Invalid redeem-script"); } @@ -623,10 +635,10 @@ let n = []; for (let i in tx.ins) { var s = tx.extractScriptKey(i); - if (s['type'] !== 'multisig') + if (s['type'] !== 'multisig' && s['type'] !== 'multisig_bech32') n.push(s.signed == 'true' || (tx.witness[i] && tx.witness[i].length == 2)) else { - var rs = coinjs.script().decodeRedeemScript(s.script); + var rs = coinjs.script().decodeRedeemScript(s.script); //will work for bech32 too, as only address is diff let x = { s: s['signatures'], r: rs['signaturesRequired'], @@ -682,10 +694,10 @@ result.outputs = tx.outs.map(out => { var address; switch (out.script.chunks[0]) { - case 0: //bech32 + case 0: //bech32, multisig-bech32 address = encodeBech32(Crypto.util.bytesToHex(out.script.chunks[1]), coinjs.bech32.version, coinjs.bech32.hrp); break; - case 169: //multisig, segwit + case 169: //segwit, multisig-segwit address = encodeLegacy(Crypto.util.bytesToHex(out.script.chunks[1]), coinjs.multisig); break; case 118: //legacy From ea4d1f67d6299d04a0be43c97ae8a85ced206ec3 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 16 Dec 2022 20:47:21 +0530 Subject: [PATCH 235/289] bug fix: btcOperator v1.0.14b (ignore dust-change) --- btcOperator.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index 9efd6ee..c81f2e2 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //btcOperator v1.0.14a +(function (EXPORTS) { //btcOperator v1.0.14b /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -338,7 +338,7 @@ const tx = coinjs.transaction(); let output_size = addOutputs(tx, receivers, amounts, change_address); addInputs(tx, senders, redeemScripts, total_amount, fee, output_size, fee_from_receiver).then(result => { - if (result.change_amount > 0) //add change amount if any + if (result.change_amount > 0 && result.change_amount > result.fee) //add change amount if any (ignore dust change) tx.outs[tx.outs.length - 1].value = parseInt(result.change_amount * SATOSHI_IN_BTC); //values are in satoshi if (fee_from_receiver) { //deduce fee from receivers if fee_from_receiver let fee_remaining = parseInt(result.fee * SATOSHI_IN_BTC); From cc4380d623003b1dfc50dcd3438ac33e528b50cd Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 18 Dec 2022 03:44:04 +0530 Subject: [PATCH 236/289] floDapps v2.3.3 - Added support: update cloud node URL - Added support: trusted IDs (configured by adminID) - Trusted IDs have permission to edit tag data --- floDapps.js | 73 +++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 54 insertions(+), 19 deletions(-) diff --git a/floDapps.js b/floDapps.js index 38ee0b4..9603c41 100644 --- a/floDapps.js +++ b/floDapps.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //floDapps v2.3.2d +(function (EXPORTS) { //floDapps v2.3.3 /* General functions for FLO Dapps*/ 'use strict'; const floDapps = EXPORTS; @@ -181,6 +181,7 @@ credentials: {}, //for Dapps subAdmins: {}, + trustedIDs: {}, settings: {}, appObjects: {}, generalData: {}, @@ -244,6 +245,12 @@ compactIDB.removeData("supernodes", sn, DEFAULT.root); for (let sn in content.newNodes) compactIDB.writeData("supernodes", content.newNodes[sn], sn, DEFAULT.root); + for (let sn in content.updateNodes) + compactIDB.readData("supernodes", sn, DEFAULT.root).then(r => { + r = r || {} + r.uri = content.updateNodes[sn]; + compactIDB.writeData("supernodes", r, sn, DEFAULT.root); + }); } compactIDB.writeData("lastTx", result.totalTxs, floCloudAPI.SNStorageID, DEFAULT.root); compactIDB.readAllData("supernodes", DEFAULT.root).then(nodes => { @@ -274,6 +281,12 @@ if (Array.isArray(content.addSubAdmin)) for (var k = 0; k < content.addSubAdmin.length; k++) compactIDB.writeData("subAdmins", true, content.addSubAdmin[k]); + if (Array.isArray(content.removeTrustedID)) + for (var j = 0; j < content.removeTrustedID.length; j++) + compactIDB.removeData("trustedIDs", content.removeTrustedID[j]); + if (Array.isArray(content.addTrustedID)) + for (var k = 0; k < content.addTrustedID.length; k++) + compactIDB.writeData("trustedIDs", true, content.addTrustedID[k]); if (content.settings) for (let l in content.settings) compactIDB.writeData("settings", content.settings[l], l) @@ -454,7 +467,7 @@ }) }); - floDapps.launchStartUp = function() { + floDapps.launchStartUp = function () { return new Promise((resolve, reject) => { initIndexedDB().then(log => { console.log(log) @@ -497,7 +510,7 @@ floDapps.setAppObjectStores = appObs => initIndexedDB.appObs = appObs; - floDapps.storeContact = function(floID, name) { + floDapps.storeContact = function (floID, name) { return new Promise((resolve, reject) => { if (!floCrypto.validateAddr(floID)) return reject("Invalid floID!") @@ -508,7 +521,7 @@ }); } - floDapps.storePubKey = function(floID, pubKey) { + floDapps.storePubKey = function (floID, pubKey) { return new Promise((resolve, reject) => { if (floID in user.pubKeys) return resolve("pubKey already stored") @@ -523,7 +536,7 @@ }); } - floDapps.sendMessage = function(floID, message) { + floDapps.sendMessage = function (floID, message) { return new Promise((resolve, reject) => { let options = { receiverID: floID, @@ -538,7 +551,7 @@ }) } - floDapps.requestInbox = function(callback) { + floDapps.requestInbox = function (callback) { return new Promise((resolve, reject) => { let lastVC = Object.keys(user.messages).sort().pop() let options = { @@ -552,7 +565,7 @@ try { if (d[v].message instanceof Object && "secret" in d[v].message) d[v].message = floCrypto.decryptData(d[v].message, privKey) - } catch (error) {} + } catch (error) { } compactIDB.writeData("messages", d[v], v, user.db_name) user.messages[v] = d[v] } @@ -565,7 +578,7 @@ }) } - floDapps.manageAppConfig = function(adminPrivKey, addList, rmList, settings) { + floDapps.manageAppConfig = function (adminPrivKey, addList, rmList, settings) { return new Promise((resolve, reject) => { if (!Array.isArray(addList) || !addList.length) addList = undefined; if (!Array.isArray(rmList) || !rmList.length) rmList = undefined; @@ -584,12 +597,34 @@ reject('Access Denied for Admin privilege') else floBlockchainAPI.writeData(floID, JSON.stringify(floData), adminPrivKey) - .then(result => resolve(['Updated App Configuration', result])) - .catch(error => reject(error)) + .then(result => resolve(['Updated App Configuration', result])) + .catch(error => reject(error)) }) } - const clearCredentials = floDapps.clearCredentials = function() { + floDapps.manageAppTrustedIDs = function (adminPrivKey, addList, rmList) { + return new Promise((resolve, reject) => { + if (!Array.isArray(addList) || !addList.length) addList = undefined; + if (!Array.isArray(rmList) || !rmList.length) rmList = undefined; + if (!addList && !rmList) + return reject("No change in list") + var floData = { + [DEFAULT.application]: { + addTrustedID: addList, + removeTrustedID: rmList + } + } + var floID = floCrypto.getFloID(adminPrivKey) + if (floID != DEFAULT.adminID) + reject('Access Denied for Admin privilege') + else + floBlockchainAPI.writeData(floID, JSON.stringify(floData), adminPrivKey) + .then(result => resolve(['Updated App Configuration', result])) + .catch(error => reject(error)) + }) + } + + const clearCredentials = floDapps.clearCredentials = function () { return new Promise((resolve, reject) => { compactIDB.clearData('credentials', DEFAULT.application).then(result => { localStorage.removeItem(`${DEFAULT.application}#privKey`); @@ -599,7 +634,7 @@ }) } - floDapps.deleteUserData = function(credentials = false) { + floDapps.deleteUserData = function (credentials = false) { return new Promise((resolve, reject) => { let p = [] p.push(compactIDB.deleteDB(user.db_name)) @@ -611,7 +646,7 @@ }) } - floDapps.deleteAppData = function() { + floDapps.deleteAppData = function () { return new Promise((resolve, reject) => { compactIDB.deleteDB(DEFAULT.application).then(result => { localStorage.removeItem(`${DEFAULT.application}#privKey`) @@ -623,7 +658,7 @@ }) } - floDapps.securePrivKey = function(pwd) { + floDapps.securePrivKey = function (pwd) { return new Promise(async (resolve, reject) => { let indexArr = localStorage.getItem(`${DEFAULT.application}#privKey`) if (!indexArr) @@ -643,8 +678,8 @@ }) } - floDapps.verifyPin = function(pin = null) { - const readSharesFromIDB = function(indexArr) { + floDapps.verifyPin = function (pin = null) { + const readSharesFromIDB = function (indexArr) { return new Promise((resolve, reject) => { var promises = [] for (var i = 0; i < indexArr.length; i++) @@ -687,7 +722,7 @@ }) } - const getNextGeneralData = floDapps.getNextGeneralData = function(type, vectorClock = null, options = {}) { + const getNextGeneralData = floDapps.getNextGeneralData = function (type, vectorClock = null, options = {}) { var fk = floCloudAPI.util.filterKey(type, options) vectorClock = vectorClock || getNextGeneralData[fk] || '0'; var filteredResult = {} @@ -716,10 +751,10 @@ let tmp = floCrypto.decryptData(data.message, key) data.message = JSON.parse(tmp) break; - } catch (error) {} + } catch (error) { } } } - } catch (error) {} + } catch (error) { } } } getNextGeneralData[fk] = Object.keys(filteredResult).sort().pop(); From c2b836c069eca5c04c4275e169dc854fdc394479 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 23 Dec 2022 22:48:52 +0530 Subject: [PATCH 237/289] Updating floSight URLs --- floBlockchainAPI.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 473b192..ab778fe 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.3.3d +(function (EXPORTS) { //floBlockchainAPI v2.3.3e /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -6,7 +6,7 @@ const DEFAULT = { blockchain: floGlobals.blockchain, apiURL: { - FLO: ['https://flosight.duckdns.org/'], + FLO: ['https://flosight.duckdns.org/', 'https://flosight.ranchimall.net/'], FLO_TEST: ['https://testnet-flosight.duckdns.org', 'https://testnet.flocha.in/'] }, sendAmt: 0.001, From c2a94e6246103d11c6a077c6fb95f29bea3241d3 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 31 Jan 2023 01:21:48 +0530 Subject: [PATCH 238/289] btcOperator v1.1.0: updating API provider updating API link to blockchain.info --- btcOperator.js | 158 +++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 126 insertions(+), 32 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index c81f2e2..beb2cd6 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,16 +1,16 @@ -(function (EXPORTS) { //btcOperator v1.0.14b +(function (EXPORTS) { //btcOperator v1.1.0 /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; //This library uses API provided by chain.so (https://chain.so/) - const URL = "https://chain.so/api/v2/"; + const URL = "https://blockchain.info/"; const fetch_api = btcOperator.fetch = function (api) { return new Promise((resolve, reject) => { console.debug(URL + api); fetch(URL + api).then(response => { response.json() - .then(result => result.status === "success" ? resolve(result) : reject(result)) + .then(result => result.error ? reject(result) : resolve(result)) .catch(error => reject(error)) }).catch(error => reject(error)) }) @@ -18,12 +18,17 @@ const SATOSHI_IN_BTC = 1e8; + const util = btcOperator.util = {}; + + util.Sat_to_BTC = value => parseFloat((value / SATOSHI_IN_BTC).toFixed(8)); + util.BTC_to_Sat = value => parseInt(value * SATOSHI_IN_BTC); + function get_fee_rate() { return new Promise((resolve, reject) => { fetch('https://api.blockchain.info/mempool/fees').then(response => { if (response.ok) response.json() - .then(result => resolve(parseFloat((result.regular / SATOSHI_IN_BTC).toFixed(8)))) + .then(result => resolve(util.Sat_to_BTC(result.regular))) .catch(error => reject(error)); else reject(response); @@ -216,8 +221,8 @@ //BTC blockchain APIs btcOperator.getBalance = addr => new Promise((resolve, reject) => { - fetch_api(`get_address_balance/BTC/${addr}`) - .then(result => resolve(parseFloat(result.data.confirmed_balance))) + fetch_api(`q/addressbalance/${addr}`) + .then(result => resolve(util.Sat_to_BTC(result))) .catch(error => reject(error)) }); @@ -308,7 +313,7 @@ parameters.privkeys[i] = coinjs.privkey2wif(key); }); if (invalids.length) - throw "Invalid keys:" + invalids; + throw "Invalid private key for address:" + invalids; } //receiver-ids (and change-id) if (!Array.isArray(parameters.receivers)) @@ -339,9 +344,9 @@ let output_size = addOutputs(tx, receivers, amounts, change_address); addInputs(tx, senders, redeemScripts, total_amount, fee, output_size, fee_from_receiver).then(result => { if (result.change_amount > 0 && result.change_amount > result.fee) //add change amount if any (ignore dust change) - tx.outs[tx.outs.length - 1].value = parseInt(result.change_amount * SATOSHI_IN_BTC); //values are in satoshi + tx.outs[tx.outs.length - 1].value = util.BTC_to_Sat(result.change_amount); //values are in satoshi if (fee_from_receiver) { //deduce fee from receivers if fee_from_receiver - let fee_remaining = parseInt(result.fee * SATOSHI_IN_BTC); + let fee_remaining = util.BTC_to_Sat(result.fee); for (let i = 0; i < tx.outs.length - 1 && fee_remaining > 0; i++) { if (fee_remaining < tx.outs[i].value) { tx.outs[i].value -= fee_remaining; @@ -409,29 +414,29 @@ rs = redeemScripts[rec_args.n]; let addr_type = coinjs.addressDecode(addr).type; let size_per_input = _sizePerInput(addr, rs); - fetch_api(`get_tx_unspent/BTC/${addr}`).then(result => { - let utxos = result.data.txs; + fetch_api(`unspent?active=${addr}`).then(result => { + let utxos = result.unspent_outputs; console.debug("add-utxo", addr, rs, required_amount, utxos); for (let i = 0; i < utxos.length && required_amount > 0; i++) { if (!utxos[i].confirmations) //ignore unconfirmed utxo continue; var script; if (!rs || !rs.length) //legacy script - script = utxos[i].script_hex; + script = utxos[i].script; else if (((rs.match(/^00/) && rs.length == 44)) || (rs.length == 40 && rs.match(/^[a-f0-9]+$/gi)) || addr_type === 'multisigBech32') { //redeemScript for segwit/bech32 and multisig (bech32) let s = coinjs.script(); s.writeBytes(Crypto.util.hexToBytes(rs)); s.writeOp(0); - s.writeBytes(coinjs.numToBytes((utxos[i].value * SATOSHI_IN_BTC).toFixed(0), 8)); + s.writeBytes(coinjs.numToBytes(utxos[i].value.toFixed(0), 8)); script = Crypto.util.bytesToHex(s.buffer); } else //redeemScript for multisig (segwit) script = rs; - tx.addinput(utxos[i].txid, utxos[i].output_no, script, 0xfffffffd /*sequence*/); //0xfffffffd for Replace-by-fee + tx.addinput(utxos[i].tx_hash_big_endian, utxos[i].tx_output_n, script, 0xfffffffd /*sequence*/); //0xfffffffd for Replace-by-fee //update track values rec_args.input_size += size_per_input; - rec_args.input_amount += parseFloat(utxos[i].value); - required_amount -= parseFloat(utxos[i].value); + rec_args.input_amount += util.Sat_to_BTC(utxos[i].value); + required_amount -= util.Sat_to_BTC(utxos[i].value); if (fee_rate) //automatic fee calculation (dynamic) required_amount += size_per_input * fee_rate; } @@ -670,8 +675,8 @@ } const getTxOutput = (txid, i) => new Promise((resolve, reject) => { - fetch_api(`get_tx_outputs/BTC/${txid}/${i}`) - .then(result => resolve(result.data.outputs)) + fetch_api(`rawtx/${txid}`) + .then(result => resolve(result.out[i])) .catch(error => reject(error)) }); @@ -685,8 +690,8 @@ promises.push(getTxOutput(tx.ins[i].outpoint.hash, tx.ins[i].outpoint.index)); Promise.all(promises).then(inputs => { result.inputs = inputs.map(inp => Object({ - address: inp.address, - value: parseFloat(inp.value) + address: inp.addr, + value: util.Sat_to_BTC(inp.value) })); let signed = checkSigned(tx, false); result.inputs.forEach((inp, i) => inp.signed = signed[i]); @@ -705,7 +710,7 @@ } return { address, - value: parseFloat(out.value / SATOSHI_IN_BTC) + value: util.Sat_to_BTC(out.value) } }); //Parse Totals @@ -726,22 +731,111 @@ return Crypto.util.bytesToHex(txid); } - btcOperator.getTx = txid => new Promise((resolve, reject) => { - fetch_api(`get_tx/BTC/${txid}`) - .then(result => resolve(result.data)) + const getLatestBlock = btcOperator.getLatestBlock = () => new Promise((resolve, reject) => { + fetch_api(`q/getblockcount`) + .then(result => resolve(result)) .catch(error => reject(error)) + }) + + btcOperator.getTx = txid => new Promise((resolve, reject) => { + fetch_api(`rawtx/${txid}`).then(result => { + getLatestBlock().then(latest_block => { + resolve({ + block: result.block_height, + txid: result.hash, + time: result.time * 1000, + confirmations: latest_block - result.block_height, //calculate confirmations using latest block number as api doesnt relay it + size: result.size, + fee: util.Sat_to_BTC(result.fee), + inputs: result.inputs.map(i => Object({ address: i.prev_out.addr, value: util.Sat_to_BTC(i.prev_out.value) })), + total_input_value: util.Sat_to_BTC(result.inputs.reduce((a, i) => a + i.prev_out.value, 0)), + outputs: result.out.map(o => Object({ address: o.addr, value: util.Sat_to_BTC(o.value) })), + total_output_value: util.Sat_to_BTC(result.out.reduce((a, o) => a += o.value, 0)), + }) + }) + }).catch(error => reject(error)) }); - btcOperator.getAddressData = addr => new Promise((resolve, reject) => { - fetch_api(`address/BTC/${addr}`) - .then(result => resolve(result.data)) - .catch(error => reject(error)) + btcOperator.getAddressData = address => new Promise((resolve, reject) => { + fetch_api(`rawaddr/${address}`).then(data => { + let details = {}; + details.balance = util.Sat_to_BTC(data.final_balance); + details.address = data.address; + details.txs = data.txs.map(tx => { + let d = { + txid: tx.hash, + time: tx.time * 1000, //s to ms + block: tx.block_height, + } + //sender list + d.tx_senders = {}; + tx.inputs.forEach(i => { + if (i.prev_out.addr in d.tx_senders) + d.tx_senders[i.prev_out.addr] += i.prev_out.value; + else d.tx_senders[i.prev_out.addr] = i.prev_out.value; + }); + d.tx_input_value = 0; + for (let s in d.tx_senders) { + let val = d.tx_senders[s]; + d.tx_senders[s] = util.Sat_to_BTC(val); + d.tx_input_value += val; + } + d.tx_input_value = util.Sat_to_BTC(d.tx_input_value); + //receiver list + d.tx_receivers = {}; + tx.out.forEach(o => { + if (o.addr in d.tx_receivers) + d.tx_receivers[o.addr] += o.value; + else d.tx_receivers[o.addr] = o.value; + }); + d.tx_output_value = 0; + for (let r in d.tx_receivers) { + let val = d.tx_receivers[r]; + d.tx_receivers[r] = util.Sat_to_BTC(val); + d.tx_output_value += val; + } + d.tx_output_value = util.Sat_to_BTC(d.tx_output_value); + d.tx_fee = util.Sat_to_BTC(tx.fee); + //tx type + if (tx.result > 0) { //net > 0, balance inc => type=in + d.type = "in"; + d.amount = util.Sat_to_BTC(tx.result); + d.sender = Object.keys(d.tx_senders).filter(s => s !== address); + } else if (Object.keys(d.tx_receivers).some(r => r !== address)) { //net < 0, balance dec & receiver present => type=out + d.type = "out"; + d.amount = util.Sat_to_BTC(tx.result * -1); + d.receiver = Object.keys(d.tx_receivers).filter(r => r !== address); + d.fee = d.tx_fee; + } else { //net < 0 (fee) & no other id in receiver list => type=self + d.type = "self"; + d.amount = d.tx_receivers[address]; + d.address = address + } + return d; + }) + resolve(details); + }).catch(error => reject(error)) }); btcOperator.getBlock = block => new Promise((resolve, reject) => { - fetch_api(`get_block/BTC/${block}`) - .then(result => resolve(result.data)) - .catch(error => reject(error)) + fetch_api(`rawblock/${block}`).then(result => resolve({ + height: result.height, + hash: result.hash, + merkle_root: result.mrkl_root, + prev_block: result.prev_block, + next_block: result.next_block[0], + size: result.size, + time: result.time * 1000, //s to ms + txs: result.tx.map(t => Object({ + fee: t.fee, + size: t.size, + inputs: t.inputs.map(i => Object({ address: i.prev_out.addr, value: util.Sat_to_BTC(i.prev_out.value) })), + total_input_value: util.Sat_to_BTC(t.inputs.reduce((a, i) => a + i.prev_out.value, 0)), + outputs: t.out.map(o => Object({ address: o.addr, value: util.Sat_to_BTC(o.value) })), + total_output_value: util.Sat_to_BTC(t.out.reduce((a, o) => a += o.value, 0)), + })) + + })).catch(error => reject(error)) }); -})('object' === typeof module ? module.exports : window.btcOperator = {}); \ No newline at end of file +})('object' === typeof module ? module.exports : window.btcOperator = {}); From ca0d557d943aab2e4a7decca5ccae436bc4f10d6 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 31 Jan 2023 02:13:37 +0530 Subject: [PATCH 239/289] btcOperator v1.1.1: getTx.hex - Added getTx.hex(txid): resolves the tx hex of the txid - Update: api responses are checked for response.ok - Fixed: getTx giving incorrect confirmation value for unconfirmed tx --- btcOperator.js | 48 +++++++++++++++++++++++++++++------------------- 1 file changed, 29 insertions(+), 19 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index beb2cd6..6925cec 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,17 +1,23 @@ -(function (EXPORTS) { //btcOperator v1.1.0 +(function (EXPORTS) { //btcOperator v1.1.1 /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; //This library uses API provided by chain.so (https://chain.so/) const URL = "https://blockchain.info/"; - const fetch_api = btcOperator.fetch = function (api) { + const fetch_api = btcOperator.fetch = function (api, json_res = true) { return new Promise((resolve, reject) => { console.debug(URL + api); fetch(URL + api).then(response => { - response.json() - .then(result => result.error ? reject(result) : resolve(result)) - .catch(error => reject(error)) + if (response.ok) { + (json_res ? response.json() : response.text()) + .then(result => resolve(result)) + .catch(error => reject(error)) + } else { + response.json() + .then(result => reject(result)) + .catch(error => reject(error)) + } }).catch(error => reject(error)) }) }; @@ -739,23 +745,27 @@ btcOperator.getTx = txid => new Promise((resolve, reject) => { fetch_api(`rawtx/${txid}`).then(result => { - getLatestBlock().then(latest_block => { - resolve({ - block: result.block_height, - txid: result.hash, - time: result.time * 1000, - confirmations: latest_block - result.block_height, //calculate confirmations using latest block number as api doesnt relay it - size: result.size, - fee: util.Sat_to_BTC(result.fee), - inputs: result.inputs.map(i => Object({ address: i.prev_out.addr, value: util.Sat_to_BTC(i.prev_out.value) })), - total_input_value: util.Sat_to_BTC(result.inputs.reduce((a, i) => a + i.prev_out.value, 0)), - outputs: result.out.map(o => Object({ address: o.addr, value: util.Sat_to_BTC(o.value) })), - total_output_value: util.Sat_to_BTC(result.out.reduce((a, o) => a += o.value, 0)), - }) - }) + getLatestBlock().then(latest_block => resolve({ + block: result.block_height, + txid: result.hash, + time: result.time * 1000, + confirmations: result.block_height === null ? 0 : latest_block - result.block_height, //calculate confirmations using latest block number as api doesnt relay it + size: result.size, + fee: util.Sat_to_BTC(result.fee), + inputs: result.inputs.map(i => Object({ address: i.prev_out.addr, value: util.Sat_to_BTC(i.prev_out.value) })), + total_input_value: util.Sat_to_BTC(result.inputs.reduce((a, i) => a + i.prev_out.value, 0)), + outputs: result.out.map(o => Object({ address: o.addr, value: util.Sat_to_BTC(o.value) })), + total_output_value: util.Sat_to_BTC(result.out.reduce((a, o) => a += o.value, 0)), + })) }).catch(error => reject(error)) }); + btcOperator.getTx.hex = txid => new Promise((resolve, reject) => { + fetch_api(`rawtx/${txid}?format=hex`, false) + .then(result => resolve(result)) + .catch(error => reject(error)) + }) + btcOperator.getAddressData = address => new Promise((resolve, reject) => { fetch_api(`rawaddr/${address}`).then(data => { let details = {}; From 7d31dec230f4b9aafcea64c87f48b876584f7e9a Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 19 Feb 2023 17:26:24 +0530 Subject: [PATCH 240/289] lib v1.3.3: Improvements to bitjs for flo - Updated tx.addflodata: will now check if the data is valid or not - Optimized tx.serialize: changed complex code for appending flodata to a simple one - Added bitjs.strToBytes: converts string (ascii) to strToBytes - Added bitjs.pubkeydecompress: decompresses the public key - Added bitjs.verifySignature: verify the signature (of hash and pubkey) --- lib.js | 78 ++++++++++++++++++++++++++++++++++------------------------ 1 file changed, 46 insertions(+), 32 deletions(-) diff --git a/lib.js b/lib.js index 2234db8..e0ac086 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function (GLOBAL) { //lib v1.3.2 +(function (GLOBAL) { //lib v1.3.3 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -4349,15 +4349,6 @@ var bitjs = GLOBAL.bitjs = function () { }; - function ascii_to_hexa(str) { - var arr1 = []; - for (var n = 0, l = str.length; n < l; n++) { - var hex = Number(str.charCodeAt(n)).toString(16); - arr1.push(hex); - } - return arr1.join(''); - } - /* public vars */ bitjs.pub = 0x23; // flochange - changed the prefix to FLO Mainnet PublicKey Prefix 0x23 bitjs.priv = 0xa3; //flochange - changed the prefix to FLO Mainnet Private key prefix 0xa3 @@ -4497,10 +4488,18 @@ return this.outputs.push(o); } + // flochange - Added fn to assign flodata to tx + btrx.addflodata = function (data) { + //checks for valid flo-data string + if (typeof data !== "string") + throw Error("floData should be String"); + if (data.length > 1040) + throw Error("floData Character Limit Exceeded"); + if (bitjs.strToBytes(data).some(c => c < 32 || c > 127)) + throw Error("floData contains Invalid characters (only ASCII characters allowed"); - btrx.addflodata = function (txcomments) { // flochange - this whole function needs to be done - this.floData = txcomments; - return this.floData; //flochange .. returning the txcomments -- check if the function return will assign + this.floData = data; + return this.floData; } @@ -4793,29 +4792,14 @@ } buffer = buffer.concat(bitjs.numToBytes(parseInt(this.locktime), 4)); - var flohex = ascii_to_hexa(this.floData); - var floDataCount = this.floData.length; - var floDataCountString; - //flochange -- creating unique data character count logic for floData. This string is prefixed before actual floData string in Raw Transaction - if (floDataCount < 16) { - floDataCountString = floDataCount.toString(16); - floDataCountString = "0" + floDataCountString; - } else if (floDataCount < 253) { - floDataCountString = floDataCount.toString(16); - } else if (floDataCount <= 1040) { - let floDataCountAdjusted = (floDataCount - 253) + parseInt("0xfd00fd"); - let floDataCountStringAdjusted = floDataCountAdjusted.toString(16); - floDataCountString = floDataCountStringAdjusted.substr(0, 2) + floDataCountStringAdjusted.substr(4, 2) + floDataCountStringAdjusted.substr(2, 2); - } else { - floDataCountString = "Character Limit Exceeded"; - } + //flochange -- append floData field + buffer = buffer.concat(bitjs.numToVarInt(this.floData.length)); + buffer = buffer.concat(bitjs.strToBytes(this.floData)) - return Crypto.util.bytesToHex(buffer) + floDataCountString + flohex; // flochange -- Addition of floDataCountString and floData in serialization + return Crypto.util.bytesToHex(buffer); } - - return btrx; } @@ -4856,6 +4840,36 @@ else return bytes[0] + 256 * bitjs.bytesToNum(bytes.slice(1)); } + //flochange - adding fn to convert string (for flodata) to byte + bitjs.strToBytes = function (str) { + return str.split('').map(c => c.charCodeAt(0)); + } + + /* decompress an compressed public key */ + bitjs.pubkeydecompress = function (pubkey) { + if ((typeof (pubkey) == 'string') && pubkey.match(/^[a-f0-9]+$/i)) { + var curve = EllipticCurve.getSECCurveByName("secp256k1"); + try { + var pt = curve.curve.decodePointHex(pubkey); + var x = pt.getX().toBigInteger(); + var y = pt.getY().toBigInteger(); + + var publicKeyBytes = EllipticCurve.integerToBytes(x, 32); + publicKeyBytes = publicKeyBytes.concat(EllipticCurve.integerToBytes(y, 32)); + publicKeyBytes.unshift(0x04); + return Crypto.util.bytesToHex(publicKeyBytes); + } catch (e) { + // console.log(e); + return false; + } + } + return false; + } + + bitjs.verifySignature = function (hash, sig, pubkey) { + return Bitcoin.ECDSA.verify(hash, sig, pubkey); + } + /* clone an object */ bitjs.clone = function (obj) { if (obj == null || typeof (obj) != 'object') return obj; From 1f670be8931806ecddf561dc24da40f157595291 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 19 Feb 2023 17:43:07 +0530 Subject: [PATCH 241/289] lib v1.4.0: Support for FLO multisig address --- lib.js | 214 +++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 202 insertions(+), 12 deletions(-) diff --git a/lib.js b/lib.js index e0ac086..2eeb2f7 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function (GLOBAL) { //lib v1.3.3 +(function (GLOBAL) { //lib v1.4.0 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -4352,6 +4352,7 @@ /* public vars */ bitjs.pub = 0x23; // flochange - changed the prefix to FLO Mainnet PublicKey Prefix 0x23 bitjs.priv = 0xa3; //flochange - changed the prefix to FLO Mainnet Private key prefix 0xa3 + bitjs.multisig = 0x5e; //flochange - prefix for FLO Mainnet Multisig 0x5e bitjs.compressed = false; /* provide a privkey and return an WIF */ @@ -4452,6 +4453,45 @@ return B58.encode(r.concat(checksum)); } + /* generate a multisig address from pubkeys and required signatures */ + bitjs.pubkeys2multisig = function (pubkeys, required) { + var s = []; + s.push(80 + required); //OP_1 + for (var i = 0; i < pubkeys.length; ++i) { + let bytes = Crypto.util.hexToBytes(pubkeys[i]); + s.push(bytes.length); + s = s.concat(bytes); + } + s.push(80 + pubkeys.length); //OP_1 + s.push(174); //OP_CHECKMULTISIG + + if (s.length > 520) { // too large + throw Error(`redeemScript size(=${s.length}) too large`) + } + + var x = ripemd160(Crypto.SHA256(s, { + asBytes: true + }), { + asBytes: true + }); + x.unshift(bitjs.multisig); + var r = x; + r = Crypto.SHA256(Crypto.SHA256(r, { + asBytes: true + }), { + asBytes: true + }); + var checksum = r.slice(0, 4); + var redeemScript = Crypto.util.bytesToHex(s); + var address = B58.encode(x.concat(checksum)); + + return { + 'address': address, + 'redeemScript': redeemScript, + 'size': s.length + }; + } + bitjs.transaction = function () { var btrx = {}; btrx.version = 2; //flochange look at this version @@ -4467,7 +4507,6 @@ 'hash': txid, 'index': index }; - //o.script = []; Signature and Public Key should be added after singning o.script = Crypto.util.hexToBytes(scriptPubKey); //push previous output pubkey script o.sequence = sequence || ((btrx.locktime == 0) ? 4294967295 : 0); return this.inputs.push(o); @@ -4476,14 +4515,23 @@ btrx.addoutput = function (address, value) { var o = {}; var buf = []; - var addrDecoded = btrx.addressDecode(address); + var addr = this.addressDecode(address); o.value = new BigInteger('' + Math.round((value * 1) * 1e8), 10); - buf.push(118); //OP_DUP - buf.push(169); //OP_HASH160 - buf.push(addrDecoded.length); - buf = buf.concat(addrDecoded); // address in bytes - buf.push(136); //OP_EQUALVERIFY - buf.push(172); // OP_CHECKSIG + + if (addr.version === bitjs.pub) { // regular address + buf.push(118); //OP_DUP + buf.push(169); //OP_HASH160 + buf.push(addr.bytes.length); + buf = buf.concat(addr.bytes); // address in bytes + buf.push(136); //OP_EQUALVERIFY + buf.push(172); //OP_CHECKSIG + } else if (addr.version === bitjs.multisig) { // multisig address + buf.push(169); //OP_HASH160 + buf.push(addr.bytes.length); + buf = buf.concat(addr.bytes); // address in bytes + buf.push(135); //OP_EQUAL + } + o.script = buf; return this.outputs.push(o); } @@ -4503,7 +4551,7 @@ } - // Only standard addresses + // Only standard addresses (standard multisig supported) btrx.addressDecode = function (address) { var bytes = B58.decode(address); var front = bytes.slice(0, bytes.length - 4); @@ -4514,7 +4562,10 @@ asBytes: true }).slice(0, 4); if (checksum + "" == back + "") { - return front.slice(1); + return { + version: front[0], + bytes: front.slice(1) + }; } } @@ -4739,6 +4790,60 @@ return KBigInt; }; + btrx.parseScript = function (script) { + + var chunks = []; + var i = 0; + + function readChunk(n) { + chunks.push(script.slice(i, i + n)); + i += n; + }; + + while (i < script.length) { + var opcode = script[i++]; + if (opcode >= 0xF0) { + opcode = (opcode << 8) | script[i++]; + } + + var len; + if (opcode > 0 && opcode < 76) { //OP_PUSHDATA1 + readChunk(opcode); + } else if (opcode == 76) { //OP_PUSHDATA1 + len = script[i++]; + readChunk(len); + } else if (opcode == 77) { //OP_PUSHDATA2 + len = (script[i++] << 8) | script[i++]; + readChunk(len); + } else if (opcode == 78) { //OP_PUSHDATA4 + len = (script[i++] << 24) | (script[i++] << 16) | (script[i++] << 8) | script[i++]; + readChunk(len); + } else { + chunks.push(opcode); + } + + if (i < 0x00) { + break; + } + } + + return chunks; + } + + btrx.decodeRedeemScript = function (rs) { + if (typeof rs == "string") + rs = Crypto.util.hexToBytes(rs); + var script = this.parseScript(rs); + var r = {}; + r.required = script[0] - 80; + r.pubkeys = []; + for (var i = 1; i < script.length - 2; i++) + r.pubkeys.push(Crypto.util.bytesToHex(script[i])); + r.address = bitjs.pubkeys2multisig(r.pubkeys, r.required).address; + r.redeemscript = Crypto.util.bytesToHex(rs); + return r; + } + /* sign a "standard" input */ btrx.signinput = function (index, wif, sigHashType) { var key = bitjs.wif2pubkey(wif); @@ -4755,15 +4860,100 @@ return true; } + /* sign a multisig input */ + btrx.signmultisig = function (index, wif, sigHashType) { + + var script = Array.from(this.inputs[index].script); + var redeemScript, sigsList = []; + + if (script[0] == 0) { //script with signatures + script = this.parseScript(script); + for (var i = 0; i < script.length; i++) { + if (Array.isArray(script[i])) { + if (script[i][0] == 48) //0x30 DERSequence + sigsList.push(script[i]); + else if (script[i][0] >= 80 && script[i][script[i].length - 1] == 174) //OP_CHECKMULTISIG + redeemScript = script[i]; + } + } + } else { //script = redeemscript + redeemScript = script; + } + + var pubkeyList = this.decodeRedeemScript(redeemScript).pubkeys; + var pubkey = bitjs.wif2pubkey(wif)['pubkey']; + if (!pubkeyList.includes(pubkey)) //wif not a part of this multisig + return false; + + pubkeyList = pubkeyList.map(pub => Crypto.util.hexToBytes(bitjs.pubkeydecompress(pub))); //decompress pubkeys + + var shType = sigHashType || 1; + this.inputs[index].script = redeemScript; //script to be signed is redeemscript + var signature = Crypto.util.hexToBytes(this.transactionSig(index, wif, shType)); + sigsList.push(signature); + + var buf = []; + buf.push(0); + + //verify signatures and order them (also remove duplicate sigs) + for (let x in pubkeyList) { + for (let y in sigsList) { + var sighash = Crypto.util.hexToBytes(this.transactionHash(index, sigsList[y].slice(-1)[0] * 1)); + if (bitjs.verifySignature(sighash, sigsList[y], pubkeyList[x])) { + buf.push(sigsList[y].length); + buf = buf.concat(sigsList[y]); + break; //ensures duplicate sigs from same pubkey are not added + } + } + } + + //append redeemscript + buf.push(redeemScript.length); + buf = buf.concat(redeemScript); + + this.inputs[index].script = buf; + return true; + } + /* sign inputs */ btrx.sign = function (wif, sigHashType) { var shType = sigHashType || 1; for (var i = 0; i < this.inputs.length; i++) { - this.signinput(i, wif, shType); + + var decodedScript = this.scriptDecode(i); + + if (decodedScript.type == "scriptpubkey" && decodedScript.signed == false) { //regular + var addr = bitjs.wif2address(wif)["address"];; + if (decodedScript.pubhash == Crypto.util.bytesToHex(this.addressDecode(addr).bytes)) //input belongs to wif + this.signinput(i, wif, shType); + } else if (decodedScript.type == "multisig") { //multisig + this.signmultisig(i, wif, shType); + } } return this.serialize(); } + // function to find type of the script in input + btrx.scriptDecode = function (index) { + var script = this.parseScript(this.inputs[index].script); + if (script.length == 5 && script[script.length - 1] == 172) { + //OP_DUP OP_HASH160 [address bytes] OP_EQUALVERIFY OP_CHECKSIG + // regular scriptPubkey (not signed) + return { type: 'scriptpubkey', signed: false, pubhash: Crypto.util.bytesToHex(script[2]) }; + } else if (script.length == 2 && script[0][0] == 48) { + //[signature] [pubkey] + //(probably) regular signed + return { type: 'scriptpubkey', signed: true }; + } else if (script[0] == 0 && script[script.length - 1][script[script.length - 1].length - 1] == 174) { + //0 [signatues] [redeemscript OP_CHECKMULTISIG] + // multisig with signature + return { type: 'multisig', rs: script[script.length - 1] }; + } else if (script[0] >= 80 && script[script.length - 1] == 174) { + //redeemscript: 80+ [pubkeys] OP_CHECKMULTISIG + // multisig without signature + return { type: 'multisig', rs: Array.from(this.inputs[index].script) }; + } + } /* serialize a transaction */ btrx.serialize = function () { From 0031761a066dd27b3f2992a9a9670996845e3173 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Mon, 20 Feb 2023 02:58:47 +0530 Subject: [PATCH 242/289] lib v1.4.1: Bitcoin.Address: FLO-multisig support - Bitcoin.Address now supports multisg version - new Bitcoin.Address (hex) will now assign the respective version when its regular or multisig address - Added constants: Bitcoin.Address .standardVersion= 0x23 .multisigVersion = 0x5e .testnetVersion = 0x73 --- lib.js | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/lib.js b/lib.js index 2eeb2f7..550402f 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function (GLOBAL) { //lib v1.4.0 +(function (GLOBAL) { //lib v1.4.1 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -5224,17 +5224,26 @@ //https://raw.github.com/bitcoinjs/bitcoinjs-lib/09e8c6e184d6501a0c2c59d73ca64db5c0d3eb95/src/address.js Bitcoin.Address = function (bytes) { - if (GLOBAL.cryptocoin == "FLO") - this.version = 0x23; // FLO mainnet public address - else if (GLOBAL.cryptocoin == "FLO_TEST") - this.version = 0x73; // FLO testnet public address if ("string" == typeof bytes) { - bytes = Bitcoin.Address.decodeString(bytes, this.version); + var d = Bitcoin.Address.decodeString(bytes); + bytes = d.hash; + if (GLOBAL.cryptocoin == "FLO" && (d.version == Bitcoin.Address.standardVersion || d.version == Bitcoin.Address.multisigVersion)) + this.version = d.version; + else if (GLOBAL.cryptocoin == "FLO_TEST" && d.version == Bitcoin.Address.testnetVersion) + this.version = d.version; + else throw "Version (prefix) " + d.version + " not supported!"; + } else { + if (GLOBAL.cryptocoin == "FLO") + this.version = Bitcoin.Address.standardVersion; + else if (GLOBAL.cryptocoin == "FLO_TEST") + this.version = Bitcoin.Address.testnetVersion; // FLO testnet public address } this.hash = bytes; }; - Bitcoin.Address.networkVersion = 0x23; // (FLO mainnet 0x23, 35D), (Bitcoin Mainnet, 0x00, 0D) // *this has no effect * + Bitcoin.Address.standardVersion = 0x23; // (FLO mainnet 0x23, 35D), (Bitcoin Mainnet, 0x00, 0D) + Bitcoin.Address.multisigVersion = 0x5e; // (FLO multisig 0x5e, 94D) + Bitcoin.Address.testnetVersion = 0x73; // (FLO testnet 0x73, 115D) /** * Serialize this object as a standard Bitcoin address. @@ -5263,7 +5272,7 @@ /** * Parse a Bitcoin address contained in a string. */ - Bitcoin.Address.decodeString = function (string, version) { + Bitcoin.Address.decodeString = function (string) { var bytes = Bitcoin.Base58.decode(string); var hash = bytes.slice(0, 21); var checksum = Crypto.SHA256(Crypto.SHA256(hash, { @@ -5279,11 +5288,12 @@ throw "Checksum validation failed!"; } - if (version != hash.shift()) { + /*if (version != hash.shift()) { throw "Version " + hash.shift() + " not supported!"; - } + }*/ - return hash; + var version = hash.shift(); + return { version, hash }; }; //https://raw.github.com/bitcoinjs/bitcoinjs-lib/e90780d3d3b8fc0d027d2bcb38b80479902f223e/src/ecdsa.js Bitcoin.ECDSA = (function () { From dac87a85958f8e01e27f8ae9c83c99842edc35bb Mon Sep 17 00:00:00 2001 From: sairajzero Date: Mon, 20 Feb 2023 03:10:15 +0530 Subject: [PATCH 243/289] floCrypto v2.3.4: multisig address - Added getMultisigAddress(pubkeys, required_sigs): returns a multisig address from given pubkey list and required signatures - Added decodeRedeemScript (redeemScript): decodes the given redeemscript (of multisig) - Updated validateFloID: now validates FLO regular and multisig address. optional argument regularOnly(default=false) if true validates only FLO regular address. --- floCrypto.js | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/floCrypto.js b/floCrypto.js index 563d77f..5e8376f 100644 --- a/floCrypto.js +++ b/floCrypto.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floCrypto v2.3.3e +(function (EXPORTS) { //floCrypto v2.3.4 /* FLO Crypto Operators */ 'use strict'; const floCrypto = EXPORTS; @@ -231,12 +231,36 @@ } } + floCrypto.getMultisigAddress = function (publicKeyList, requiredSignatures) { + if (!Array.isArray(publicKeyList) || !publicKeyList.length) + return null; + if (!Number.isInteger(requiredSignatures) || requiredSignatures < 1) + return null; + try { + var multisig = bitjs.pubkeys2multisig(publicKeyList, requiredSignatures); + return multisig; + } catch { + return null; + } + } + + floCrypto.decodeRedeemScript = function (redeemScript) { + try { + var decoded = bitjs.transaction().decodeRedeemScript(redeemScript); + return decoded; + } catch { + return null; + } + } + //Check if the given flo-id is valid or not - floCrypto.validateFloID = function (floID) { + floCrypto.validateFloID = function (floID, regularOnly = false) { if (!floID) return false; try { let addr = new Bitcoin.Address(floID); + if (regularOnly && addr.version != Bitcoin.Address.standardVersion) + return false; return true; } catch { return false; From 2e0846edc420f3f2fec2c6faaf413e0704227f12 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Mon, 20 Feb 2023 04:59:23 +0530 Subject: [PATCH 244/289] floBlockchainAPI v2.4.0: multisig tx Changes: - multisig addresses are accepted as receiver address in all send-tx fns - multisig addresses are accepted in query fns - sendTx: sender can be regular address only Added 3 multisig transaction fns: - createMultisigTx: creates unsigned tx for multisig sender - sendMultisigTx: create signed multisig tx and broadcast it - writeMultisigData: same as writeData(), but for multisig --- floBlockchainAPI.js | 133 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 125 insertions(+), 8 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index ab778fe..d4f9bf6 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.3.3e +(function (EXPORTS) { //floBlockchainAPI v2.4.0 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -126,7 +126,7 @@ return new Promise((resolve, reject) => { if (!floCrypto.validateASCII(floData)) return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); - else if (!floCrypto.validateFloID(senderAddr)) + else if (!floCrypto.validateFloID(senderAddr, true)) return reject(`Invalid address : ${senderAddr}`); else if (!floCrypto.validateFloID(receiverAddr)) return reject(`Invalid address : ${receiverAddr}`); @@ -203,7 +203,7 @@ //merge all UTXOs of a given floID into a single UTXO floBlockchainAPI.mergeUTXOs = function (floID, privKey, floData = '') { return new Promise((resolve, reject) => { - if (!floCrypto.validateFloID(floID)) + if (!floCrypto.validateFloID(floID, true)) return reject(`Invalid floID`); if (!floCrypto.verifyPrivKey(privKey, floID)) return reject("Invalid Private Key"); @@ -381,7 +381,6 @@ for (let floID in senders) promises.push(promisedAPI(`api/addr/${floID}/utxo`)); Promise.all(promises).then(results => { - let wifSeq = []; var trx = bitjs.transaction(); for (let floID in senders) { let utxos = results.shift(); @@ -391,13 +390,11 @@ sendAmt = totalSendAmt * ratio; } else sendAmt = senders[floID].coins + dividedFee; - let wif = senders[floID].wif; let utxoAmt = 0.0; for (let i = utxos.length - 1; (i >= 0) && (utxoAmt < sendAmt); i--) { if (utxos[i].confirmations) { trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); - wifSeq.push(wif); utxoAmt += utxos[i].amount; } } @@ -410,8 +407,8 @@ for (let floID in receivers) trx.addoutput(floID, receivers[floID]); trx.addflodata(floData.replace(/\n/g, ' ')); - for (let i = 0; i < wifSeq.length; i++) - trx.signinput(i, wifSeq[i], 1); + for (let floID in senders) + trx.sign(senders[floID].wif, 1); var signedTxHash = trx.serialize(); broadcastTx(signedTxHash) .then(txid => resolve(txid)) @@ -421,6 +418,126 @@ }) } + //Create a multisig transaction + const createMultisigTx = floBlockchainAPI.createMultisigTx = function (redeemScript, receivers, amounts, floData = '', strict_utxo = true) { + return new Promise((resolve, reject) => { + var multisig = floCrypto.decodeRedeemScript(redeemScript); + + //validate multisig script and flodata + if (!multisig) + return reject(`Invalid redeemScript`); + var senderAddr = multisig.address; + if (!floCrypto.validateFloID(senderAddr)) + return reject(`Invalid multisig : ${senderAddr}`); + else if (!floCrypto.validateASCII(floData)) + return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); + //validate receiver addresses + if (!Array.isArray(receivers)) + receivers = [receivers]; + for (let r of receivers) + if (!floCrypto.validateFloID(r)) + return reject(`Invalid address : ${r}`); + //validate amounts + if (!Array.isArray(amounts)) + amounts = [amounts]; + if (amounts.length != receivers.length) + return reject("Receivers and amounts have different length"); + var sendAmt = 0; + for (let a of amounts) { + if (typeof a !== 'number' || a <= 0) + return reject(`Invalid amount : ${a}`); + sendAmt += a; + } + + getBalance(senderAddr).then(balance => { + var fee = DEFAULT.fee; + if (balance < sendAmt + fee) + return reject("Insufficient FLO balance!"); + //get unconfirmed tx list + promisedAPI(`api/addr/${senderAddr}`).then(result => { + readTxs(senderAddr, 0, result.unconfirmedTxApperances).then(result => { + let unconfirmedSpent = {}; + for (let tx of result.items) + if (tx.confirmations == 0) + for (let vin of tx.vin) + if (vin.addr === senderAddr) { + if (Array.isArray(unconfirmedSpent[vin.txid])) + unconfirmedSpent[vin.txid].push(vin.vout); + else + unconfirmedSpent[vin.txid] = [vin.vout]; + } + //get utxos list + promisedAPI(`api/addr/${senderAddr}/utxo`).then(utxos => { + //form/construct the transaction data + var trx = bitjs.transaction(); + var utxoAmt = 0.0; + for (var i = utxos.length - 1; + (i >= 0) && (utxoAmt < sendAmt + fee); i--) { + //use only utxos with confirmations (strict_utxo mode) + if (utxos[i].confirmations || !strict_utxo) { + if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout)) + continue; //A transaction has already used the utxo, but is unconfirmed. + trx.addinput(utxos[i].txid, utxos[i].vout, redeemScript); //for multisig, script=redeemScript + utxoAmt += utxos[i].amount; + }; + } + if (utxoAmt < sendAmt + fee) + reject("Insufficient FLO: Some UTXOs are unconfirmed"); + else { + for (let i in receivers) + trx.addoutput(receivers[i], amounts[i]); + var change = utxoAmt - sendAmt - fee; + if (change > DEFAULT.minChangeAmt) + trx.addoutput(senderAddr, change); + trx.addflodata(floData.replace(/\n/g, ' ')); + resolve(trx); + } + }).catch(error => reject(error)) + }).catch(error => reject(error)) + }).catch(error => reject(error)) + }).catch(error => reject(error)) + }); + } + + //Create and send multisig transaction + const sendMultisigTx = floBlockchainAPI.sendMultisigTx = function (redeemScript, privateKeys, receivers, amounts, floData = '', strict_utxo = true) { + return new Promise((resolve, reject) => { + var multisig = floCrypto.decodeRedeemScript(redeemScript); + if (!multisig) + return reject(`Invalid redeemScript`); + if (privateKeys.length < multisig.required) + return reject(`Insufficient privateKeys (required ${multisig.required})`); + for (let pk of privateKeys) { + var flag = false; + for (let pub of multisig.pubkeys) + if (floCrypto.verifyPrivKey(pk, pub, false)) + flag = true; + if (!flag) + return reject(`Invalid Private key`); + } + createMultisigTx(redeemScript, receivers, amounts, floData, strict_utxo).then(trx => { + for (let pk of privateKeys) + trx.sign(pk, 1); + var signedTxHash = trx.serialize(); + broadcastTx(signedTxHash) + .then(txid => resolve(txid)) + .catch(error => reject(error)) + }).catch(error => reject(error)) + }) + } + + floBlockchainAPI.writeMultisigData = function (redeemScript, data, privatekeys, receiverAddr = DEFAULT.receiverID, options = {}) { + let strict_utxo = options.strict_utxo === false ? false : true, + sendAmt = isNaN(options.sendAmt) ? DEFAULT.sendAmt : options.sendAmt; + return new Promise((resolve, reject) => { + if (!floCrypto.validateFloID(receiverAddr)) + return reject(`Invalid receiver: ${receiverAddr}`); + sendMultisigTx(redeemScript, privatekeys, receiverAddr, sendAmt, data, strict_utxo) + .then(txid => resolve(txid)) + .catch(error => reject(error)) + }) + } + //Broadcast signed Tx in blockchain using API const broadcastTx = floBlockchainAPI.broadcastTx = function (signedTxHash) { return new Promise((resolve, reject) => { From a102f5225b20c9a12aad2d2271d029d0e512523b Mon Sep 17 00:00:00 2001 From: sairajzero Date: Mon, 20 Feb 2023 05:02:43 +0530 Subject: [PATCH 245/289] floCrypto v2.3.4a: bug fix - Fixed: verifyPrivKey incorrectly returning false when pubkey is lowercase. (pubkey hex is case-insensitive) --- floCrypto.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/floCrypto.js b/floCrypto.js index 5e8376f..19ffedc 100644 --- a/floCrypto.js +++ b/floCrypto.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floCrypto v2.3.4 +(function (EXPORTS) { //floCrypto v2.3.4a /* FLO Crypto Operators */ 'use strict'; const floCrypto = EXPORTS; @@ -222,7 +222,7 @@ key.setCompressed(true); if (isfloID && pubKey_floID == key.getBitcoinAddress()) return true; - else if (!isfloID && pubKey_floID == key.getPubKeyHex()) + else if (!isfloID && pubKey_floID.toUpperCase() == key.getPubKeyHex().toUpperCase()) return true; else return false; From 9132d169d247e9e5ae7a3c56613ad378d5a2d58a Mon Sep 17 00:00:00 2001 From: sairajzero Date: Mon, 20 Feb 2023 05:20:04 +0530 Subject: [PATCH 246/289] lib v1.4.1a: bug fix - Fixed: bitjs.btrx.decodeRedeemScript not throwing Invalid RedeemScript error --- lib.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib.js b/lib.js index 550402f..d0871b1 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function (GLOBAL) { //lib v1.4.1 +(function (GLOBAL) { //lib v1.4.1a 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -4834,6 +4834,8 @@ if (typeof rs == "string") rs = Crypto.util.hexToBytes(rs); var script = this.parseScript(rs); + if (!(script[0] > 80 && script[script.length - 2] > 80 && script[script.length - 1] == 174)) //OP_CHECKMULTISIG + throw "Invalid RedeemScript"; var r = {}; r.required = script[0] - 80; r.pubkeys = []; From 6288dc82d9007b5d0faf769f25be49d7ad212b05 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 23 Feb 2023 02:04:16 +0530 Subject: [PATCH 247/289] lib v1.4.1b: Minor fixes in coinjs multisig-addr - pubkeys2MultisigAddressBech32: returns another value 'scripthash' - Fixed multisigBech32Address: returning scripthash as redeemScript. (now returns both scripthash and redeemScript --- lib.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/lib.js b/lib.js index d0871b1..50305cf 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function (GLOBAL) { //lib v1.4.1a +(function (GLOBAL) { //lib v1.4.1b 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -6704,6 +6704,7 @@ return { 'address': address, 'redeemScript': r.redeemScript, + 'scripthash': Crypto.util.bytesToHex(program), 'size': r.size }; } @@ -6797,15 +6798,16 @@ }; } - coinjs.multisigBech32Address = function (raw_redeemscript) { - var program = Crypto.SHA256(Crypto.util.hexToBytes(raw_redeemscript), { + coinjs.multisigBech32Address = function (redeemscript) { + var program = Crypto.SHA256(Crypto.util.hexToBytes(redeemscript), { asBytes: true }); var address = coinjs.bech32_encode(coinjs.bech32.hrp, [coinjs.bech32.version].concat(coinjs.bech32_convert(program, 8, 5, true))); return { 'address': address, 'type': 'multisigBech32', - 'redeemscript': Crypto.util.bytesToHex(program) + 'redeemScript': redeemscript, + 'scripthash': Crypto.util.bytesToHex(program) }; } @@ -7803,7 +7805,7 @@ var n = u.getElementsByTagName("tx_output_n")[0].childNodes[0].nodeValue; var scr = script || u.getElementsByTagName("script")[0].childNodes[0].nodeValue; - if (segwit) { //also for MULTISIG_BECH32 (p2wsh-multisig)(script = raw_redeemscript; for p2wsh-multisig) + if (segwit) { //also for MULTISIG_BECH32 (p2wsh-multisig)(script = redeemscript; for p2wsh-multisig) /* this is a small hack to include the value with the redeemscript to make the signing procedure smoother. It is not standard and removed during the signing procedure. */ From 070d2198ba15b37653b47390290ceac200db4db8 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 23 Feb 2023 02:13:31 +0530 Subject: [PATCH 248/289] btcOperator v1.1.2: multisig utils - Added decodeRedeemScript: decodes the given redeemScript and return {address, pubKeys, required}. (optional bech32; default=true. if true return bech32 address. if false returns legacy multisig address) - Added convert.multisig2multisig: convert from one multisig address to another. (optional target_version; default=btc-multisig-version) - Added convert.bech2multisig: converts multisig bech32 address to multisig address. (optional target_version; default=btc-multisig-version) - Added encodeLegacy, decodeLegacy, encodeBech32, decodeBech32 to util --- btcOperator.js | 74 ++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 54 insertions(+), 20 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index 6925cec..ed967b9 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //btcOperator v1.1.1 +(function (EXPORTS) { //btcOperator v1.1.2 /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -130,50 +130,84 @@ return coinjs.pubkeys2MultisigAddress(pubKeys, minRequired); } + btcOperator.decodeRedeemScript = function (redeemScript, bech32 = true) { + let script = coinjs.script(); + let decoded = (bech32) ? + script.decodeRedeemScriptBech32(redeemScript) : + script.decodeRedeemScript(redeemScript); + if (!decoded) + return null; + return { + address: decoded.address, + pubKeys: decoded.pubkeys, + redeemScript: decoded.redeemscript, + required: decoded.signaturesRequired + } + + } + //convert from one blockchain to another blockchain (target version) btcOperator.convert = {}; btcOperator.convert.wif = function (source_wif, target_version = coinjs.priv) { - let keyHex = decodeLegacy(source_wif).hex; + let keyHex = util.decodeLegacy(source_wif).hex; if (!keyHex || keyHex.length < 66 || !/01$/.test(keyHex)) return null; else - return encodeLegacy(keyHex, target_version); + return util.encodeLegacy(keyHex, target_version); } btcOperator.convert.legacy2legacy = function (source_addr, target_version = coinjs.pub) { - let rawHex = decodeLegacy(source_addr).hex; + let rawHex = util.decodeLegacy(source_addr).hex; if (!rawHex) return null; else - return encodeLegacy(rawHex, target_version); + return util.encodeLegacy(rawHex, target_version); } btcOperator.convert.legacy2bech = function (source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) { - let rawHex = decodeLegacy(source_addr).hex; + let rawHex = util.decodeLegacy(source_addr).hex; if (!rawHex) return null; else - return encodeBech32(rawHex, target_version, target_hrp); + return util.encodeBech32(rawHex, target_version, target_hrp); } btcOperator.convert.bech2bech = function (source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) { - let rawHex = decodeBech32(source_addr).hex; + let rawHex = util.decodeBech32(source_addr).hex; if (!rawHex) return null; else - return encodeBech32(rawHex, target_version, target_hrp); + return util.encodeBech32(rawHex, target_version, target_hrp); } btcOperator.convert.bech2legacy = function (source_addr, target_version = coinjs.pub) { - let rawHex = decodeBech32(source_addr).hex; + let rawHex = util.decodeBech32(source_addr).hex; if (!rawHex) return null; else - return encodeLegacy(rawHex, target_version); + return util.encodeLegacy(rawHex, target_version); } - function decodeLegacy(source) { + btcOperator.convert.multisig2multisig = function (source_addr, target_version = coinjs.multisig) { + let rawHex = util.decodeLegacy(source_addr).hex; + if (!rawHex) + return null; + else + return util.encodeLegacy(rawHex, target_version); + } + + btcOperator.convert.bech2multisig = function (source_addr, target_version = coinjs.multisig) { + let rawHex = util.decodeBech32(source_addr).hex; + if (!rawHex) + return null; + else { + rawHex = Crypto.util.bytesToHex(ripemd160(Crypto.util.hexToBytes(rawHex), { asBytes: true })); + return util.encodeLegacy(rawHex, target_version); + } + } + + util.decodeLegacy = function (source) { var decode = coinjs.base58decode(source); var raw = decode.slice(0, decode.length - 4), checksum = decode.slice(decode.length - 4); @@ -183,7 +217,7 @@ asBytes: true }); if (hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3]) - return null; + return false; let version = raw.shift(); return { version: version, @@ -191,7 +225,7 @@ } } - function encodeLegacy(hex, version) { + util.encodeLegacy = function (hex, version) { var bytes = Crypto.util.hexToBytes(hex); bytes.unshift(version); var hash = Crypto.SHA256(Crypto.SHA256(bytes, { @@ -203,10 +237,10 @@ return coinjs.base58encode(bytes.concat(checksum)); } - function decodeBech32(source) { + util.decodeBech32 = function (source) { let decode = coinjs.bech32_decode(source); if (!decode) - return null; + return false; var raw = decode.data; let version = raw.shift(); raw = coinjs.bech32_convert(raw, 5, 8, false); @@ -217,7 +251,7 @@ } } - function encodeBech32(hex, version, hrp) { + util.encodeBech32 = function (hex, version, hrp) { var bytes = Crypto.util.hexToBytes(hex); bytes = coinjs.bech32_convert(bytes, 8, 5, true); bytes.unshift(version) @@ -706,13 +740,13 @@ var address; switch (out.script.chunks[0]) { case 0: //bech32, multisig-bech32 - address = encodeBech32(Crypto.util.bytesToHex(out.script.chunks[1]), coinjs.bech32.version, coinjs.bech32.hrp); + address = util.encodeBech32(Crypto.util.bytesToHex(out.script.chunks[1]), coinjs.bech32.version, coinjs.bech32.hrp); break; case 169: //segwit, multisig-segwit - address = encodeLegacy(Crypto.util.bytesToHex(out.script.chunks[1]), coinjs.multisig); + address = util.encodeLegacy(Crypto.util.bytesToHex(out.script.chunks[1]), coinjs.multisig); break; case 118: //legacy - address = encodeLegacy(Crypto.util.bytesToHex(out.script.chunks[2]), coinjs.pub); + address = util.encodeLegacy(Crypto.util.bytesToHex(out.script.chunks[2]), coinjs.pub); } return { address, From e4fd63912c09e23b175d8fc71a590f76a1a329da Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 23 Feb 2023 02:49:42 +0530 Subject: [PATCH 249/289] floCrypto v2.3.5: multisig address utils - Added toMultisigFloID: converts given multisig address to FLO multisig ID - Improved verifyPubKey: also support verifying multisig redeemScript for the multisig address - Improved isSameAddr: supports multisig bech32 - Improved decodeAddress: supports multisig bech32 --- floCrypto.js | 56 ++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 46 insertions(+), 10 deletions(-) diff --git a/floCrypto.js b/floCrypto.js index 19ffedc..8f0da40 100644 --- a/floCrypto.js +++ b/floCrypto.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floCrypto v2.3.4a +(function (EXPORTS) { //floCrypto v2.3.5 /* FLO Crypto Operators */ 'use strict'; const floCrypto = EXPORTS; @@ -290,13 +290,15 @@ return false; } - //Check the public-key for the address (any blockchain) + //Check the public-key (or redeem-script) for the address (any blockchain) floCrypto.verifyPubKey = function (pubKeyHex, address) { - let raw = decodeAddress(address), - pub_hash = Crypto.util.bytesToHex(ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubKeyHex), { - asBytes: true - }))); - return raw ? pub_hash === raw.hex : false; + let raw = decodeAddress(address); + if (!raw) + return; + let pub_hash = Crypto.util.bytesToHex(ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubKeyHex), { asBytes: true }))); + if (typeof raw.bech_version !== 'undefined' && raw.bytes.length == 32) //bech32-multisig + raw.hex = Crypto.util.bytesToHex(ripemd160(raw.bytes, { asBytes: true })); + return pub_hash === raw.hex; } //Convert the given address (any blockchain) to equivalent floID @@ -306,7 +308,7 @@ let raw = decodeAddress(address); if (!raw) return; - else if (options) { + else if (options) { //if (optional) version check is passed if (typeof raw.version !== 'undefined' && (!options.std || !options.std.includes(raw.version))) return; if (typeof raw.bech_version !== 'undefined' && (!options.bech || !options.bech.includes(raw.bech_version))) @@ -321,6 +323,35 @@ return bitjs.Base58.encode(raw.bytes.concat(hash.slice(0, 4))); } + //Convert the given multisig address (any blockchain) to equivalent multisig floID + floCrypto.toMultisigFloID = function (address, options = null) { + if (!address) + return; + let raw = decodeAddress(address); + if (!raw) + return; + else if (options) { //if (optional) version check is passed + if (typeof raw.version !== 'undefined' && (!options.std || !options.std.includes(raw.version))) + return; + if (typeof raw.bech_version !== 'undefined' && (!options.bech || !options.bech.includes(raw.bech_version))) + return; + } + if (typeof raw.bech_version !== 'undefined') { + if (raw.bytes.length != 32) return; //multisig bech address have 32 bytes + //multisig-bech:hash=SHA256 whereas multisig:hash=r160(SHA265), thus ripemd160 the bytes from multisig-bech + raw.bytes = ripemd160(raw.bytes, { + asBytes: true + }); + } + raw.bytes.unshift(bitjs.multisig); + let hash = Crypto.SHA256(Crypto.SHA256(raw.bytes, { + asBytes: true + }), { + asBytes: true + }); + return bitjs.Base58.encode(raw.bytes.concat(hash.slice(0, 4))); + } + //Checks if the given addresses (any blockchain) are same (w.r.t keys) floCrypto.isSameAddr = function (addr1, addr2) { if (!addr1 || !addr2) @@ -329,8 +360,13 @@ raw2 = decodeAddress(addr2); if (!raw1 || !raw2) return false; - else + else { + if (typeof raw1.bech_version !== 'undefined' && raw1.bytes.length == 32) //bech32-multisig + raw1.hex = Crypto.util.bytesToHex(ripemd160(raw1.bytes, { asBytes: true })); + if (typeof raw2.bech_version !== 'undefined' && raw2.bytes.length == 32) //bech32-multisig + raw2.hex = Crypto.util.bytesToHex(ripemd160(raw2.bytes, { asBytes: true })); return raw1.hex === raw2.hex; + } } const decodeAddress = floCrypto.decodeAddr = function (address) { @@ -350,7 +386,7 @@ hex: Crypto.util.bytesToHex(bytes), bytes } - } else if (address.length == 42) { //bech encoding + } else if (address.length == 42 || address.length == 62) { //bech encoding let decode = coinjs.bech32_decode(address); if (decode) { let bytes = decode.data; From 24415b835c8665f9310c27cd05f76a38fcf375d1 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 23 Feb 2023 22:49:32 +0530 Subject: [PATCH 250/289] lib v1.4.2: (flo) bitjs.transaction deserialize - pass tx_data (hex or byte array) to bitjs.transaction to deserialize the transaction ie, `tx = bitjs.transaction(tx_data)` - invoking without any parameter `bitjs.transaction()` will create an empty tx as before (no change) --- lib.js | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 74 insertions(+), 2 deletions(-) diff --git a/lib.js b/lib.js index 50305cf..64131f2 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function (GLOBAL) { //lib v1.4.1b +(function (GLOBAL) { //lib v1.4.2 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -4492,7 +4492,7 @@ }; } - bitjs.transaction = function () { + bitjs.transaction = function (tx_data = undefined) { var btrx = {}; btrx.version = 2; //flochange look at this version btrx.inputs = []; @@ -4992,6 +4992,78 @@ return Crypto.util.bytesToHex(buffer); } + /* deserialize a transaction */ + function deserialize(buffer) { + if (typeof buffer == "string") { + buffer = Crypto.util.hexToBytes(buffer) + } + + var pos = 0; + + var readAsInt = function (bytes) { + if (bytes == 0) return 0; + pos++; + return buffer[pos - 1] + readAsInt(bytes - 1) * 256; + } + + var readVarInt = function () { + pos++; + if (buffer[pos - 1] < 253) { + return buffer[pos - 1]; + } + return readAsInt(buffer[pos - 1] - 251); + } + + var readBytes = function (bytes) { + pos += bytes; + return buffer.slice(pos - bytes, pos); + } + + var readVarString = function () { + var size = readVarInt(); + return readBytes(size); + } + + var bytesToStr = function (bytes) { + return bytes.map(b => String.fromCharCode(b)).join(''); + } + + const self = btrx; + + self.version = readAsInt(4); + + var ins = readVarInt(); + for (var i = 0; i < ins; i++) { + self.inputs.push({ + outpoint: { + hash: Crypto.util.bytesToHex(readBytes(32).reverse()), + index: readAsInt(4) + }, + script: readVarString(), + sequence: readAsInt(4) + }); + } + + var outs = readVarInt(); + for (var i = 0; i < outs; i++) { + self.outputs.push({ + value: bitjs.bytesToNum(readBytes(8)), + script: readVarString() + }); + } + + self.lock_time = readAsInt(4); + + //flochange - floData field + self.floData = bytesToStr(readVarString()); + + return self; + } + + //deserialize the data if passed + if (tx_data) + deserialize(tx_data); + return btrx; } From 09e306d3128d8744c1ffa587c37751424f019a4d Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 23 Feb 2023 23:07:54 +0530 Subject: [PATCH 251/289] floBlockchainAPI v2.4.1: Improvements and signTx - Added createTx: create unsigned tx (resolves tx-hex ) - Updated createMultisigTx: resolve tx-hex instead of tx object - Added signTx: (synchronized fn) sign the given tx (hex or object) with given private key and returns the signed txhex --- floBlockchainAPI.js | 61 +++++++++++++++++++++++++++++++++++++-------- 1 file changed, 51 insertions(+), 10 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index d4f9bf6..7cc90c7 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.4.0 +(function (EXPORTS) { //floBlockchainAPI v2.4.1 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -121,8 +121,8 @@ }); } - //Send Tx to blockchain - const sendTx = floBlockchainAPI.sendTx = function (senderAddr, receiverAddr, sendAmt, privKey, floData = '', strict_utxo = true) { + //create a transaction with single sender + const createTx = function (senderAddr, receiverAddr, sendAmt, floData = '', strict_utxo = true) { return new Promise((resolve, reject) => { if (!floCrypto.validateASCII(floData)) return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); @@ -130,8 +130,6 @@ return reject(`Invalid address : ${senderAddr}`); else if (!floCrypto.validateFloID(receiverAddr)) return reject(`Invalid address : ${receiverAddr}`); - else if (privKey.length < 1 || !floCrypto.verifyPrivKey(privKey, senderAddr)) - return reject("Invalid Private key!"); else if (typeof sendAmt !== 'number' || sendAmt <= 0) return reject(`Invalid sendAmt : ${sendAmt}`); @@ -175,15 +173,36 @@ if (change > DEFAULT.minChangeAmt) trx.addoutput(senderAddr, change); trx.addflodata(floData.replace(/\n/g, ' ')); - var signedTxHash = trx.sign(privKey, 1); - broadcastTx(signedTxHash) - .then(txid => resolve(txid)) - .catch(error => reject(error)) + resolve(trx); } }).catch(error => reject(error)) }).catch(error => reject(error)) }).catch(error => reject(error)) }).catch(error => reject(error)) + }) + } + + floBlockchainAPI.createTx = function (senderAddr, receiverAddr, sendAmt, floData = '', strict_utxo = true) { + return new Promise((resolve, reject) => { + createTx(senderAddr, receiverAddr, sendAmt, floData, strict_utxo) + .then(trx => resolve(trx.serialize())) + .catch(error => reject(error)) + }) + } + + //Send Tx to blockchain + const sendTx = floBlockchainAPI.sendTx = function (senderAddr, receiverAddr, sendAmt, privKey, floData = '', strict_utxo = true) { + return new Promise((resolve, reject) => { + if (!floCrypto.validateFloID(senderAddr, true)) + return reject(`Invalid address : ${senderAddr}`); + else if (privKey.length < 1 || !floCrypto.verifyPrivKey(privKey, senderAddr)) + return reject("Invalid Private key!"); + createTx(senderAddr, receiverAddr, sendAmt, floData, strict_utxo).then(trx => { + var signedTxHash = trx.sign(privKey, 1); + broadcastTx(signedTxHash) + .then(txid => resolve(txid)) + .catch(error => reject(error)) + }).catch(error => reject(error)) }); } @@ -419,7 +438,7 @@ } //Create a multisig transaction - const createMultisigTx = floBlockchainAPI.createMultisigTx = function (redeemScript, receivers, amounts, floData = '', strict_utxo = true) { + const createMultisigTx = function (redeemScript, receivers, amounts, floData = '', strict_utxo = true) { return new Promise((resolve, reject) => { var multisig = floCrypto.decodeRedeemScript(redeemScript); @@ -499,6 +518,15 @@ }); } + //Same as above, but explict call should return serialized tx-hex + floBlockchainAPI.createMultisigTx = function (redeemScript, receivers, amounts, floData = '', strict_utxo = true) { + return new Promise((resolve, reject) => { + createMultisigTx(redeemScript, receivers, amounts, floData, strict_utxo) + .then(trx => resolve(trx.serialize())) + .catch(error => reject(error)) + }) + } + //Create and send multisig transaction const sendMultisigTx = floBlockchainAPI.sendMultisigTx = function (redeemScript, privateKeys, receivers, amounts, floData = '', strict_utxo = true) { return new Promise((resolve, reject) => { @@ -538,6 +566,19 @@ }) } + floBlockchainAPI.signTx = function (tx, privateKey, sighashtype = 1) { + if (!floCrypto.getFloID(privateKey)) + throw "Invalid Private key"; + //deserialize if needed + if (!(tx instanceof Object)) { + if (typeof tx === 'string' || Array.isArray(tx)) + tx = bitjs.transaction(tx) + } else if (typeof tx.sign !== 'function') + throw "Tx is not a instance of transaction"; + var signedTxHex = tx.sign(privateKey); + return signedTxHex; + } + //Broadcast signed Tx in blockchain using API const broadcastTx = floBlockchainAPI.broadcastTx = function (signedTxHash) { return new Promise((resolve, reject) => { From daec31c1ac16c33372bc9020a1f2131f0269e8b6 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 23 Feb 2023 23:24:55 +0530 Subject: [PATCH 252/289] btcOperator v1.1.2a: bug fix - Fixed: checkIfSameTx loop in comparing outputs using incorrect length --- btcOperator.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/btcOperator.js b/btcOperator.js index ed967b9..ff86fb9 100644 --- a/btcOperator.js +++ b/btcOperator.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //btcOperator v1.1.2 +(function (EXPORTS) { //btcOperator v1.1.2a /* BTC Crypto and API Operator */ const btcOperator = EXPORTS; @@ -703,12 +703,15 @@ btcOperator.checkIfSameTx = function (tx1, tx2) { tx1 = deserializeTx(tx1); tx2 = deserializeTx(tx2); + //compare input and output length if (tx1.ins.length !== tx2.ins.length || tx1.outs.length !== tx2.outs.length) return false; + //compare inputs for (let i = 0; i < tx1.ins.length; i++) if (tx1.ins[i].outpoint.hash !== tx2.ins[i].outpoint.hash || tx1.ins[i].outpoint.index !== tx2.ins[i].outpoint.index) return false; - for (let i = 0; i < tx2.ins.length; i++) + //compare outputs + for (let i = 0; i < tx1.outs.length; i++) if (tx1.outs[i].value !== tx2.outs[i].value || Crypto.util.bytesToHex(tx1.outs[i].script.buffer) !== Crypto.util.bytesToHex(tx2.outs[i].script.buffer)) return false; return true; From 7b298ceb50ba696c3c0914e696d3869643e48b2b Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 24 Feb 2023 00:04:06 +0530 Subject: [PATCH 253/289] floBlockchainAPI v2.4.2: tx utility fns - Added checkSigned: check if the tx is signed or not (if optional args is passed as false, returns a detailed array indicating if each input is signed or not) - Added checkIfSameTx: check if the passed 2 tx are same or not (ie, input, output and flodata are same or not) - Added transactionID: returns the transaction id of the tx hex --- floBlockchainAPI.js | 84 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 77 insertions(+), 7 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 7cc90c7..76ea569 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.4.1 +(function (EXPORTS) { //floBlockchainAPI v2.4.2 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -566,19 +566,89 @@ }) } + function deserializeTx(tx) { + if (typeof tx === 'string' || Array.isArray(tx)) { + try { + tx = bitjs.transaction(tx); + } catch { + throw "Invalid transaction hex"; + } + } else if (typeof tx !== 'object' || typeof tx.sign !== 'function') + throw "Invalid transaction object"; + return tx; + } + floBlockchainAPI.signTx = function (tx, privateKey, sighashtype = 1) { if (!floCrypto.getFloID(privateKey)) throw "Invalid Private key"; //deserialize if needed - if (!(tx instanceof Object)) { - if (typeof tx === 'string' || Array.isArray(tx)) - tx = bitjs.transaction(tx) - } else if (typeof tx.sign !== 'function') - throw "Tx is not a instance of transaction"; - var signedTxHex = tx.sign(privateKey); + tx = deserializeTx(tx); + var signedTxHex = tx.sign(privateKey, sighashtype); return signedTxHex; } + floBlockchainAPI.checkSigned = function (tx, bool = true) { + tx = deserializeTx(tx); + let n = []; + for (let i = 0; i < tx.inputs.length; i++) { + var s = tx.scriptDecode(i); + if (s['type'] === 'scriptpubkey') + n.push(s.signed); + else if (s['type'] === 'multisig') { + var rs = tx.decodeRedeemScript(s['rs']); + let x = { + s: 0, + r: rs['required'], + t: rs['pubkeys'].length + }; + //check input script for signatures + var script = Array.from(tx.inputs[i].script); + if (script[0] == 0) { //script with signatures + script = tx.parseScript(script); + for (var k = 0; k < script.length; k++) + if (Array.isArray(script[k]) && script[k][0] == 48) //0x30 DERSequence + x.s++; + } + //validate counts + if (x.r > x.t) + throw "signaturesRequired is more than publicKeys"; + else if (x.s < x.r) + n.push(x); + else + n.push(true); + } + } + return bool ? !(n.filter(x => x !== true).length) : n; + } + + floBlockchainAPI.checkIfSameTx = function (tx1, tx2) { + tx1 = deserializeTx(tx1); + tx2 = deserializeTx(tx2); + //compare input and output length + if (tx1.inputs.length !== tx2.inputs.length || tx1.outputs.length !== tx2.outputs.length) + return false; + //compare flodata + if (tx1.floData !== tx2.floData) + return false + //compare inputs + for (let i = 0; i < tx1.inputs.length; i++) + if (tx1.inputs[i].outpoint.hash !== tx2.inputs[i].outpoint.hash || tx1.inputs[i].outpoint.index !== tx2.inputs[i].outpoint.index) + return false; + //compare outputs + for (let i = 0; i < tx1.outputs.length; i++) + if (tx1.outputs[i].value !== tx2.outputs[i].value || Crypto.util.bytesToHex(tx1.outputs[i].script) !== Crypto.util.bytesToHex(tx2.outputs[i].script)) + return false; + return true; + } + + floBlockchainAPI.transactionID = function (tx) { + tx = deserializeTx(tx); + let clone = bitjs.clone(tx); + let raw_bytes = Crypto.util.hexToBytes(clone.serialize()); + let txid = Crypto.SHA256(Crypto.SHA256(raw_bytes, { asBytes: true }), { asBytes: true }).reverse(); + return Crypto.util.bytesToHex(txid); + } + //Broadcast signed Tx in blockchain using API const broadcastTx = floBlockchainAPI.broadcastTx = function (signedTxHash) { return new Promise((resolve, reject) => { From 9db998c17652b3c1151cc60d00e5c3c485129e0f Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 24 Feb 2023 00:46:00 +0530 Subject: [PATCH 254/289] floBlockchainAPI v2.4.3: utility fns - Added parseTransaction: parse the given txhex - Added Sat_to_FLO and FLO_to_Sat to .util --- floBlockchainAPI.js | 66 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 64 insertions(+), 2 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 76ea569..35f1e0a 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.4.2 +(function (EXPORTS) { //floBlockchainAPI v2.4.3 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -15,6 +15,13 @@ receiverID: floGlobals.adminID }; + const SATOSHI_IN_BTC = 1e8; + + const util = floBlockchainAPI.util = {}; + + util.Sat_to_FLO = value => parseFloat((value / SATOSHI_IN_BTC).toFixed(8)); + util.FLO_to_Sat = value => parseInt(value * SATOSHI_IN_BTC); + Object.defineProperties(floBlockchainAPI, { sendAmt: { get: () => DEFAULT.sendAmt, @@ -587,7 +594,7 @@ return signedTxHex; } - floBlockchainAPI.checkSigned = function (tx, bool = true) { + const checkSigned = floBlockchainAPI.checkSigned = function (tx, bool = true) { tx = deserializeTx(tx); let n = []; for (let i = 0; i < tx.inputs.length; i++) { @@ -649,6 +656,61 @@ return Crypto.util.bytesToHex(txid); } + const getTxOutput = (txid, i) => new Promise((resolve, reject) => { + fetch_api(`api/tx/${txid}`) + .then(result => resolve(result.vout[i])) + .catch(error => reject(error)) + }); + + function getOutputAddress(outscript) { + var bytes, version; + switch (outscript[0]) { + case 118: //legacy + bytes = outscript.slice(3, outscript.length - 2); + version = bitjs.pub; + break + case 169: //multisig + bytes = outscript.slice(2, outscript.length - 1); + version = bitjs.multisig; + break; + default: return; //unknown + } + bytes.unshift(version); + var hash = Crypto.SHA256(Crypto.SHA256(bytes, { asBytes: true }), { asBytes: true }); + var checksum = hash.slice(0, 4); + return bitjs.Base58.encode(bytes.concat(checksum)); + } + + floBlockchainAPI.parseTransaction = function (tx) { + return new Promise((resolve, reject) => { + tx = deserializeTx(tx); + let result = {}; + let promises = []; + //Parse Inputs + for (let i = 0; i < tx.inputs.length; i++) + promises.push(getTxOutput(tx.inputs[i].outpoint.hash, tx.inputs[i].outpoint.index)); + Promise.all(promises).then(inputs => { + result.inputs = inputs.map(inp => Object({ + address: inp.scriptPubKey.addresses[0], + value: parseFloat(inp.value) + })); + let signed = checkSigned(tx, false); + result.inputs.forEach((inp, i) => inp.signed = signed[i]); + //Parse Outputs + result.outputs = tx.outputs.map(out => Object({ + address: getOutputAddress(out.script), + value: util.Sat_to_FLO(out.value) + })) + //Parse Totals + result.total_input = parseFloat(result.inputs.reduce((a, inp) => a += inp.value, 0).toFixed(8)); + result.total_output = parseFloat(result.outputs.reduce((a, out) => a += out.value, 0).toFixed(8)); + result.fee = parseFloat((result.total_input - result.total_output).toFixed(8)); + result.floData = tx.floData; + resolve(result); + }).catch(error => reject(error)) + }) + } + //Broadcast signed Tx in blockchain using API const broadcastTx = floBlockchainAPI.broadcastTx = function (signedTxHash) { return new Promise((resolve, reject) => { From 476b95c6795dcb10e7790a0050818c78df2f4eda Mon Sep 17 00:00:00 2001 From: Sai Raj <39055732+sairajzero@users.noreply.github.com> Date: Fri, 24 Feb 2023 02:12:46 +0530 Subject: [PATCH 255/289] Create LICENCE --- LICENCE | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENCE diff --git a/LICENCE b/LICENCE new file mode 100644 index 0000000..d3f4c4c --- /dev/null +++ b/LICENCE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Sai Raj + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From bf9e018883e0db1e70f1ae4d20f280bff8f00973 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 24 Feb 2023 18:34:49 +0530 Subject: [PATCH 256/289] lib v1.4.2a and floCrypto v2.3.5a lib v1.4.2a - Fixed multisig for testnet floCrypto v2.3.5a - Fixed: getMultisigAddress accepting requiredSignatures value greater than pubkeys array length (now it will return null instead) --- floCrypto.js | 4 ++-- lib.js | 23 ++++++++++++++--------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/floCrypto.js b/floCrypto.js index 8f0da40..ec41da4 100644 --- a/floCrypto.js +++ b/floCrypto.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floCrypto v2.3.5 +(function (EXPORTS) { //floCrypto v2.3.5a /* FLO Crypto Operators */ 'use strict'; const floCrypto = EXPORTS; @@ -234,7 +234,7 @@ floCrypto.getMultisigAddress = function (publicKeyList, requiredSignatures) { if (!Array.isArray(publicKeyList) || !publicKeyList.length) return null; - if (!Number.isInteger(requiredSignatures) || requiredSignatures < 1) + if (!Number.isInteger(requiredSignatures) || requiredSignatures < 1 || requiredSignatures > publicKeyList.length) return null; try { var multisig = bitjs.pubkeys2multisig(publicKeyList, requiredSignatures); diff --git a/lib.js b/lib.js index 64131f2..b4a41e2 100644 --- a/lib.js +++ b/lib.js @@ -1,4 +1,4 @@ -(function (GLOBAL) { //lib v1.4.2 +(function (GLOBAL) { //lib v1.4.2a 'use strict'; /* Utility Libraries required for Standard operations * All credits for these codes belong to their respective creators, moderators and owners. @@ -4355,6 +4355,12 @@ bitjs.multisig = 0x5e; //flochange - prefix for FLO Mainnet Multisig 0x5e bitjs.compressed = false; + if (GLOBAL.cryptocoin == 'FLO_TEST') { + bitjs.pub = 0x73; // flochange - changed the prefix to FLO TestNet PublicKey Prefix 0x73 + bitjs.priv = 0xa3; //flochange - changed the prefix to FLO TestNet Private key prefix 0xa3 + bitjs.multisig = 0xc6; //flochange - prefix for FLO TestNet Multisig 0xc6 + } + /* provide a privkey and return an WIF */ bitjs.privkey2wif = function (h) { var r = Crypto.util.hexToBytes(h); @@ -5301,23 +5307,22 @@ if ("string" == typeof bytes) { var d = Bitcoin.Address.decodeString(bytes); bytes = d.hash; - if (GLOBAL.cryptocoin == "FLO" && (d.version == Bitcoin.Address.standardVersion || d.version == Bitcoin.Address.multisigVersion)) - this.version = d.version; - else if (GLOBAL.cryptocoin == "FLO_TEST" && d.version == Bitcoin.Address.testnetVersion) + if (d.version == Bitcoin.Address.standardVersion || d.version == Bitcoin.Address.multisigVersion) this.version = d.version; else throw "Version (prefix) " + d.version + " not supported!"; } else { - if (GLOBAL.cryptocoin == "FLO") - this.version = Bitcoin.Address.standardVersion; - else if (GLOBAL.cryptocoin == "FLO_TEST") - this.version = Bitcoin.Address.testnetVersion; // FLO testnet public address + this.version = Bitcoin.Address.standardVersion; } this.hash = bytes; }; Bitcoin.Address.standardVersion = 0x23; // (FLO mainnet 0x23, 35D), (Bitcoin Mainnet, 0x00, 0D) Bitcoin.Address.multisigVersion = 0x5e; // (FLO multisig 0x5e, 94D) - Bitcoin.Address.testnetVersion = 0x73; // (FLO testnet 0x73, 115D) + + if (GLOBAL.cryptocoin == "FLO_TEST") { + Bitcoin.Address.standardVersion = 0x73; // (FLO testnet 0x73, 115D), (Bitcoin Mainnet, 0x00, 0D) + Bitcoin.Address.multisigVersion = 0xc6; // (FLO testnet multisig 0xc6, 198D) + } /** * Serialize this object as a standard Bitcoin address. From 1a8e1abe45b91a38dfcb46b4ce3e10407efdcf62 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 24 Feb 2023 18:49:22 +0530 Subject: [PATCH 257/289] Update index.html Only for Testing purpose - Added quick param: pass quick in url query to ignore onLoadStartup - Added testnet param: pass testnet in url query to change blockchain to FLO_TEST (testnet FLO) --- index.html | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/index.html b/index.html index 7ec9496..b541802 100644 --- a/index.html +++ b/index.html @@ -11,6 +11,21 @@ application: "TEST_MODE", } + @@ -21,7 +36,7 @@ @@ -1821,10 +1821,15 @@ // remove digitals after specified decimal places without rounding function toFixed(num, fixed = 8) { - var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?'); - return parseFloat(num.toString().match(re)[0]); + const re = new RegExp(`^-?\\d+(?:\\.\\d{0,${fixed}})?`); + const match = num.toString().match(re); + if (!match) { + return NaN; + } + return parseFloat(match[0]); } + function getSuggestedPrice(asset = pagesData.params.asset || 'FLO') { return toFixed(parseFloat(floGlobals.exchangeRates[asset]) * deviation[tradeType]) } @@ -2729,10 +2734,10 @@ getRef('market_asset_rates').append(createElement('li', { className: 'listed-asset grid align-center', innerHTML: ` -
${getIcon(asset)}
-

${asset}

- ${formatAmount(rate)} - ` +
${getIcon(asset)}
+

${asset}

+ ${formatAmount(rate)} + ` })) }) resolve(); @@ -2766,6 +2771,7 @@ showSuggestedPrice() }).catch(error => { notify(error.message, 'error'); + reject(error) }) }).catch(error => console.error(error)) } From 9c0730e051f8cec2191869ef70dab6a066b140a3 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 13 Apr 2023 03:15:26 +0530 Subject: [PATCH 269/289] floBlockchainAPI v2.4.5: getBalance improvements - Updated getBalance: now chain queries for addr with more than 1000 tx to get the net balance. - (optional): can use 'after' parameter to get the balance(update) after a given txid --- floBlockchainAPI.js | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 3ddf7ee..e43a888 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.4.4 +(function (EXPORTS) { //floBlockchainAPI v2.4.5 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -21,6 +21,7 @@ util.Sat_to_FLO = value => parseFloat((value / SATOSHI_IN_BTC).toFixed(8)); util.FLO_to_Sat = value => parseInt(value * SATOSHI_IN_BTC); + util.toFixed = value => parseFloat((value).toFixed(8)); Object.defineProperties(floBlockchainAPI, { sendAmt: { @@ -120,11 +121,21 @@ } //Get balance for the given Address - const getBalance = floBlockchainAPI.getBalance = function (addr) { + const getBalance = floBlockchainAPI.getBalance = function (addr, after = null) { return new Promise((resolve, reject) => { - promisedAPI(`api/addr/${addr}/balance`) - .then(balance => resolve(parseFloat(balance))) - .catch(error => reject(error)); + let api = `api/addr/${addr}/balance`; + if (after) { + if (typeof after === 'string' && /^[0-9a-z]{64}$/i.test(after)) + api += '?after=' + after; + else return reject("Invalid 'after' parameter"); + } + promisedAPI(api).then(result => { + if (typeof result === 'object' && result.lastItem) { + getBalance(addr, result.lastItem) + .then(r => resolve(util.toFixed(r + result.data))) + .catch(error => reject(error)) + } else resolve(result); + }).catch(error => reject(error)) }); } From ca0d8c68f3ce1fc3bc8fc73006c923be859d90b9 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 14 Apr 2023 03:36:23 +0530 Subject: [PATCH 270/289] floBlockchainAPI v2.4.6 Improved utxo and unconfirmed-spent api fetch in send/create tx --- floBlockchainAPI.js | 160 +++++++++++++++++++++----------------------- 1 file changed, 77 insertions(+), 83 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index e43a888..908548d 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.4.5 +(function (EXPORTS) { //floBlockchainAPI v2.4.6 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -139,6 +139,28 @@ }); } + const getUTXOs = address => new Promise((resolve, reject) => { + promisedAPI(`api/addr/${address}/utxo`) + .then(utxo => resolve(utxo)) + .catch(error => reject(error)) + }) + + const getUnconfirmedSpent = address => new Promise((resolve, reject) => { + readTxs(address, { mempool: "only" }).then(result => { + let unconfirmedSpent = {}; + for (let tx of result.items) + if (tx.confirmations == 0) + for (let vin of tx.vin) + if (vin.addr === address) { + if (Array.isArray(unconfirmedSpent[vin.txid])) + unconfirmedSpent[vin.txid].push(vin.vout); + else + unconfirmedSpent[vin.txid] = [vin.vout]; + } + resolve(unconfirmedSpent); + }).catch(error => reject(error)) + }) + //create a transaction with single sender const createTx = function (senderAddr, receiverAddr, sendAmt, floData = '', strict_utxo = true) { return new Promise((resolve, reject) => { @@ -155,45 +177,31 @@ var fee = DEFAULT.fee; if (balance < sendAmt + fee) return reject("Insufficient FLO balance!"); - //get unconfirmed tx list - promisedAPI(`api/addr/${senderAddr}`).then(result => { - readTxs(senderAddr, 0, result.unconfirmedTxApperances).then(result => { - let unconfirmedSpent = {}; - for (let tx of result.items) - if (tx.confirmations == 0) - for (let vin of tx.vin) - if (vin.addr === senderAddr) { - if (Array.isArray(unconfirmedSpent[vin.txid])) - unconfirmedSpent[vin.txid].push(vin.vout); - else - unconfirmedSpent[vin.txid] = [vin.vout]; - } - //get utxos list - promisedAPI(`api/addr/${senderAddr}/utxo`).then(utxos => { - //form/construct the transaction data - var trx = bitjs.transaction(); - var utxoAmt = 0.0; - for (var i = utxos.length - 1; - (i >= 0) && (utxoAmt < sendAmt + fee); i--) { - //use only utxos with confirmations (strict_utxo mode) - if (utxos[i].confirmations || !strict_utxo) { - if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout)) - continue; //A transaction has already used the utxo, but is unconfirmed. - trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); - utxoAmt += utxos[i].amount; - }; - } - if (utxoAmt < sendAmt + fee) - reject("Insufficient FLO: Some UTXOs are unconfirmed"); - else { - trx.addoutput(receiverAddr, sendAmt); - var change = utxoAmt - sendAmt - fee; - if (change > DEFAULT.minChangeAmt) - trx.addoutput(senderAddr, change); - trx.addflodata(floData.replace(/\n/g, ' ')); - resolve(trx); - } - }).catch(error => reject(error)) + getUnconfirmedSpent(senderAddr).then(unconfirmedSpent => { + getUTXOs(senderAddr).then(utxos => { + //form/construct the transaction data + var trx = bitjs.transaction(); + var utxoAmt = 0.0; + for (var i = utxos.length - 1; + (i >= 0) && (utxoAmt < sendAmt + fee); i--) { + //use only utxos with confirmations (strict_utxo mode) + if (utxos[i].confirmations || !strict_utxo) { + if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout)) + continue; //A transaction has already used the utxo, but is unconfirmed. + trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); + utxoAmt += utxos[i].amount; + }; + } + if (utxoAmt < sendAmt + fee) + reject("Insufficient FLO: Some UTXOs are unconfirmed"); + else { + trx.addoutput(receiverAddr, sendAmt); + var change = utxoAmt - sendAmt - fee; + if (change > DEFAULT.minChangeAmt) + trx.addoutput(senderAddr, change); + trx.addflodata(floData.replace(/\n/g, ' ')); + resolve(trx); + } }).catch(error => reject(error)) }).catch(error => reject(error)) }).catch(error => reject(error)) @@ -249,7 +257,7 @@ var trx = bitjs.transaction(); var utxoAmt = 0.0; var fee = DEFAULT.fee; - promisedAPI(`api/addr/${floID}/utxo`).then(utxos => { + getUTXOs(floID).then(utxos => { for (var i = utxos.length - 1; i >= 0; i--) if (utxos[i].confirmations) { trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); @@ -416,7 +424,7 @@ //Get the UTXOs of the senders let promises = []; for (let floID in senders) - promises.push(promisedAPI(`api/addr/${floID}/utxo`)); + promises.push(getUTXOs(floID)); Promise.all(promises).then(results => { var trx = bitjs.transaction(); for (let floID in senders) { @@ -490,46 +498,32 @@ var fee = DEFAULT.fee; if (balance < sendAmt + fee) return reject("Insufficient FLO balance!"); - //get unconfirmed tx list - promisedAPI(`api/addr/${senderAddr}`).then(result => { - readTxs(senderAddr, 0, result.unconfirmedTxApperances).then(result => { - let unconfirmedSpent = {}; - for (let tx of result.items) - if (tx.confirmations == 0) - for (let vin of tx.vin) - if (vin.addr === senderAddr) { - if (Array.isArray(unconfirmedSpent[vin.txid])) - unconfirmedSpent[vin.txid].push(vin.vout); - else - unconfirmedSpent[vin.txid] = [vin.vout]; - } - //get utxos list - promisedAPI(`api/addr/${senderAddr}/utxo`).then(utxos => { - //form/construct the transaction data - var trx = bitjs.transaction(); - var utxoAmt = 0.0; - for (var i = utxos.length - 1; - (i >= 0) && (utxoAmt < sendAmt + fee); i--) { - //use only utxos with confirmations (strict_utxo mode) - if (utxos[i].confirmations || !strict_utxo) { - if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout)) - continue; //A transaction has already used the utxo, but is unconfirmed. - trx.addinput(utxos[i].txid, utxos[i].vout, redeemScript); //for multisig, script=redeemScript - utxoAmt += utxos[i].amount; - }; - } - if (utxoAmt < sendAmt + fee) - reject("Insufficient FLO: Some UTXOs are unconfirmed"); - else { - for (let i in receivers) - trx.addoutput(receivers[i], amounts[i]); - var change = utxoAmt - sendAmt - fee; - if (change > DEFAULT.minChangeAmt) - trx.addoutput(senderAddr, change); - trx.addflodata(floData.replace(/\n/g, ' ')); - resolve(trx); - } - }).catch(error => reject(error)) + getUnconfirmedSpent(senderAddr).then(unconfirmedSpent => { + getUTXOs(senderAddr).then(utxos => { + //form/construct the transaction data + var trx = bitjs.transaction(); + var utxoAmt = 0.0; + for (var i = utxos.length - 1; + (i >= 0) && (utxoAmt < sendAmt + fee); i--) { + //use only utxos with confirmations (strict_utxo mode) + if (utxos[i].confirmations || !strict_utxo) { + if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout)) + continue; //A transaction has already used the utxo, but is unconfirmed. + trx.addinput(utxos[i].txid, utxos[i].vout, redeemScript); //for multisig, script=redeemScript + utxoAmt += utxos[i].amount; + }; + } + if (utxoAmt < sendAmt + fee) + reject("Insufficient FLO: Some UTXOs are unconfirmed"); + else { + for (let i in receivers) + trx.addoutput(receivers[i], amounts[i]); + var change = utxoAmt - sendAmt - fee; + if (change > DEFAULT.minChangeAmt) + trx.addoutput(senderAddr, change); + trx.addflodata(floData.replace(/\n/g, ' ')); + resolve(trx); + } }).catch(error => reject(error)) }).catch(error => reject(error)) }).catch(error => reject(error)) @@ -668,7 +662,7 @@ } const getTxOutput = (txid, i) => new Promise((resolve, reject) => { - fetch_api(`api/tx/${txid}`) + promisedAPI(`api/tx/${txid}`) .then(result => resolve(result.vout[i])) .catch(error => reject(error)) }); From a296a5c986f78378764e67bfccd02277e2daa4a0 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 14 Apr 2023 03:52:39 +0530 Subject: [PATCH 271/289] floBlockchainAPI v2.5.0 1. Updated readTxs: from, to parameter are replaced with options parameter. 'options' available - after: query after the given tx - from/to: query from and to (deprecated, support for backward compatibility) - mempool: query mempool values (true, false, only) 2. Updated readAllTxs: chain queries the data from flosight when address have too many tx --- floBlockchainAPI.js | 44 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 9 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 908548d..6f361d9 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.4.6 +(function (EXPORTS) { //floBlockchainAPI v2.5.0 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -745,23 +745,49 @@ }) } + const isUndefined = val => typeof val === 'undefined'; + //Read Txs of Address between from and to - const readTxs = floBlockchainAPI.readTxs = function (addr, from, to) { + const readTxs = floBlockchainAPI.readTxs = function (addr, options = {}) { return new Promise((resolve, reject) => { - promisedAPI(`api/addrs/${addr}/txs?from=${from}&to=${to}`) + let api = `api/addrs/${addr}/txs`; + //API options + let api_options = []; + if (!isUndefined(options.after)) + api_options.push(`after=${options.after}`); + else { + if (!isUndefined(options.from)) + api_options.push(`from=${options.from}`); + if (!isUndefined(options.to)) + api_options.push(`to=${options.to}`); + } + if (!isUndefined(options.mempool)) + api_options.push(`mempool=${options.mempool}`) + if (api_options.length) + api += "?" + api_options.join('&'); + promisedAPI(api) .then(response => resolve(response)) .catch(error => reject(error)) }); } //Read All Txs of Address (newest first) - floBlockchainAPI.readAllTxs = function (addr) { + const readAllTxs = floBlockchainAPI.readAllTxs = function (addr, options) { return new Promise((resolve, reject) => { - promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => { - promisedAPI(`api/addrs/${addr}/txs?from=0&to=${response.totalItems}0`) - .then(response => resolve(response.items)) - .catch(error => reject(error)); - }).catch(error => reject(error)) + readTxs(addr, options).then(response => { + if (response.incomplete) { + let next_options = Object.assign({}, options); + next_options.after = response.lastItem; + readAllTxs(addr, next_options).then(r => { + r.items = r.items.concat(response.items); //latest tx are 1st in array + resolve(r); + }).catch(error => reject(error)) + } else + resolve({ + lastKey: response.lastItem || options.after, + items: response.items + }); + }) }); } From e37e808a98d489f6ddf0cda6610a2293b617df96 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sat, 15 Apr 2023 00:37:59 +0530 Subject: [PATCH 272/289] floBlockchainAPI v2.5.1: updated readData - uses readAllTxs to chain query the txs from flosight - keeping ignoreOld option to support backward compatibility, but resolved value no longer have totalTxs. - new option 'after': fetch after the given txid - new option 'mempool': query mempool tx or not (options same as readAllTx, DEFAULT=false: ignore unconfirmed tx) - the resolved value have the following structure based on options.tx true: {lastKey, items} false (DEFAULT}: {lastKey, data} - Optimized the query and filter process --- floBlockchainAPI.js | 160 +++++++++++++++++++------------------------- 1 file changed, 68 insertions(+), 92 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 6f361d9..4b13f39 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.5.0 +(function (EXPORTS) { //floBlockchainAPI v2.5.1 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -793,8 +793,9 @@ /*Read flo Data from txs of given Address options can be used to filter data - limit : maximum number of filtered data (default = 1000, negative = no limit) - ignoreOld : ignore old txs (default = 0) + after : query after the given txid + mempool : query mempool tx or not (options same as readAllTx, DEFAULT=false: ignore unconfirmed tx) + ignoreOld : ignore old txs (deprecated: support for backward compatibility only, cannot be used with 'after') sentOnly : filters only sent data receivedOnly: filters only received data pattern : filters data that with JSON pattern @@ -804,98 +805,73 @@ receiver : flo-id(s) of receiver */ floBlockchainAPI.readData = function (addr, options = {}) { - options.limit = options.limit || 0; - options.ignoreOld = options.ignoreOld || 0; - if (typeof options.senders === "string") options.senders = [options.senders]; - if (typeof options.receivers === "string") options.receivers = [options.receivers]; return new Promise((resolve, reject) => { - promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => { - var newItems = response.totalItems - options.ignoreOld; - promisedAPI(`api/addrs/${addr}/txs?from=0&to=${newItems * 2}`).then(response => { - if (options.limit <= 0) - options.limit = response.items.length; - var filteredData = []; - let numToRead = response.totalItems - options.ignoreOld, - unconfirmedCount = 0; - for (let i = 0; i < numToRead && filteredData.length < options.limit; i++) { - if (!response.items[i].confirmations) { //unconfirmed transactions - unconfirmedCount++; - if (numToRead < response.items[i].length) - numToRead++; - continue; - } - if (options.pattern) { - try { - let jsonContent = JSON.parse(response.items[i].floData); - if (!Object.keys(jsonContent).includes(options.pattern)) - continue; - } catch (error) { - continue; - } - } - if (options.sentOnly) { - let flag = false; - for (let vin of response.items[i].vin) - if (vin.addr === addr) { - flag = true; - break; - } - if (!flag) continue; - } - if (Array.isArray(options.senders)) { - let flag = false; - for (let vin of response.items[i].vin) - if (options.senders.includes(vin.addr)) { - flag = true; - break; - } - if (!flag) continue; - } - if (options.receivedOnly) { - let flag = false; - for (let vout of response.items[i].vout) - if (vout.scriptPubKey.addresses[0] === addr) { - flag = true; - break; - } - if (!flag) continue; - } - if (Array.isArray(options.receivers)) { - let flag = false; - for (let vout of response.items[i].vout) - if (options.receivers.includes(vout.scriptPubKey.addresses[0])) { - flag = true; - break; - } - if (!flag) continue; - } - if (options.filter && !options.filter(response.items[i].floData)) - continue; - if (options.tx) { - let d = {} - d.txid = response.items[i].txid; - d.time = response.items[i].time; - d.blockheight = response.items[i].blockheight; - d.senders = new Set(response.items[i].vin.map(v => v.addr)); - d.receivers = new Set(response.items[i].vout.map(v => v.scriptPubKey.addresses[0])); - d.data = response.items[i].floData; - filteredData.push(d); - } else - filteredData.push(response.items[i].floData); + //fetch options + let fetch_options = {}; + fetch_options.mempool = isUndefined(options.mempool) ? 'false' : options.mempool; //DEFAULT: ignore unconfirmed tx + if (!isUndefined(options.after)) { + if (!isUndefined(options.ignoreOld)) //Backward support + return reject("Invalid options: cannot use after and ignoreOld in same query"); + else + fetch_options.after = options.after; + } + readAllTxs(addr, fetch_options).then(response => { + + if (Number.isInteger(options.ignoreOld)) //backward support, cannot be used with options.after + response.items.splice(-options.ignoreOld); //negative to count from end of the array + + if (typeof options.senders === "string") options.senders = [options.senders]; + if (typeof options.receivers === "string") options.receivers = [options.receivers]; + + //filter the txs based on options + const filteredData = response.items.filter(tx => { + + if (!tx.confirmations) //unconfirmed transactions: this should not happen as we send mempool=false in API query + return false; + + if (options.sentOnly && !tx.vin.some(vin => vin.addr === addr)) + return false; + else if (Array.isArray(options.senders) && !tx.vin.some(vin => options.senders.includes(vin.addr))) + return false; + + if (options.receivedOnly && !tx.vout.some(vout => vout.scriptPubKey.addresses[0] === addr)) + return false; + else if (Array.isArray(options.receivers) && !tx.vout.some(vout => options.receivers.includes(vout.scriptPubKey.addresses[0]))) + return false; + + if (options.pattern) { + try { + let jsonContent = JSON.parse(tx.floData); + if (!Object.keys(jsonContent).includes(options.pattern)) + return false; + } catch { + return false; + } } - resolve({ - totalTxs: response.totalItems - unconfirmedCount, - data: filteredData - }); - }).catch(error => { - reject(error); - }); - }).catch(error => { - reject(error); - }); - }); + + if (options.filter && !options.filter(tx.floData)) + return false; + + return true; + }).map(tx => options.tx ? { + txid: tx.txid, + time: tx.time, + blockheight: tx.blockheight, + senders: new Set(tx.vin.map(v => v.addr)), + receivers: new Set(tx.vout.map(v => v.scriptPubKey.addresses[0])), + data: tx.floData + } : tx.floData); + + const result = { lastKey: response.lastKey }; + if (options.tx) + result.items = filteredData; + else + result.data = filteredData + resolve(result); + + }).catch(error => reject(error)) + }) } - })('object' === typeof module ? module.exports : window.floBlockchainAPI = {}); \ No newline at end of file From 456e9097de6d802fae40edc9f8e0cb1732d02641 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sat, 29 Apr 2023 03:03:45 +0530 Subject: [PATCH 273/289] floBlockchainAPI v2.5.2: Added splitUTXOs - splitUTXOs: split sufficient UTXOs of a given floID for a parallel sending --- floBlockchainAPI.js | 52 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 4b13f39..cce86b3 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.5.1 +(function (EXPORTS) { //floBlockchainAPI v2.5.2 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -273,6 +273,56 @@ }) } + //split sufficient UTXOs of a given floID for a parallel sending + floBlockchainAPI.splitUTXOs = function (floID, privKey, count, floData = '') { + return new Promise((resolve, reject) => { + if (!floCrypto.validateFloID(floID, true)) + return reject(`Invalid floID`); + if (!floCrypto.verifyPrivKey(privKey, floID)) + return reject("Invalid Private Key"); + if (!floCrypto.validateASCII(floData)) + return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); + var fee = DEFAULT.fee; + var splitAmt = DEFAULT.sendAmt + fee; + var totalAmt = splitAmt * count; + getBalance(floID).then(balance => { + var fee = DEFAULT.fee; + if (balance < totalAmt + fee) + return reject("Insufficient FLO balance!"); + //get unconfirmed tx list + getUnconfirmedSpent(senderAddr).then(unconfirmedSpent => { + getUTXOs(senderAddr).then(utxos => { + var trx = bitjs.transaction(); + var utxoAmt = 0.0; + for (let i = utxos.length - 1; (i >= 0) && (utxoAmt < totalAmt + fee); i--) { + //use only utxos with confirmations (strict_utxo mode) + if (utxos[i].confirmations || !strict_utxo) { + if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout)) + continue; //A transaction has already used the utxo, but is unconfirmed. + trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); + utxoAmt += utxos[i].amount; + }; + } + if (utxoAmt < totalAmt + fee) + reject("Insufficient FLO: Some UTXOs are unconfirmed"); + else { + for (let i = 0; i < count; i++) + trx.addoutput(floID, splitAmt); + var change = utxoAmt - totalAmt - fee; + if (change > DEFAULT.minChangeAmt) + trx.addoutput(floID, change); + trx.addflodata(floData.replace(/\n/g, ' ')); + var signedTxHash = trx.sign(privKey, 1); + broadcastTx(signedTxHash) + .then(txid => resolve(txid)) + .catch(error => reject(error)) + } + }).catch(error => reject(error)) + }).catch(error => reject(error)) + }).catch(error => reject(error)) + }) + } + /**Write data into blockchain from (and/or) to multiple floID * @param {Array} senderPrivKeys List of sender private-keys * @param {string} data FLO data of the txn From 7bd528d55ed0ce4d35eed25be0ecc29afae339ec Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sat, 29 Apr 2023 03:22:38 +0530 Subject: [PATCH 274/289] floBlockchainAPI v2.5.3 - Added waitForConfirmation: Wait for the given txid to get confirmation in blockchain --- floBlockchainAPI.js | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index cce86b3..35a3c3f 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.5.2 +(function (EXPORTS) { //floBlockchainAPI v2.5.3 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -787,7 +787,7 @@ }) } - floBlockchainAPI.getTx = function (txid) { + const getTx = floBlockchainAPI.getTx = function (txid) { return new Promise((resolve, reject) => { promisedAPI(`api/tx/${txid}`) .then(response => resolve(response)) @@ -795,6 +795,33 @@ }) } + /**Wait for the given txid to get confirmation in blockchain + * @param {string} txid of the transaction to wait for + * @param {int} max_retry: maximum number of retries before exiting wait. negative number = Infinite retries (DEFAULT: -1 ie, infinite retries) + * @param {Array} retry_timeout: time (seconds) between retries (DEFAULT: 20 seconds) + * @return {Promise} resolves when tx gets confirmation + */ + const waitForConfirmation = floBlockchainAPI.waitForConfirmation = function (txid, max_retry = -1, retry_timeout = 20) { + return new Promise((resolve, reject) => { + setTimeout(function () { + getTx(txid).then(tx => { + if (!tx) + return reject("Transaction not found"); + if (tx.confirmations) + return resolve(tx); + else if (max_retry === 0) //no more retries + return reject("Waiting timeout: tx still not confirmed"); + else { + max_retry = max_retry < 0 ? -1 : max_retry - 1; //decrease retry count (unless infinite retries) + waitForConfirmation(txid, max_retry, retry_timeout) + .then(result => resolve(result)) + .catch(error => reject(error)) + } + }).catch(error => reject(error)) + }, retry_timeout * 1000) + }) + } + const isUndefined = val => typeof val === 'undefined'; //Read Txs of Address between from and to From fe33250b472e1b10ee11a48c5a95128bf30b6b60 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sat, 29 Apr 2023 03:28:33 +0530 Subject: [PATCH 275/289] floBlockchainAPI v2.5.4 - Adding support for 'before' and 'latest' option in readTxs and its derivatives --- floBlockchainAPI.js | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 35a3c3f..73cf7e3 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.5.3 +(function (EXPORTS) { //floBlockchainAPI v2.5.4 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -830,14 +830,19 @@ let api = `api/addrs/${addr}/txs`; //API options let api_options = []; - if (!isUndefined(options.after)) - api_options.push(`after=${options.after}`); - else { + if (!isUndefined(options.after) || !isUndefined(options.before)) { + if (!isUndefined(options.after)) + api_options.push(`after=${options.after}`); + if (!isUndefined(options.before)) + api_options.push(`before=${options.before}`); + } else { if (!isUndefined(options.from)) api_options.push(`from=${options.from}`); if (!isUndefined(options.to)) api_options.push(`to=${options.to}`); } + if (!isUndefined(options.latest)) + api_options.push('latest'); if (!isUndefined(options.mempool)) api_options.push(`mempool=${options.mempool}`) if (api_options.length) @@ -854,7 +859,10 @@ readTxs(addr, options).then(response => { if (response.incomplete) { let next_options = Object.assign({}, options); - next_options.after = response.lastItem; + if (options.latest) + next_options.before = response.initItem; //update before for chain query (latest 1st) + else + next_options.after = response.lastItem; //update after for chain query (oldest 1st) readAllTxs(addr, next_options).then(r => { r.items = r.items.concat(response.items); //latest tx are 1st in array resolve(r); @@ -871,6 +879,7 @@ /*Read flo Data from txs of given Address options can be used to filter data after : query after the given txid + before : query before the given txid mempool : query mempool tx or not (options same as readAllTx, DEFAULT=false: ignore unconfirmed tx) ignoreOld : ignore old txs (deprecated: support for backward compatibility only, cannot be used with 'after') sentOnly : filters only sent data @@ -887,15 +896,16 @@ //fetch options let fetch_options = {}; fetch_options.mempool = isUndefined(options.mempool) ? 'false' : options.mempool; //DEFAULT: ignore unconfirmed tx - if (!isUndefined(options.after)) { + if (!isUndefined(options.after) || !isUndefined(options.before)) { if (!isUndefined(options.ignoreOld)) //Backward support - return reject("Invalid options: cannot use after and ignoreOld in same query"); - else - fetch_options.after = options.after; + return reject("Invalid options: cannot use after/before and ignoreOld in same query"); + //use passed after and/or before options (options remain undefined if not passed) + fetch_options.after = options.after; + fetch_options.before = options.before; } readAllTxs(addr, fetch_options).then(response => { - if (Number.isInteger(options.ignoreOld)) //backward support, cannot be used with options.after + if (Number.isInteger(options.ignoreOld)) //backward support, cannot be used with options.after or options.before response.items.splice(-options.ignoreOld); //negative to count from end of the array if (typeof options.senders === "string") options.senders = [options.senders]; From 8afde73e7862f8442101fa705b2065784af41763 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sat, 29 Apr 2023 05:29:39 +0530 Subject: [PATCH 276/289] floBlockchainAPI v2.5.5: adding getLatestData - Added getLatestData: Get the latest flo Data that match the caseFn from txs of given Address --- floBlockchainAPI.js | 79 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 77 insertions(+), 2 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 73cf7e3..8b84c36 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.5.4 +(function (EXPORTS) { //floBlockchainAPI v2.5.5 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -895,7 +895,7 @@ //fetch options let fetch_options = {}; - fetch_options.mempool = isUndefined(options.mempool) ? 'false' : options.mempool; //DEFAULT: ignore unconfirmed tx + fetch_options.mempool = isUndefined(options.mempool) ? false : options.mempool; //DEFAULT: ignore unconfirmed tx if (!isUndefined(options.after) || !isUndefined(options.before)) { if (!isUndefined(options.ignoreOld)) //Backward support return reject("Invalid options: cannot use after/before and ignoreOld in same query"); @@ -961,4 +961,79 @@ }) } + /*Get the latest flo Data that match the caseFn from txs of given Address + caseFn: (function) flodata => return bool value + options can be used to filter data + after : query after the given txid + before : query before the given txid + mempool : query mempool tx or not (options same as readAllTx, DEFAULT=false: ignore unconfirmed tx) + sentOnly : filters only sent data + receivedOnly: filters only received data + tx : (boolean) resolve tx data or not (resolves an Array of Object with tx details) + sender : flo-id(s) of sender + receiver : flo-id(s) of receiver + */ + const getLatestData = floBlockchainAPI.getLatestData = function (addr, caseFn, options = {}) { + return new Promise((resolve, reject) => { + //fetch options + let fetch_options = { latest: true }; + fetch_options.mempool = isUndefined(options.mempool) ? false : options.mempool; //DEFAULT: ignore unconfirmed tx + if (!isUndefined(options.after)) fetch_options.after = options.after; + if (!isUndefined(options.before)) fetch_options.before = options.before; + + readTxs(addr, fetch_options).then(response => { + + if (typeof options.senders === "string") options.senders = [options.senders]; + if (typeof options.receivers === "string") options.receivers = [options.receivers]; + + var item = response.items.find(tx => { + if (!tx.confirmations) //unconfirmed transactions: this should not happen as we send mempool=false in API query + return false; + + if (options.sentOnly && !tx.vin.some(vin => vin.addr === addr)) + return false; + else if (Array.isArray(options.senders) && !tx.vin.some(vin => options.senders.includes(vin.addr))) + return false; + + if (options.receivedOnly && !tx.vout.some(vout => vout.scriptPubKey.addresses[0] === addr)) + return false; + else if (Array.isArray(options.receivers) && !tx.vout.some(vout => options.receivers.includes(vout.scriptPubKey.addresses[0]))) + return false; + + return caseFn(tx.floData) ? true : false; //return only bool for find fn + }); + + //if item found, then resolve the result + if (!isUndefined(item)) { + const result = { lastKey: response.lastItem }; + if (options.tx) { + result.item = { + txid: tx.txid, + time: tx.time, + blockheight: tx.blockheight, + senders: new Set(tx.vin.map(v => v.addr)), + receivers: new Set(tx.vout.map(v => v.scriptPubKey.addresses[0])), + data: tx.floData + } + } else + result.data = tx.floData; + return resolve(result); + } + //else if address needs chain query + else if (response.incomplete) { + let next_options = Object.assign({}, options); + options.before = response.initItem; //this fn uses latest option, so using before to chain query + getLatestData(addr, caseFn, next_options).then(r => { + r.lastKey = response.lastItem; //update last key as it should be the newest tx + resolve(r); + }).catch(error => reject(error)) + } + //no data match the caseFn, resolve just the lastKey + else + resolve({ lastKey: response.lastItem }); + + }).catch(error => reject(error)) + }) + } + })('object' === typeof module ? module.exports : window.floBlockchainAPI = {}); \ No newline at end of file From b09c88f0df02b04cd0c12dc7182f41d49e543e44 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Mon, 1 May 2023 20:44:44 +0530 Subject: [PATCH 277/289] floDapps v2.3.5 - Added get property trustedIDs to floGlobals ie, floGlobals.trustedIDs will give the list of trustedIDs for the app --- floDapps.js | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/floDapps.js b/floDapps.js index 4668e4e..8924153 100644 --- a/floDapps.js +++ b/floDapps.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floDapps v2.3.4 +(function (EXPORTS) { //floDapps v2.3.5 /* General functions for FLO Dapps*/ 'use strict'; const floDapps = EXPORTS; @@ -144,11 +144,14 @@ } }); - var subAdmins, settings + var subAdmins, trustedIDs, settings; Object.defineProperties(floGlobals, { subAdmins: { get: () => subAdmins }, + trustedIDs: { + get: () => trustedIDs + }, settings: { get: () => settings }, @@ -317,9 +320,12 @@ compactIDB.writeData("lastTx", result.totalTxs, `${DEFAULT.application}|${DEFAULT.adminID}`, DEFAULT.root); compactIDB.readAllData("subAdmins").then(result => { subAdmins = Object.keys(result); - compactIDB.readAllData("settings").then(result => { - settings = result; - resolve("Read app configuration from blockchain"); + compactIDB.readAllData("trustedIDs").then(result => { + trustedIDs = Object.keys(result); + compactIDB.readAllData("settings").then(result => { + settings = result; + resolve("Read app configuration from blockchain"); + }) }) }) }) From a762f4441b84c022c32423a8dd63e30712e1e2d1 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 2 May 2023 21:47:48 +0530 Subject: [PATCH 278/289] floBlockchainAPI v2.5.5a: bug fix --- floBlockchainAPI.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 8b84c36..39be710 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.5.5 +(function (EXPORTS) { //floBlockchainAPI v2.5.5a /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -7,7 +7,7 @@ blockchain: floGlobals.blockchain, apiURL: { FLO: ['https://flosight.duckdns.org/', 'https://flosight.ranchimall.net/'], - FLO_TEST: ['https://testnet-flosight.duckdns.org', 'https://testnet.flocha.in/'] + FLO_TEST: ['https://flosight-testnet.ranchimall.net/'] }, sendAmt: 0.0003, fee: 0.0002, @@ -290,8 +290,8 @@ if (balance < totalAmt + fee) return reject("Insufficient FLO balance!"); //get unconfirmed tx list - getUnconfirmedSpent(senderAddr).then(unconfirmedSpent => { - getUTXOs(senderAddr).then(utxos => { + getUnconfirmedSpent(floID).then(unconfirmedSpent => { + getUTXOs(floID).then(utxos => { var trx = bitjs.transaction(); var utxoAmt = 0.0; for (let i = utxos.length - 1; (i >= 0) && (utxoAmt < totalAmt + fee); i--) { From 7e618c98f23979dd1949d123f6dfb8e4b2310074 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Tue, 2 May 2023 22:15:54 +0530 Subject: [PATCH 279/289] floTokenAPI v1.0.4: Added bunkTransferTokens - Added bunkTransferTokens: bulk transfer tokens to multiple receivers - usage: floWebWallet.bunkTransferTokens(sender, privKey, token, receivers) sender: floID of sender privKey: private key of sender token: token to send receivers: an object representing receiver floID and token amount ie, {receiverID1: amount1, receiverID2: amount2....} eg: {Fxyz: 123, Fpqr:321, Fabc: 987} --- floTokenAPI.js | 66 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/floTokenAPI.js b/floTokenAPI.js index efbd2ae..346ab65 100644 --- a/floTokenAPI.js +++ b/floTokenAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floTokenAPI v1.0.3c +(function (EXPORTS) { //floTokenAPI v1.0.4 /* Token Operator to send/receive tokens via blockchain using API calls*/ 'use strict'; const tokenAPI = EXPORTS; @@ -77,6 +77,70 @@ }); } + function sendTokens_raw(privKey, receiverID, token, amount, utxo, vout, scriptPubKey) { + return new Promise((resolve, reject) => { + var trx = bitjs.transaction(); + trx.addinput(utxo, vout, scriptPubKey) + trx.addoutput(receiverID, floBlockchainAPI.sendAmt); + trx.addflodata(`send ${amount} ${token}#`); + var signedTxHash = trx.sign(privKey, 1); + floBlockchainAPI.broadcastTx(signedTxHash) + .then(txid => resolve([receiverID, txid])) + .catch(error => reject([receiverID, error])) + }) + } + + //bulk transfer tokens + tokenAPI.bunkTransferTokens = function (sender, privKey, token, receivers) { + return new Promise((resolve, reject) => { + if (typeof receivers !== 'object') + return reject("receivers must be object in format {receiver1: amount1, receiver2:amount2...}") + + let receiver_list = Object.keys(receivers), amount_list = Object.values(receivers); + let invalidReceivers = receiver_list.filter(id => !floCrypto.validateFloID(id)); + let invalidAmount = amount_list.filter(val => typeof val !== 'number' || val <= 0); + if (invalidReceivers.length) + return reject(`Invalid receivers: ${invalidReceivers}`); + else if (invalidAmount.length) + return reject(`Invalid amounts: ${invalidAmount}`); + + if (receiver_list.length == 0) + return reject("Receivers cannot be empty"); + + if (receiver_list.length == 1) { + let receiver = receiver_list[0], amount = amount_list[0]; + floTokenAPI.sendToken(privKey, amount, receiver, "", token) + .then(txid => resolve({ success: { [receiver]: txid } })) + .catch(error => reject(error)) + } else { + //check for token balance + floTokenAPI.getBalance(sender, token).then(token_balance => { + let total_token_amout = amount_list.reduce((a, e) => a + e, 0); + if (total_token_amout > token_balance) + return reject(`Insufficient ${token}# balance`); + + //split utxos + floBlockchainAPI.splitUTXOs(sender, privKey, receiver_list.length).then(split_txid => { + //wait for the split utxo to get confirmation + floBlockchainAPI.waitForConfirmation(split_txid).then(split_tx => { + //send tokens using the split-utxo + var scriptPubKey = split_tx.vout[0].scriptPubKey.hex; + let promises = []; + for (let i in receiver_list) + promises.push(sendTokens_raw(privKey, receiver_list[i], token, amount_list[i], split_txid, i, scriptPubKey)); + Promise.allSettled(promises).then(results => { + let success = Object.fromEntries(results.filter(r => r.status == 'fulfilled').map(r => r.value)); + let failed = Object.fromEntries(results.filter(r => r.status == 'rejected').map(r => r.reason)); + resolve({ success, failed }); + }) + }).catch(error => reject(error)) + }).catch(error => reject(error)) + }).catch(error => reject(error)) + } + + }) + } + tokenAPI.getAllTxs = function (floID, token = DEFAULT.currency) { return new Promise((resolve, reject) => { fetch_api(`api/v1.0/getFloAddressTransactions?token=${token}&floAddress=${floID}`) From 704def4db1a0d6473430fbed89f702c513489a48 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 4 May 2023 16:59:10 +0530 Subject: [PATCH 280/289] floCloudAPI v2.4.3a - Added property: SNStorageName (string content "SuperNodeStorage" --- floCloudAPI.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/floCloudAPI.js b/floCloudAPI.js index 921fa69..c2d2c3f 100644 --- a/floCloudAPI.js +++ b/floCloudAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floCloudAPI v2.4.3 +(function (EXPORTS) { //floCloudAPI v2.4.3a /* FLO Cloud operations to send/request application data*/ 'use strict'; const floCloudAPI = EXPORTS; @@ -8,6 +8,7 @@ SNStorageID: floGlobals.SNStorageID || "FNaN9McoBAEFUjkRmNQRYLmBF8SpS7Tgfk", adminID: floGlobals.adminID, application: floGlobals.application, + SNStorageName: "SuperNodeStorage", callback: (d, e) => console.debug(d, e) }; @@ -58,6 +59,9 @@ SNStorageID: { get: () => DEFAULT.SNStorageID }, + SNStorageName: { + get: () => DEFAULT.SNStorageName + }, adminID: { get: () => DEFAULT.adminID }, From 9e10a02dc8e7b1ff0083d913b181c4198629724d Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 4 May 2023 17:04:55 +0530 Subject: [PATCH 281/289] floBlockchainAPI v2.5.6 - All search query (get method) now uses URLSearchParams to construct the string - renamed all lastKey property to lastItem to match flosight response --- floBlockchainAPI.js | 67 ++++++++++++++++++++++----------------------- 1 file changed, 33 insertions(+), 34 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 39be710..d34e3ef 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.5.5a +(function (EXPORTS) { //floBlockchainAPI v2.5.6 /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -16,6 +16,7 @@ }; const SATOSHI_IN_BTC = 1e8; + const isUndefined = val => typeof val === 'undefined'; const util = floBlockchainAPI.util = {}; @@ -111,9 +112,11 @@ }); //Promised function to get data from API - const promisedAPI = floBlockchainAPI.promisedAPI = floBlockchainAPI.fetch = function (apicall) { + const promisedAPI = floBlockchainAPI.promisedAPI = floBlockchainAPI.fetch = function (apicall, query_params = undefined) { return new Promise((resolve, reject) => { - //console.log(apicall); + if (!isUndefined(query_params)) + apicall += '?' + new URLSearchParams(JSON.parse(JSON.stringify(query_params))).toString(); + //console.debug(apicall); fetch_api(apicall) .then(result => resolve(result)) .catch(error => reject(error)); @@ -123,13 +126,13 @@ //Get balance for the given Address const getBalance = floBlockchainAPI.getBalance = function (addr, after = null) { return new Promise((resolve, reject) => { - let api = `api/addr/${addr}/balance`; + let api = `api/addr/${addr}/balance`, query_params = {}; if (after) { if (typeof after === 'string' && /^[0-9a-z]{64}$/i.test(after)) - api += '?after=' + after; + query_params.after = after; else return reject("Invalid 'after' parameter"); } - promisedAPI(api).then(result => { + promisedAPI(api, query_params).then(result => { if (typeof result === 'object' && result.lastItem) { getBalance(addr, result.lastItem) .then(r => resolve(util.toFixed(r + result.data))) @@ -822,32 +825,28 @@ }) } - const isUndefined = val => typeof val === 'undefined'; - //Read Txs of Address between from and to const readTxs = floBlockchainAPI.readTxs = function (addr, options = {}) { return new Promise((resolve, reject) => { let api = `api/addrs/${addr}/txs`; //API options - let api_options = []; + let query_params = {}; if (!isUndefined(options.after) || !isUndefined(options.before)) { if (!isUndefined(options.after)) - api_options.push(`after=${options.after}`); + query_params.after = options.after; if (!isUndefined(options.before)) - api_options.push(`before=${options.before}`); + query_params.before = options.before; } else { if (!isUndefined(options.from)) - api_options.push(`from=${options.from}`); + query_params.from = options.from; if (!isUndefined(options.to)) - api_options.push(`to=${options.to}`); + query_params.to = options.to; } if (!isUndefined(options.latest)) - api_options.push('latest'); + query_params.latest = latest; if (!isUndefined(options.mempool)) - api_options.push(`mempool=${options.mempool}`) - if (api_options.length) - api += "?" + api_options.join('&'); - promisedAPI(api) + query_params.mempool = options.mempool; + promisedAPI(api, query_params) .then(response => resolve(response)) .catch(error => reject(error)) }); @@ -869,7 +868,7 @@ }).catch(error => reject(error)) } else resolve({ - lastKey: response.lastItem || options.after, + lastItem: response.lastItem || options.after, items: response.items }); }) @@ -894,16 +893,16 @@ return new Promise((resolve, reject) => { //fetch options - let fetch_options = {}; - fetch_options.mempool = isUndefined(options.mempool) ? false : options.mempool; //DEFAULT: ignore unconfirmed tx + let query_options = {}; + query_options.mempool = isUndefined(options.mempool) ? false : options.mempool; //DEFAULT: ignore unconfirmed tx if (!isUndefined(options.after) || !isUndefined(options.before)) { if (!isUndefined(options.ignoreOld)) //Backward support return reject("Invalid options: cannot use after/before and ignoreOld in same query"); //use passed after and/or before options (options remain undefined if not passed) - fetch_options.after = options.after; - fetch_options.before = options.before; + query_options.after = options.after; + query_options.before = options.before; } - readAllTxs(addr, fetch_options).then(response => { + readAllTxs(addr, query_options).then(response => { if (Number.isInteger(options.ignoreOld)) //backward support, cannot be used with options.after or options.before response.items.splice(-options.ignoreOld); //negative to count from end of the array @@ -950,7 +949,7 @@ data: tx.floData } : tx.floData); - const result = { lastKey: response.lastKey }; + const result = { lastItem: response.lastItem }; if (options.tx) result.items = filteredData; else @@ -976,12 +975,12 @@ const getLatestData = floBlockchainAPI.getLatestData = function (addr, caseFn, options = {}) { return new Promise((resolve, reject) => { //fetch options - let fetch_options = { latest: true }; - fetch_options.mempool = isUndefined(options.mempool) ? false : options.mempool; //DEFAULT: ignore unconfirmed tx - if (!isUndefined(options.after)) fetch_options.after = options.after; - if (!isUndefined(options.before)) fetch_options.before = options.before; + let query_options = { latest: true }; + query_options.mempool = isUndefined(options.mempool) ? false : options.mempool; //DEFAULT: ignore unconfirmed tx + if (!isUndefined(options.after)) query_options.after = options.after; + if (!isUndefined(options.before)) query_options.before = options.before; - readTxs(addr, fetch_options).then(response => { + readTxs(addr, query_options).then(response => { if (typeof options.senders === "string") options.senders = [options.senders]; if (typeof options.receivers === "string") options.receivers = [options.receivers]; @@ -1005,7 +1004,7 @@ //if item found, then resolve the result if (!isUndefined(item)) { - const result = { lastKey: response.lastItem }; + const result = { lastItem: response.lastItem }; if (options.tx) { result.item = { txid: tx.txid, @@ -1024,13 +1023,13 @@ let next_options = Object.assign({}, options); options.before = response.initItem; //this fn uses latest option, so using before to chain query getLatestData(addr, caseFn, next_options).then(r => { - r.lastKey = response.lastItem; //update last key as it should be the newest tx + r.lastItem = response.lastItem; //update last key as it should be the newest tx resolve(r); }).catch(error => reject(error)) } - //no data match the caseFn, resolve just the lastKey + //no data match the caseFn, resolve just the lastItem else - resolve({ lastKey: response.lastItem }); + resolve({ lastItem: response.lastItem }); }).catch(error => reject(error)) }) From 46ae8581e4d5e4bb8459ba23288f3f1eb5546f95 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Thu, 4 May 2023 17:09:02 +0530 Subject: [PATCH 282/289] floDapps v2.4.0 - Update for new flosight version - requires floBlockchainAPI >= v2.5.6 - requires floCloudAPI >= v2.4.3a - lastTx now stores the lastItem property (ie, txid) - backward-support: maintaining support for idb data (lastTx) from old floDapps module to be converted to this version --- floDapps.js | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/floDapps.js b/floDapps.js index 8924153..4d525a2 100644 --- a/floDapps.js +++ b/floDapps.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floDapps v2.3.5 +(function (EXPORTS) { //floDapps v2.4.0 /* General functions for FLO Dapps*/ 'use strict'; const floDapps = EXPORTS; @@ -258,13 +258,15 @@ if (!startUpOptions.cloud) return resolve("No cloud for this app"); compactIDB.readData("lastTx", floCloudAPI.SNStorageID, DEFAULT.root).then(lastTx => { - floBlockchainAPI.readData(floCloudAPI.SNStorageID, { - ignoreOld: lastTx, - sentOnly: true, - pattern: "SuperNodeStorage" - }).then(result => { + var query_options = { sentOnly: true, pattern: floCloudAPI.SNStorageName }; + if (typeof lastTx == 'number') //lastTx is tx count (*backward support) + query_options.ignoreOld = lastTx; + else if (typeof lastTx == 'string') //lastTx is txid of last tx + query_options.after = lastTx; + //fetch data from flosight + floBlockchainAPI.readData(floCloudAPI.SNStorageID, query_options).then(result => { for (var i = result.data.length - 1; i >= 0; i--) { - var content = JSON.parse(result.data[i]).SuperNodeStorage; + var content = JSON.parse(result.data[i])[floCloudAPI.SNStorageName]; for (let sn in content.removeNodes) compactIDB.removeData("supernodes", sn, DEFAULT.root); for (let sn in content.newNodes) @@ -276,7 +278,7 @@ compactIDB.writeData("supernodes", r, sn, DEFAULT.root); }); } - compactIDB.writeData("lastTx", result.totalTxs, floCloudAPI.SNStorageID, DEFAULT.root); + compactIDB.writeData("lastTx", result.lastItem, floCloudAPI.SNStorageID, DEFAULT.root); compactIDB.readAllData("supernodes", DEFAULT.root).then(nodes => { floCloudAPI.init(nodes) .then(result => resolve("Loaded Supernode list\n" + result)) @@ -292,11 +294,13 @@ if (!startUpOptions.app_config) return resolve("No configs for this app"); compactIDB.readData("lastTx", `${DEFAULT.application}|${DEFAULT.adminID}`, DEFAULT.root).then(lastTx => { - floBlockchainAPI.readData(DEFAULT.adminID, { - ignoreOld: lastTx, - sentOnly: true, - pattern: DEFAULT.application - }).then(result => { + var query_options = { sentOnly: true, pattern: DEFAULT.application }; + if (typeof lastTx == 'number') //lastTx is tx count (*backward support) + query_options.ignoreOld = lastTx; + else if (typeof lastTx == 'string') //lastTx is txid of last tx + query_options.after = lastTx; + //fetch data from flosight + floBlockchainAPI.readData(DEFAULT.adminID, query_options).then(result => { for (var i = result.data.length - 1; i >= 0; i--) { var content = JSON.parse(result.data[i])[DEFAULT.application]; if (!content || typeof content !== "object") @@ -317,7 +321,7 @@ for (let l in content.settings) compactIDB.writeData("settings", content.settings[l], l) } - compactIDB.writeData("lastTx", result.totalTxs, `${DEFAULT.application}|${DEFAULT.adminID}`, DEFAULT.root); + compactIDB.writeData("lastTx", result.lastItem, `${DEFAULT.application}|${DEFAULT.adminID}`, DEFAULT.root); compactIDB.readAllData("subAdmins").then(result => { subAdmins = Object.keys(result); compactIDB.readAllData("trustedIDs").then(result => { From 1390c91907c79b0c80e6260630fe1a27c586b01a Mon Sep 17 00:00:00 2001 From: sairajzero Date: Wed, 10 May 2023 01:46:36 +0530 Subject: [PATCH 283/289] floBlockchainAPI v2.5.6a - minor bug fix: default value for options missing in readAllTxs fn - removed flosight.duckdns.org from apiURL --- floBlockchainAPI.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index d34e3ef..460775b 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.5.6 +(function (EXPORTS) { //floBlockchainAPI v2.5.6a /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -6,7 +6,7 @@ const DEFAULT = { blockchain: floGlobals.blockchain, apiURL: { - FLO: ['https://flosight.duckdns.org/', 'https://flosight.ranchimall.net/'], + FLO: ['https://flosight.ranchimall.net/'], FLO_TEST: ['https://flosight-testnet.ranchimall.net/'] }, sendAmt: 0.0003, @@ -853,7 +853,7 @@ } //Read All Txs of Address (newest first) - const readAllTxs = floBlockchainAPI.readAllTxs = function (addr, options) { + const readAllTxs = floBlockchainAPI.readAllTxs = function (addr, options = {}) { return new Promise((resolve, reject) => { readTxs(addr, options).then(response => { if (response.incomplete) { From 94fb4f4849e12e83e61b21bef00bb48a62c11ba6 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Wed, 10 May 2023 01:50:46 +0530 Subject: [PATCH 284/289] compactIDB v2.1.2 - Fixed: options.limit not working in searchData - Added option reverse to searchData (if set to true, the ordering will be reversed --- compactIDB.js | 46 ++++++++++++++++++++++------------------------ 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/compactIDB.js b/compactIDB.js index 624db0a..ba843ec 100644 --- a/compactIDB.js +++ b/compactIDB.js @@ -1,4 +1,4 @@ -(function(EXPORTS) { //compactIDB v2.1.0 +(function (EXPORTS) { //compactIDB v2.1.2 /* Compact IndexedDB operations */ 'use strict'; const compactIDB = EXPORTS; @@ -59,7 +59,7 @@ }) } - compactIDB.initDB = function(dbName, objectStores = {}) { + compactIDB.initDB = function (dbName, objectStores = {}) { return new Promise((resolve, reject) => { if (!(objectStores instanceof Object)) return reject('ObjectStores must be an object or array') @@ -87,14 +87,14 @@ resolve("Initiated IndexedDB"); else upgradeDB(dbName, a_obs, d_obs) - .then(result => resolve(result)) - .catch(error => reject(error)) + .then(result => resolve(result)) + .catch(error => reject(error)) db.close(); } }); } - const openDB = compactIDB.openDB = function(dbName = defaultDB) { + const openDB = compactIDB.openDB = function (dbName = defaultDB) { return new Promise((resolve, reject) => { var idb = indexedDB.open(dbName); idb.onerror = (event) => reject("Error in opening IndexedDB"); @@ -106,7 +106,7 @@ }); } - const deleteDB = compactIDB.deleteDB = function(dbName = defaultDB) { + const deleteDB = compactIDB.deleteDB = function (dbName = defaultDB) { return new Promise((resolve, reject) => { var deleteReq = indexedDB.deleteDatabase(dbName);; deleteReq.onerror = (event) => reject("Error deleting database!"); @@ -114,7 +114,7 @@ }); } - compactIDB.writeData = function(obsName, data, key = false, dbName = defaultDB) { + compactIDB.writeData = function (obsName, data, key = false, dbName = defaultDB) { return new Promise((resolve, reject) => { openDB(dbName).then(db => { var obs = db.transaction(obsName, "readwrite").objectStore(obsName); @@ -128,7 +128,7 @@ }); } - compactIDB.addData = function(obsName, data, key = false, dbName = defaultDB) { + compactIDB.addData = function (obsName, data, key = false, dbName = defaultDB) { return new Promise((resolve, reject) => { openDB(dbName).then(db => { var obs = db.transaction(obsName, "readwrite").objectStore(obsName); @@ -142,7 +142,7 @@ }); } - compactIDB.removeData = function(obsName, key, dbName = defaultDB) { + compactIDB.removeData = function (obsName, key, dbName = defaultDB) { return new Promise((resolve, reject) => { openDB(dbName).then(db => { var obs = db.transaction(obsName, "readwrite").objectStore(obsName); @@ -156,7 +156,7 @@ }); } - compactIDB.clearData = function(obsName, dbName = defaultDB) { + compactIDB.clearData = function (obsName, dbName = defaultDB) { return new Promise((resolve, reject) => { openDB(dbName).then(db => { var obs = db.transaction(obsName, "readwrite").objectStore(obsName); @@ -168,7 +168,7 @@ }); } - compactIDB.readData = function(obsName, key, dbName = defaultDB) { + compactIDB.readData = function (obsName, key, dbName = defaultDB) { return new Promise((resolve, reject) => { openDB(dbName).then(db => { var obs = db.transaction(obsName, "readonly").objectStore(obsName); @@ -182,7 +182,7 @@ }); } - compactIDB.readAllData = function(obsName, dbName = defaultDB) { + compactIDB.readAllData = function (obsName, dbName = defaultDB) { return new Promise((resolve, reject) => { openDB(dbName).then(db => { var obs = db.transaction(obsName, "readonly").objectStore(obsName); @@ -223,13 +223,12 @@ }) }*/ - compactIDB.searchData = function(obsName, options = {}, dbName = defaultDB) { + compactIDB.searchData = function (obsName, options = {}, dbName = defaultDB) { options.lowerKey = options.atKey || options.lowerKey || 0 options.upperKey = options.atKey || options.upperKey || false - options.patternEval = options.patternEval || ((k, v) => { - return true - }) + options.patternEval = options.patternEval || ((k, v) => true); options.limit = options.limit || false; + options.reverse = options.reverse || false; options.lastOnly = options.lastOnly || false return new Promise((resolve, reject) => { openDB(dbName).then(db => { @@ -237,17 +236,16 @@ var filteredResult = {} let curReq = obs.openCursor( options.upperKey ? IDBKeyRange.bound(options.lowerKey, options.upperKey) : IDBKeyRange.lowerBound(options.lowerKey), - options.lastOnly ? "prev" : "next"); + options.lastOnly || options.reverse ? "prev" : "next"); curReq.onsuccess = (evt) => { var cursor = evt.target.result; - if (cursor) { - if (options.patternEval(cursor.primaryKey, cursor.value)) { - filteredResult[cursor.primaryKey] = cursor.value; - options.lastOnly ? resolve(filteredResult) : cursor.continue(); - } else - cursor.continue(); + if (!cursor || (options.limit && options.limit <= Object.keys(filteredResult).length)) + return resolve(filteredResult); //reached end of key list or limit reached + else if (options.patternEval(cursor.primaryKey, cursor.value)) { + filteredResult[cursor.primaryKey] = cursor.value; + options.lastOnly ? resolve(filteredResult) : cursor.continue(); } else - resolve(filteredResult); + cursor.continue(); } curReq.onerror = (evt) => reject(`Search unsuccessful [${evt.target.error.name}] ${evt.target.error.message}`); db.close(); From d777303097a038f27f72d7618467fadc6c4e935b Mon Sep 17 00:00:00 2001 From: sairajzero Date: Wed, 10 May 2023 02:01:47 +0530 Subject: [PATCH 285/289] floTokenAPI v1.0.4a - fixed: typo in bulkTransferTokens --- floTokenAPI.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/floTokenAPI.js b/floTokenAPI.js index 346ab65..2456b88 100644 --- a/floTokenAPI.js +++ b/floTokenAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floTokenAPI v1.0.4 +(function (EXPORTS) { //floTokenAPI v1.0.4a /* Token Operator to send/receive tokens via blockchain using API calls*/ 'use strict'; const tokenAPI = EXPORTS; @@ -91,7 +91,7 @@ } //bulk transfer tokens - tokenAPI.bunkTransferTokens = function (sender, privKey, token, receivers) { + tokenAPI.bulkTransferTokens = function (sender, privKey, token, receivers) { return new Promise((resolve, reject) => { if (typeof receivers !== 'object') return reject("receivers must be object in format {receiver1: amount1, receiver2:amount2...}") From 92303cbc47ed065d3e7999bb036860258e05ccc5 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sat, 13 May 2023 18:18:23 +0530 Subject: [PATCH 286/289] floBlockchainAPI v2.5.6b: bug fix --- floBlockchainAPI.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/floBlockchainAPI.js b/floBlockchainAPI.js index 460775b..6fec5b8 100644 --- a/floBlockchainAPI.js +++ b/floBlockchainAPI.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //floBlockchainAPI v2.5.6a +(function (EXPORTS) { //floBlockchainAPI v2.5.6b /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ 'use strict'; const floBlockchainAPI = EXPORTS; @@ -843,7 +843,7 @@ query_params.to = options.to; } if (!isUndefined(options.latest)) - query_params.latest = latest; + query_params.latest = options.latest; if (!isUndefined(options.mempool)) query_params.mempool = options.mempool; promisedAPI(api, query_params) From 5db3902cea407374f8822d6611a23815b87c2b66 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 19 May 2023 00:58:31 +0530 Subject: [PATCH 287/289] remove stdops --- docs/scripts/btcOperator.js | 851 --- docs/scripts/floBlockchainAPI.js | 580 -- docs/scripts/floCrypto.js | 442 -- docs/scripts/floTokenAPI.js | 102 - docs/scripts/lib.js | 9356 ------------------------------ 5 files changed, 11331 deletions(-) delete mode 100644 docs/scripts/btcOperator.js delete mode 100644 docs/scripts/floBlockchainAPI.js delete mode 100644 docs/scripts/floCrypto.js delete mode 100644 docs/scripts/floTokenAPI.js delete mode 100644 docs/scripts/lib.js diff --git a/docs/scripts/btcOperator.js b/docs/scripts/btcOperator.js deleted file mode 100644 index 6925cec..0000000 --- a/docs/scripts/btcOperator.js +++ /dev/null @@ -1,851 +0,0 @@ -(function (EXPORTS) { //btcOperator v1.1.1 - /* BTC Crypto and API Operator */ - const btcOperator = EXPORTS; - - //This library uses API provided by chain.so (https://chain.so/) - const URL = "https://blockchain.info/"; - - const fetch_api = btcOperator.fetch = function (api, json_res = true) { - return new Promise((resolve, reject) => { - console.debug(URL + api); - fetch(URL + api).then(response => { - if (response.ok) { - (json_res ? response.json() : response.text()) - .then(result => resolve(result)) - .catch(error => reject(error)) - } else { - response.json() - .then(result => reject(result)) - .catch(error => reject(error)) - } - }).catch(error => reject(error)) - }) - }; - - const SATOSHI_IN_BTC = 1e8; - - const util = btcOperator.util = {}; - - util.Sat_to_BTC = value => parseFloat((value / SATOSHI_IN_BTC).toFixed(8)); - util.BTC_to_Sat = value => parseInt(value * SATOSHI_IN_BTC); - - function get_fee_rate() { - return new Promise((resolve, reject) => { - fetch('https://api.blockchain.info/mempool/fees').then(response => { - if (response.ok) - response.json() - .then(result => resolve(util.Sat_to_BTC(result.regular))) - .catch(error => reject(error)); - else - reject(response); - }).catch(error => reject(error)) - }) - } - - const broadcastTx = btcOperator.broadcastTx = rawTxHex => new Promise((resolve, reject) => { - let url = 'https://coinb.in/api/?uid=1&key=12345678901234567890123456789012&setmodule=bitcoin&request=sendrawtransaction'; - fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: "rawtx=" + rawTxHex - }).then(response => { - response.text().then(resultText => { - let r = resultText.match(/.*<\/result>/); - if (!r) - reject(resultText); - else { - r = r.pop().replace('', '').replace('', ''); - if (r == '1') { - let txid = resultText.match(/.*<\/txid>/).pop().replace('', '').replace('', ''); - resolve(txid); - } else if (r == '0') { - let error = resultText.match(/.*<\/response>/).pop().replace('', '').replace('', ''); - reject(decodeURIComponent(error.replace(/\+/g, " "))); - } else reject(resultText); - } - }).catch(error => reject(error)) - }).catch(error => reject(error)) - }); - - Object.defineProperties(btcOperator, { - newKeys: { - get: () => { - let r = coinjs.newKeys(); - r.segwitAddress = coinjs.segwitAddress(r.pubkey).address; - r.bech32Address = coinjs.bech32Address(r.pubkey).address; - return r; - } - }, - pubkey: { - value: key => key.length >= 66 ? key : (key.length == 64 ? coinjs.newPubkey(key) : coinjs.wif2pubkey(key).pubkey) - }, - address: { - value: (key, prefix = undefined) => coinjs.pubkey2address(btcOperator.pubkey(key), prefix) - }, - segwitAddress: { - value: key => coinjs.segwitAddress(btcOperator.pubkey(key)).address - }, - bech32Address: { - value: key => coinjs.bech32Address(btcOperator.pubkey(key)).address - } - }); - - coinjs.compressed = true; - - const verifyKey = btcOperator.verifyKey = function (addr, key) { - if (!addr || !key) - return undefined; - switch (coinjs.addressDecode(addr).type) { - case "standard": - return btcOperator.address(key) === addr; - case "multisig": - return btcOperator.segwitAddress(key) === addr; - case "bech32": - return btcOperator.bech32Address(key) === addr; - default: - return null; - } - } - - const validateAddress = btcOperator.validateAddress = function (addr) { - if (!addr) - return undefined; - let type = coinjs.addressDecode(addr).type; - if (["standard", "multisig", "bech32", "multisigBech32"].includes(type)) - return type; - else - return false; - } - - btcOperator.multiSigAddress = function (pubKeys, minRequired, bech32 = true) { - if (!Array.isArray(pubKeys)) - throw "pubKeys must be an array of public keys"; - else if (pubKeys.length < minRequired) - throw "minimum required should be less than the number of pubKeys"; - if (bech32) - return coinjs.pubkeys2MultisigAddressBech32(pubKeys, minRequired); - else - return coinjs.pubkeys2MultisigAddress(pubKeys, minRequired); - } - - //convert from one blockchain to another blockchain (target version) - btcOperator.convert = {}; - - btcOperator.convert.wif = function (source_wif, target_version = coinjs.priv) { - let keyHex = decodeLegacy(source_wif).hex; - if (!keyHex || keyHex.length < 66 || !/01$/.test(keyHex)) - return null; - else - return encodeLegacy(keyHex, target_version); - } - - btcOperator.convert.legacy2legacy = function (source_addr, target_version = coinjs.pub) { - let rawHex = decodeLegacy(source_addr).hex; - if (!rawHex) - return null; - else - return encodeLegacy(rawHex, target_version); - } - - btcOperator.convert.legacy2bech = function (source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) { - let rawHex = decodeLegacy(source_addr).hex; - if (!rawHex) - return null; - else - return encodeBech32(rawHex, target_version, target_hrp); - } - - btcOperator.convert.bech2bech = function (source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) { - let rawHex = decodeBech32(source_addr).hex; - if (!rawHex) - return null; - else - return encodeBech32(rawHex, target_version, target_hrp); - } - - btcOperator.convert.bech2legacy = function (source_addr, target_version = coinjs.pub) { - let rawHex = decodeBech32(source_addr).hex; - if (!rawHex) - return null; - else - return encodeLegacy(rawHex, target_version); - } - - function decodeLegacy(source) { - var decode = coinjs.base58decode(source); - var raw = decode.slice(0, decode.length - 4), - checksum = decode.slice(decode.length - 4); - var hash = Crypto.SHA256(Crypto.SHA256(raw, { - asBytes: true - }), { - asBytes: true - }); - if (hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3]) - return null; - let version = raw.shift(); - return { - version: version, - hex: Crypto.util.bytesToHex(raw) - } - } - - function encodeLegacy(hex, version) { - var bytes = Crypto.util.hexToBytes(hex); - bytes.unshift(version); - var hash = Crypto.SHA256(Crypto.SHA256(bytes, { - asBytes: true - }), { - asBytes: true - }); - var checksum = hash.slice(0, 4); - return coinjs.base58encode(bytes.concat(checksum)); - } - - function decodeBech32(source) { - let decode = coinjs.bech32_decode(source); - if (!decode) - return null; - var raw = decode.data; - let version = raw.shift(); - raw = coinjs.bech32_convert(raw, 5, 8, false); - return { - hrp: decode.hrp, - version: version, - hex: Crypto.util.bytesToHex(raw) - } - } - - function encodeBech32(hex, version, hrp) { - var bytes = Crypto.util.hexToBytes(hex); - bytes = coinjs.bech32_convert(bytes, 8, 5, true); - bytes.unshift(version) - return coinjs.bech32_encode(hrp, bytes); - } - - //BTC blockchain APIs - - btcOperator.getBalance = addr => new Promise((resolve, reject) => { - fetch_api(`q/addressbalance/${addr}`) - .then(result => resolve(util.Sat_to_BTC(result))) - .catch(error => reject(error)) - }); - - const BASE_TX_SIZE = 12, - BASE_INPUT_SIZE = 41, - LEGACY_INPUT_SIZE = 107, - BECH32_INPUT_SIZE = 27, - BECH32_MULTISIG_INPUT_SIZE = 35, - SEGWIT_INPUT_SIZE = 59, - MULTISIG_INPUT_SIZE_ES = 351, - BASE_OUTPUT_SIZE = 9, - LEGACY_OUTPUT_SIZE = 25, - BECH32_OUTPUT_SIZE = 23, - BECH32_MULTISIG_OUTPUT_SIZE = 34, - SEGWIT_OUTPUT_SIZE = 23; - - function _redeemScript(addr, key) { - let decode = coinjs.addressDecode(addr); - switch (decode.type) { - case "standard": - return false; - case "multisig": - return key ? coinjs.segwitAddress(btcOperator.pubkey(key)).redeemscript : null; - case "bech32": - return decode.redeemscript; - default: - return null; - } - } - - function _sizePerInput(addr, rs) { - switch (coinjs.addressDecode(addr).type) { - case "standard": - return BASE_INPUT_SIZE + LEGACY_INPUT_SIZE; - case "bech32": - return BASE_INPUT_SIZE + BECH32_INPUT_SIZE; - case "multisigBech32": - return BASE_INPUT_SIZE + BECH32_MULTISIG_INPUT_SIZE; - case "multisig": - switch (coinjs.script().decodeRedeemScript(rs).type) { - case "segwit__": - return BASE_INPUT_SIZE + SEGWIT_INPUT_SIZE; - case "multisig__": - return BASE_INPUT_SIZE + MULTISIG_INPUT_SIZE_ES; - default: - return null; - }; - default: - return null; - } - } - - function _sizePerOutput(addr) { - switch (coinjs.addressDecode(addr).type) { - case "standard": - return BASE_OUTPUT_SIZE + LEGACY_OUTPUT_SIZE; - case "bech32": - return BASE_OUTPUT_SIZE + BECH32_OUTPUT_SIZE; - case "multisigBech32": - return BASE_OUTPUT_SIZE + BECH32_MULTISIG_OUTPUT_SIZE; - case "multisig": - return BASE_OUTPUT_SIZE + SEGWIT_OUTPUT_SIZE; - default: - return null; - } - } - - function validateTxParameters(parameters) { - let invalids = []; - //sender-ids - if (parameters.senders) { - if (!Array.isArray(parameters.senders)) - parameters.senders = [parameters.senders]; - parameters.senders.forEach(id => !validateAddress(id) ? invalids.push(id) : null); - if (invalids.length) - throw "Invalid senders:" + invalids; - } - if (parameters.privkeys) { - if (!Array.isArray(parameters.privkeys)) - parameters.privkeys = [parameters.privkeys]; - if (parameters.senders.length != parameters.privkeys.length) - throw "Array length for senders and privkeys should be equal"; - parameters.senders.forEach((id, i) => { - let key = parameters.privkeys[i]; - if (!verifyKey(id, key)) //verify private-key - invalids.push(id); - if (key.length === 64) //convert Hex to WIF if needed - parameters.privkeys[i] = coinjs.privkey2wif(key); - }); - if (invalids.length) - throw "Invalid private key for address:" + invalids; - } - //receiver-ids (and change-id) - if (!Array.isArray(parameters.receivers)) - parameters.receivers = [parameters.receivers]; - parameters.receivers.forEach(id => !validateAddress(id) ? invalids.push(id) : null); - if (invalids.length) - throw "Invalid receivers:" + invalids; - if (parameters.change_address && !validateAddress(parameters.change_address)) - throw "Invalid change_address:" + parameters.change_address; - //fee and amounts - if ((typeof parameters.fee !== "number" || parameters.fee <= 0) && parameters.fee !== null) //fee = null (auto calc) - throw "Invalid fee:" + parameters.fee; - if (!Array.isArray(parameters.amounts)) - parameters.amounts = [parameters.amounts]; - if (parameters.receivers.length != parameters.amounts.length) - throw "Array length for receivers and amounts should be equal"; - parameters.amounts.forEach(a => typeof a !== "number" || a <= 0 ? invalids.push(a) : null); - if (invalids.length) - throw "Invalid amounts:" + invalids; - //return - return parameters; - } - - function createTransaction(senders, redeemScripts, receivers, amounts, fee, change_address, fee_from_receiver) { - return new Promise((resolve, reject) => { - let total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8)); - const tx = coinjs.transaction(); - let output_size = addOutputs(tx, receivers, amounts, change_address); - addInputs(tx, senders, redeemScripts, total_amount, fee, output_size, fee_from_receiver).then(result => { - if (result.change_amount > 0 && result.change_amount > result.fee) //add change amount if any (ignore dust change) - tx.outs[tx.outs.length - 1].value = util.BTC_to_Sat(result.change_amount); //values are in satoshi - if (fee_from_receiver) { //deduce fee from receivers if fee_from_receiver - let fee_remaining = util.BTC_to_Sat(result.fee); - for (let i = 0; i < tx.outs.length - 1 && fee_remaining > 0; i++) { - if (fee_remaining < tx.outs[i].value) { - tx.outs[i].value -= fee_remaining; - fee_remaining = 0; - } else { - fee_remaining -= tx.outs[i].value; - tx.outs[i].value = 0; - } - } - if (fee_remaining > 0) - return reject("Send amount is less than fee"); - - } - tx.outs = tx.outs.filter(o => o.value != 0); //remove all output with value 0 - result.output_size = output_size; - result.output_amount = total_amount - (fee_from_receiver ? result.fee : 0); - result.total_size = BASE_TX_SIZE + output_size + result.input_size; - result.transaction = tx; - resolve(result); - }).catch(error => reject(error)) - }) - } - - function addInputs(tx, senders, redeemScripts, total_amount, fee, output_size, fee_from_receiver) { - return new Promise((resolve, reject) => { - if (fee !== null) { - addUTXOs(tx, senders, redeemScripts, fee_from_receiver ? total_amount : total_amount + fee, false).then(result => { - result.fee = fee; - resolve(result); - }).catch(error => reject(error)) - } else { - get_fee_rate().then(fee_rate => { - let net_fee = BASE_TX_SIZE * fee_rate; - net_fee += (output_size * fee_rate); - (fee_from_receiver ? - addUTXOs(tx, senders, redeemScripts, total_amount, false) : - addUTXOs(tx, senders, redeemScripts, total_amount + net_fee, fee_rate) - ).then(result => { - result.fee = parseFloat((net_fee + (result.input_size * fee_rate)).toFixed(8)); - result.fee_rate = fee_rate; - resolve(result); - }).catch(error => reject(error)) - }).catch(error => reject(error)) - } - }) - } - - function addUTXOs(tx, senders, redeemScripts, required_amount, fee_rate, rec_args = {}) { - return new Promise((resolve, reject) => { - required_amount = parseFloat(required_amount.toFixed(8)); - if (typeof rec_args.n === "undefined") { - rec_args.n = 0; - rec_args.input_size = 0; - rec_args.input_amount = 0; - } - if (required_amount <= 0) - return resolve({ - input_size: rec_args.input_size, - input_amount: rec_args.input_amount, - change_amount: required_amount * -1 //required_amount will be -ve of change_amount - }); - else if (rec_args.n >= senders.length) - return reject("Insufficient Balance"); - let addr = senders[rec_args.n], - rs = redeemScripts[rec_args.n]; - let addr_type = coinjs.addressDecode(addr).type; - let size_per_input = _sizePerInput(addr, rs); - fetch_api(`unspent?active=${addr}`).then(result => { - let utxos = result.unspent_outputs; - console.debug("add-utxo", addr, rs, required_amount, utxos); - for (let i = 0; i < utxos.length && required_amount > 0; i++) { - if (!utxos[i].confirmations) //ignore unconfirmed utxo - continue; - var script; - if (!rs || !rs.length) //legacy script - script = utxos[i].script; - else if (((rs.match(/^00/) && rs.length == 44)) || (rs.length == 40 && rs.match(/^[a-f0-9]+$/gi)) || addr_type === 'multisigBech32') { - //redeemScript for segwit/bech32 and multisig (bech32) - let s = coinjs.script(); - s.writeBytes(Crypto.util.hexToBytes(rs)); - s.writeOp(0); - s.writeBytes(coinjs.numToBytes(utxos[i].value.toFixed(0), 8)); - script = Crypto.util.bytesToHex(s.buffer); - } else //redeemScript for multisig (segwit) - script = rs; - tx.addinput(utxos[i].tx_hash_big_endian, utxos[i].tx_output_n, script, 0xfffffffd /*sequence*/); //0xfffffffd for Replace-by-fee - //update track values - rec_args.input_size += size_per_input; - rec_args.input_amount += util.Sat_to_BTC(utxos[i].value); - required_amount -= util.Sat_to_BTC(utxos[i].value); - if (fee_rate) //automatic fee calculation (dynamic) - required_amount += size_per_input * fee_rate; - } - rec_args.n += 1; - addUTXOs(tx, senders, redeemScripts, required_amount, fee_rate, rec_args) - .then(result => resolve(result)) - .catch(error => reject(error)) - }).catch(error => reject(error)) - }) - } - - function addOutputs(tx, receivers, amounts, change_address) { - let size = 0; - for (let i in receivers) { - tx.addoutput(receivers[i], amounts[i]); - size += _sizePerOutput(receivers[i]); - } - tx.addoutput(change_address, 0); - size += _sizePerOutput(change_address); - return size; - } - - /* - function autoFeeCalc(tx) { - return new Promise((resolve, reject) => { - get_fee_rate().then(fee_rate => { - let tx_size = tx.size(); - for (var i = 0; i < this.ins.length; i++) - switch (tx.extractScriptKey(i).type) { - case 'scriptpubkey': - tx_size += SIGN_SIZE; - break; - case 'segwit': - case 'multisig': - tx_size += SIGN_SIZE * 0.25; - break; - default: - console.warn('Unknown script-type'); - tx_size += SIGN_SIZE; - } - resolve(tx_size * fee_rate); - }).catch(error => reject(error)) - }) - } - - function editFee(tx, current_fee, target_fee, index = -1) { - //values are in satoshi - index = parseInt(index >= 0 ? index : tx.outs.length - index); - if (index < 0 || index >= tx.outs.length) - throw "Invalid index"; - let edit_value = parseInt(current_fee - target_fee), //rip of any decimal places - current_value = tx.outs[index].value; //could be BigInterger - if (edit_value < 0 && edit_value > current_value) - throw "Insufficient value at vout"; - tx.outs[index].value = current_value instanceof BigInteger ? - current_value.add(new BigInteger('' + edit_value)) : parseInt(current_value + edit_value); - } - */ - - btcOperator.sendTx = function (senders, privkeys, receivers, amounts, fee = null, options = {}) { - return new Promise((resolve, reject) => { - createSignedTx(senders, privkeys, receivers, amounts, fee, options).then(result => { - debugger; - broadcastTx(result.transaction.serialize()) - .then(txid => resolve(txid)) - .catch(error => reject(error)); - }).catch(error => reject(error)) - }) - } - - const createSignedTx = btcOperator.createSignedTx = function (senders, privkeys, receivers, amounts, fee = null, options = {}) { - return new Promise((resolve, reject) => { - try { - ({ - senders, - privkeys, - receivers, - amounts - } = validateTxParameters({ - senders, - privkeys, - receivers, - amounts, - fee, - change_address: options.change_address - })); - } catch (e) { - return reject(e) - } - let redeemScripts = [], - wif_keys = []; - for (let i in senders) { - let rs = _redeemScript(senders[i], privkeys[i]); //get redeem-script (segwit/bech32) - redeemScripts.push(rs); - rs === false ? wif_keys.unshift(privkeys[i]) : wif_keys.push(privkeys[i]); //sorting private-keys (wif) - } - if (redeemScripts.includes(null)) //TODO: segwit - return reject("Unable to get redeem-script"); - //create transaction - createTransaction(senders, redeemScripts, receivers, amounts, fee, options.change_address || senders[0], options.fee_from_receiver).then(result => { - let tx = result.transaction; - console.debug("Unsigned:", tx.serialize()); - new Set(wif_keys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/))); //Sign the tx using private key WIF - console.debug("Signed:", tx.serialize()); - resolve(result); - }).catch(error => reject(error)); - }) - } - - btcOperator.createTx = function (senders, receivers, amounts, fee = null, options = {}) { - return new Promise((resolve, reject) => { - try { - ({ - senders, - receivers, - amounts - } = validateTxParameters({ - senders, - receivers, - amounts, - fee, - change_address: options.change_address - })); - } catch (e) { - return reject(e) - } - let redeemScripts = senders.map(id => _redeemScript(id)); - if (redeemScripts.includes(null)) //TODO: segwit - return reject("Unable to get redeem-script"); - //create transaction - createTransaction(senders, redeemScripts, receivers, amounts, fee, options.change_address || senders[0], options.fee_from_receiver).then(result => { - result.tx_hex = result.transaction.serialize(); - delete result.transaction; - resolve(result); - }).catch(error => reject(error)) - }) - } - - btcOperator.createMultiSigTx = function (sender, redeemScript, receivers, amounts, fee = null, options = {}) { - return new Promise((resolve, reject) => { - //validate tx parameters - let addr_type = validateAddress(sender); - if (!(["multisig", "multisigBech32"].includes(addr_type))) - return reject("Invalid sender (multisig):" + sender); - else { - let script = coinjs.script(); - let decode = (addr_type == "multisig") ? - script.decodeRedeemScript(redeemScript) : - script.decodeRedeemScriptBech32(redeemScript); - if (!decode || decode.address !== sender) - return reject("Invalid redeem-script"); - } - try { - ({ - receivers, - amounts - } = validateTxParameters({ - receivers, - amounts, - fee, - change_address: options.change_address - })); - } catch (e) { - return reject(e) - } - //create transaction - createTransaction([sender], [redeemScript], receivers, amounts, fee, options.change_address || sender, options.fee_from_receiver).then(result => { - result.tx_hex = result.transaction.serialize(); - delete result.transaction; - resolve(result); - }).catch(error => reject(error)) - - }) - } - - function deserializeTx(tx) { - if (typeof tx === 'string' || Array.isArray(tx)) { - try { - tx = coinjs.transaction().deserialize(tx); - } catch { - throw "Invalid transaction hex"; - } - } else if (typeof tx !== 'object' || typeof tx.sign !== 'function') - throw "Invalid transaction object"; - return tx; - } - - btcOperator.signTx = function (tx, privkeys, sighashtype = 1) { - tx = deserializeTx(tx); - if (!Array.isArray(privkeys)) - privkeys = [privkeys]; - for (let i in privkeys) - if (privkeys[i].length === 64) - privkeys[i] = coinjs.privkey2wif(privkeys[i]); - new Set(privkeys).forEach(key => tx.sign(key, sighashtype)); //Sign the tx using private key WIF - return tx.serialize(); - } - - const checkSigned = btcOperator.checkSigned = function (tx, bool = true) { - tx = deserializeTx(tx); - let n = []; - for (let i in tx.ins) { - var s = tx.extractScriptKey(i); - if (s['type'] !== 'multisig' && s['type'] !== 'multisig_bech32') - n.push(s.signed == 'true' || (tx.witness[i] && tx.witness[i].length == 2)) - else { - var rs = coinjs.script().decodeRedeemScript(s.script); //will work for bech32 too, as only address is diff - let x = { - s: s['signatures'], - r: rs['signaturesRequired'], - t: rs['pubkeys'].length - }; - if (x.r > x.t) - throw "signaturesRequired is more than publicKeys"; - else if (x.s < x.r) - n.push(x); - else - n.push(true); - } - } - return bool ? !(n.filter(x => x !== true).length) : n; - } - - btcOperator.checkIfSameTx = function (tx1, tx2) { - tx1 = deserializeTx(tx1); - tx2 = deserializeTx(tx2); - if (tx1.ins.length !== tx2.ins.length || tx1.outs.length !== tx2.outs.length) - return false; - for (let i = 0; i < tx1.ins.length; i++) - if (tx1.ins[i].outpoint.hash !== tx2.ins[i].outpoint.hash || tx1.ins[i].outpoint.index !== tx2.ins[i].outpoint.index) - return false; - for (let i = 0; i < tx2.ins.length; i++) - if (tx1.outs[i].value !== tx2.outs[i].value || Crypto.util.bytesToHex(tx1.outs[i].script.buffer) !== Crypto.util.bytesToHex(tx2.outs[i].script.buffer)) - return false; - return true; - } - - const getTxOutput = (txid, i) => new Promise((resolve, reject) => { - fetch_api(`rawtx/${txid}`) - .then(result => resolve(result.out[i])) - .catch(error => reject(error)) - }); - - btcOperator.parseTransaction = function (tx) { - return new Promise((resolve, reject) => { - tx = deserializeTx(tx); - let result = {}; - let promises = []; - //Parse Inputs - for (let i = 0; i < tx.ins.length; i++) - promises.push(getTxOutput(tx.ins[i].outpoint.hash, tx.ins[i].outpoint.index)); - Promise.all(promises).then(inputs => { - result.inputs = inputs.map(inp => Object({ - address: inp.addr, - value: util.Sat_to_BTC(inp.value) - })); - let signed = checkSigned(tx, false); - result.inputs.forEach((inp, i) => inp.signed = signed[i]); - //Parse Outputs - result.outputs = tx.outs.map(out => { - var address; - switch (out.script.chunks[0]) { - case 0: //bech32, multisig-bech32 - address = encodeBech32(Crypto.util.bytesToHex(out.script.chunks[1]), coinjs.bech32.version, coinjs.bech32.hrp); - break; - case 169: //segwit, multisig-segwit - address = encodeLegacy(Crypto.util.bytesToHex(out.script.chunks[1]), coinjs.multisig); - break; - case 118: //legacy - address = encodeLegacy(Crypto.util.bytesToHex(out.script.chunks[2]), coinjs.pub); - } - return { - address, - value: util.Sat_to_BTC(out.value) - } - }); - //Parse Totals - result.total_input = parseFloat(result.inputs.reduce((a, inp) => a += inp.value, 0).toFixed(8)); - result.total_output = parseFloat(result.outputs.reduce((a, out) => a += out.value, 0).toFixed(8)); - result.fee = parseFloat((result.total_input - result.total_output).toFixed(8)); - resolve(result); - }).catch(error => reject(error)) - }) - } - - btcOperator.transactionID = function (tx) { - tx = deserializeTx(tx); - let clone = coinjs.clone(tx); - clone.witness = null; - let raw_bytes = Crypto.util.hexToBytes(clone.serialize()); - let txid = Crypto.SHA256(Crypto.SHA256(raw_bytes, { asBytes: true }), { asBytes: true }).reverse(); - return Crypto.util.bytesToHex(txid); - } - - const getLatestBlock = btcOperator.getLatestBlock = () => new Promise((resolve, reject) => { - fetch_api(`q/getblockcount`) - .then(result => resolve(result)) - .catch(error => reject(error)) - }) - - btcOperator.getTx = txid => new Promise((resolve, reject) => { - fetch_api(`rawtx/${txid}`).then(result => { - getLatestBlock().then(latest_block => resolve({ - block: result.block_height, - txid: result.hash, - time: result.time * 1000, - confirmations: result.block_height === null ? 0 : latest_block - result.block_height, //calculate confirmations using latest block number as api doesnt relay it - size: result.size, - fee: util.Sat_to_BTC(result.fee), - inputs: result.inputs.map(i => Object({ address: i.prev_out.addr, value: util.Sat_to_BTC(i.prev_out.value) })), - total_input_value: util.Sat_to_BTC(result.inputs.reduce((a, i) => a + i.prev_out.value, 0)), - outputs: result.out.map(o => Object({ address: o.addr, value: util.Sat_to_BTC(o.value) })), - total_output_value: util.Sat_to_BTC(result.out.reduce((a, o) => a += o.value, 0)), - })) - }).catch(error => reject(error)) - }); - - btcOperator.getTx.hex = txid => new Promise((resolve, reject) => { - fetch_api(`rawtx/${txid}?format=hex`, false) - .then(result => resolve(result)) - .catch(error => reject(error)) - }) - - btcOperator.getAddressData = address => new Promise((resolve, reject) => { - fetch_api(`rawaddr/${address}`).then(data => { - let details = {}; - details.balance = util.Sat_to_BTC(data.final_balance); - details.address = data.address; - details.txs = data.txs.map(tx => { - let d = { - txid: tx.hash, - time: tx.time * 1000, //s to ms - block: tx.block_height, - } - //sender list - d.tx_senders = {}; - tx.inputs.forEach(i => { - if (i.prev_out.addr in d.tx_senders) - d.tx_senders[i.prev_out.addr] += i.prev_out.value; - else d.tx_senders[i.prev_out.addr] = i.prev_out.value; - }); - d.tx_input_value = 0; - for (let s in d.tx_senders) { - let val = d.tx_senders[s]; - d.tx_senders[s] = util.Sat_to_BTC(val); - d.tx_input_value += val; - } - d.tx_input_value = util.Sat_to_BTC(d.tx_input_value); - //receiver list - d.tx_receivers = {}; - tx.out.forEach(o => { - if (o.addr in d.tx_receivers) - d.tx_receivers[o.addr] += o.value; - else d.tx_receivers[o.addr] = o.value; - }); - d.tx_output_value = 0; - for (let r in d.tx_receivers) { - let val = d.tx_receivers[r]; - d.tx_receivers[r] = util.Sat_to_BTC(val); - d.tx_output_value += val; - } - d.tx_output_value = util.Sat_to_BTC(d.tx_output_value); - d.tx_fee = util.Sat_to_BTC(tx.fee); - //tx type - if (tx.result > 0) { //net > 0, balance inc => type=in - d.type = "in"; - d.amount = util.Sat_to_BTC(tx.result); - d.sender = Object.keys(d.tx_senders).filter(s => s !== address); - } else if (Object.keys(d.tx_receivers).some(r => r !== address)) { //net < 0, balance dec & receiver present => type=out - d.type = "out"; - d.amount = util.Sat_to_BTC(tx.result * -1); - d.receiver = Object.keys(d.tx_receivers).filter(r => r !== address); - d.fee = d.tx_fee; - } else { //net < 0 (fee) & no other id in receiver list => type=self - d.type = "self"; - d.amount = d.tx_receivers[address]; - d.address = address - } - return d; - }) - resolve(details); - }).catch(error => reject(error)) - }); - - btcOperator.getBlock = block => new Promise((resolve, reject) => { - fetch_api(`rawblock/${block}`).then(result => resolve({ - height: result.height, - hash: result.hash, - merkle_root: result.mrkl_root, - prev_block: result.prev_block, - next_block: result.next_block[0], - size: result.size, - time: result.time * 1000, //s to ms - txs: result.tx.map(t => Object({ - fee: t.fee, - size: t.size, - inputs: t.inputs.map(i => Object({ address: i.prev_out.addr, value: util.Sat_to_BTC(i.prev_out.value) })), - total_input_value: util.Sat_to_BTC(t.inputs.reduce((a, i) => a + i.prev_out.value, 0)), - outputs: t.out.map(o => Object({ address: o.addr, value: util.Sat_to_BTC(o.value) })), - total_output_value: util.Sat_to_BTC(t.out.reduce((a, o) => a += o.value, 0)), - })) - - })).catch(error => reject(error)) - }); - -})('object' === typeof module ? module.exports : window.btcOperator = {}); diff --git a/docs/scripts/floBlockchainAPI.js b/docs/scripts/floBlockchainAPI.js deleted file mode 100644 index 473b192..0000000 --- a/docs/scripts/floBlockchainAPI.js +++ /dev/null @@ -1,580 +0,0 @@ -(function (EXPORTS) { //floBlockchainAPI v2.3.3d - /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ - 'use strict'; - const floBlockchainAPI = EXPORTS; - - const DEFAULT = { - blockchain: floGlobals.blockchain, - apiURL: { - FLO: ['https://flosight.duckdns.org/'], - FLO_TEST: ['https://testnet-flosight.duckdns.org', 'https://testnet.flocha.in/'] - }, - sendAmt: 0.001, - fee: 0.0005, - minChangeAmt: 0.0005, - receiverID: floGlobals.adminID - }; - - Object.defineProperties(floBlockchainAPI, { - sendAmt: { - get: () => DEFAULT.sendAmt, - set: amt => !isNaN(amt) ? DEFAULT.sendAmt = amt : null - }, - fee: { - get: () => DEFAULT.fee, - set: fee => !isNaN(fee) ? DEFAULT.fee = fee : null - }, - defaultReceiver: { - get: () => DEFAULT.receiverID, - set: floID => DEFAULT.receiverID = floID - }, - blockchain: { - get: () => DEFAULT.blockchain - } - }); - - if (floGlobals.sendAmt) floBlockchainAPI.sendAmt = floGlobals.sendAmt; - if (floGlobals.fee) floBlockchainAPI.fee = floGlobals.fee; - - Object.defineProperties(floGlobals, { - sendAmt: { - get: () => DEFAULT.sendAmt, - set: amt => !isNaN(amt) ? DEFAULT.sendAmt = amt : null - }, - fee: { - get: () => DEFAULT.fee, - set: fee => !isNaN(fee) ? DEFAULT.fee = fee : null - } - }); - - const allServerList = new Set(floGlobals.apiURL && floGlobals.apiURL[DEFAULT.blockchain] ? floGlobals.apiURL[DEFAULT.blockchain] : DEFAULT.apiURL[DEFAULT.blockchain]); - - var serverList = Array.from(allServerList); - var curPos = floCrypto.randInt(0, serverList.length - 1); - - function fetch_retry(apicall, rm_flosight) { - return new Promise((resolve, reject) => { - let i = serverList.indexOf(rm_flosight) - if (i != -1) serverList.splice(i, 1); - curPos = floCrypto.randInt(0, serverList.length - 1); - fetch_api(apicall, false) - .then(result => resolve(result)) - .catch(error => reject(error)); - }) - } - - function fetch_api(apicall, ic = true) { - return new Promise((resolve, reject) => { - if (serverList.length === 0) { - if (ic) { - serverList = Array.from(allServerList); - curPos = floCrypto.randInt(0, serverList.length - 1); - fetch_api(apicall, false) - .then(result => resolve(result)) - .catch(error => reject(error)); - } else - reject("No floSight server working"); - } else { - let flosight = serverList[curPos]; - fetch(flosight + apicall).then(response => { - if (response.ok) - response.json().then(data => resolve(data)); - else { - fetch_retry(apicall, flosight) - .then(result => resolve(result)) - .catch(error => reject(error)); - } - }).catch(error => { - fetch_retry(apicall, flosight) - .then(result => resolve(result)) - .catch(error => reject(error)); - }) - } - }) - } - - Object.defineProperties(floBlockchainAPI, { - serverList: { - get: () => Array.from(serverList) - }, - current_server: { - get: () => serverList[curPos] - } - }); - - //Promised function to get data from API - const promisedAPI = floBlockchainAPI.promisedAPI = floBlockchainAPI.fetch = function (apicall) { - return new Promise((resolve, reject) => { - //console.log(apicall); - fetch_api(apicall) - .then(result => resolve(result)) - .catch(error => reject(error)); - }); - } - - //Get balance for the given Address - const getBalance = floBlockchainAPI.getBalance = function (addr) { - return new Promise((resolve, reject) => { - promisedAPI(`api/addr/${addr}/balance`) - .then(balance => resolve(parseFloat(balance))) - .catch(error => reject(error)); - }); - } - - //Send Tx to blockchain - const sendTx = floBlockchainAPI.sendTx = function (senderAddr, receiverAddr, sendAmt, privKey, floData = '', strict_utxo = true) { - return new Promise((resolve, reject) => { - if (!floCrypto.validateASCII(floData)) - return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); - else if (!floCrypto.validateFloID(senderAddr)) - return reject(`Invalid address : ${senderAddr}`); - else if (!floCrypto.validateFloID(receiverAddr)) - return reject(`Invalid address : ${receiverAddr}`); - else if (privKey.length < 1 || !floCrypto.verifyPrivKey(privKey, senderAddr)) - return reject("Invalid Private key!"); - else if (typeof sendAmt !== 'number' || sendAmt <= 0) - return reject(`Invalid sendAmt : ${sendAmt}`); - - getBalance(senderAddr).then(balance => { - var fee = DEFAULT.fee; - if (balance < sendAmt + fee) - return reject("Insufficient FLO balance!"); - //get unconfirmed tx list - promisedAPI(`api/addr/${senderAddr}`).then(result => { - readTxs(senderAddr, 0, result.unconfirmedTxApperances).then(result => { - let unconfirmedSpent = {}; - for (let tx of result.items) - if (tx.confirmations == 0) - for (let vin of tx.vin) - if (vin.addr === senderAddr) { - if (Array.isArray(unconfirmedSpent[vin.txid])) - unconfirmedSpent[vin.txid].push(vin.vout); - else - unconfirmedSpent[vin.txid] = [vin.vout]; - } - //get utxos list - promisedAPI(`api/addr/${senderAddr}/utxo`).then(utxos => { - //form/construct the transaction data - var trx = bitjs.transaction(); - var utxoAmt = 0.0; - for (var i = utxos.length - 1; - (i >= 0) && (utxoAmt < sendAmt + fee); i--) { - //use only utxos with confirmations (strict_utxo mode) - if (utxos[i].confirmations || !strict_utxo) { - if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout)) - continue; //A transaction has already used the utxo, but is unconfirmed. - trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); - utxoAmt += utxos[i].amount; - }; - } - if (utxoAmt < sendAmt + fee) - reject("Insufficient FLO: Some UTXOs are unconfirmed"); - else { - trx.addoutput(receiverAddr, sendAmt); - var change = utxoAmt - sendAmt - fee; - if (change > DEFAULT.minChangeAmt) - trx.addoutput(senderAddr, change); - trx.addflodata(floData.replace(/\n/g, ' ')); - var signedTxHash = trx.sign(privKey, 1); - broadcastTx(signedTxHash) - .then(txid => resolve(txid)) - .catch(error => reject(error)) - } - }).catch(error => reject(error)) - }).catch(error => reject(error)) - }).catch(error => reject(error)) - }).catch(error => reject(error)) - }); - } - - //Write Data into blockchain - floBlockchainAPI.writeData = function (senderAddr, data, privKey, receiverAddr = DEFAULT.receiverID, options = {}) { - let strict_utxo = options.strict_utxo === false ? false : true, - sendAmt = isNaN(options.sendAmt) ? DEFAULT.sendAmt : options.sendAmt; - return new Promise((resolve, reject) => { - if (typeof data != "string") - data = JSON.stringify(data); - sendTx(senderAddr, receiverAddr, sendAmt, privKey, data, strict_utxo) - .then(txid => resolve(txid)) - .catch(error => reject(error)); - }); - } - - //merge all UTXOs of a given floID into a single UTXO - floBlockchainAPI.mergeUTXOs = function (floID, privKey, floData = '') { - return new Promise((resolve, reject) => { - if (!floCrypto.validateFloID(floID)) - return reject(`Invalid floID`); - if (!floCrypto.verifyPrivKey(privKey, floID)) - return reject("Invalid Private Key"); - if (!floCrypto.validateASCII(floData)) - return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); - var trx = bitjs.transaction(); - var utxoAmt = 0.0; - var fee = DEFAULT.fee; - promisedAPI(`api/addr/${floID}/utxo`).then(utxos => { - for (var i = utxos.length - 1; i >= 0; i--) - if (utxos[i].confirmations) { - trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); - utxoAmt += utxos[i].amount; - } - trx.addoutput(floID, utxoAmt - fee); - trx.addflodata(floData.replace(/\n/g, ' ')); - var signedTxHash = trx.sign(privKey, 1); - broadcastTx(signedTxHash) - .then(txid => resolve(txid)) - .catch(error => reject(error)) - }).catch(error => reject(error)) - }) - } - - /**Write data into blockchain from (and/or) to multiple floID - * @param {Array} senderPrivKeys List of sender private-keys - * @param {string} data FLO data of the txn - * @param {Array} receivers List of receivers - * @param {boolean} preserveRatio (optional) preserve ratio or equal contribution - * @return {Promise} - */ - floBlockchainAPI.writeDataMultiple = function (senderPrivKeys, data, receivers = [DEFAULT.receiverID], preserveRatio = true) { - return new Promise((resolve, reject) => { - if (!Array.isArray(senderPrivKeys)) - return reject("Invalid senderPrivKeys: SenderPrivKeys must be Array"); - if (!preserveRatio) { - let tmp = {}; - let amount = (DEFAULT.sendAmt * receivers.length) / senderPrivKeys.length; - senderPrivKeys.forEach(key => tmp[key] = amount); - senderPrivKeys = tmp; - } - if (!Array.isArray(receivers)) - return reject("Invalid receivers: Receivers must be Array"); - else { - let tmp = {}; - let amount = DEFAULT.sendAmt; - receivers.forEach(floID => tmp[floID] = amount); - receivers = tmp - } - if (typeof data != "string") - data = JSON.stringify(data); - sendTxMultiple(senderPrivKeys, receivers, data) - .then(txid => resolve(txid)) - .catch(error => reject(error)) - }) - } - - /**Send Tx from (and/or) to multiple floID - * @param {Array or Object} senderPrivKeys List of sender private-key (optional: with coins to be sent) - * @param {Object} receivers List of receivers with respective amount to be sent - * @param {string} floData FLO data of the txn - * @return {Promise} - */ - const sendTxMultiple = floBlockchainAPI.sendTxMultiple = function (senderPrivKeys, receivers, floData = '') { - return new Promise((resolve, reject) => { - if (!floCrypto.validateASCII(floData)) - return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); - let senders = {}, - preserveRatio; - //check for argument validations - try { - let invalids = { - InvalidSenderPrivKeys: [], - InvalidSenderAmountFor: [], - InvalidReceiverIDs: [], - InvalidReceiveAmountFor: [] - } - let inputVal = 0, - outputVal = 0; - //Validate sender privatekeys (and send amount if passed) - //conversion when only privateKeys are passed (preserveRatio mode) - if (Array.isArray(senderPrivKeys)) { - senderPrivKeys.forEach(key => { - try { - if (!key) - invalids.InvalidSenderPrivKeys.push(key); - else { - let floID = floCrypto.getFloID(key); - senders[floID] = { - wif: key - } - } - } catch (error) { - invalids.InvalidSenderPrivKeys.push(key) - } - }) - preserveRatio = true; - } - //conversion when privatekeys are passed with send amount - else { - for (let key in senderPrivKeys) { - try { - if (!key) - invalids.InvalidSenderPrivKeys.push(key); - else { - if (typeof senderPrivKeys[key] !== 'number' || senderPrivKeys[key] <= 0) - invalids.InvalidSenderAmountFor.push(key); - else - inputVal += senderPrivKeys[key]; - let floID = floCrypto.getFloID(key); - senders[floID] = { - wif: key, - coins: senderPrivKeys[key] - } - } - } catch (error) { - invalids.InvalidSenderPrivKeys.push(key) - } - } - preserveRatio = false; - } - //Validate the receiver IDs and receive amount - for (let floID in receivers) { - if (!floCrypto.validateFloID(floID)) - invalids.InvalidReceiverIDs.push(floID); - if (typeof receivers[floID] !== 'number' || receivers[floID] <= 0) - invalids.InvalidReceiveAmountFor.push(floID); - else - outputVal += receivers[floID]; - } - //Reject if any invalids are found - for (let i in invalids) - if (!invalids[i].length) - delete invalids[i]; - if (Object.keys(invalids).length) - return reject(invalids); - //Reject if given inputVal and outputVal are not equal - if (!preserveRatio && inputVal != outputVal) - return reject(`Input Amount (${inputVal}) not equal to Output Amount (${outputVal})`); - } catch (error) { - return reject(error) - } - //Get balance of senders - let promises = []; - for (let floID in senders) - promises.push(getBalance(floID)); - Promise.all(promises).then(results => { - let totalBalance = 0, - totalFee = DEFAULT.fee, - balance = {}; - //Divide fee among sender if not for preserveRatio - if (!preserveRatio) - var dividedFee = totalFee / Object.keys(senders).length; - //Check if balance of each sender is sufficient enough - let insufficient = []; - for (let floID in senders) { - balance[floID] = parseFloat(results.shift()); - if (isNaN(balance[floID]) || (preserveRatio && balance[floID] <= totalFee) || - (!preserveRatio && balance[floID] < senders[floID].coins + dividedFee)) - insufficient.push(floID); - totalBalance += balance[floID]; - } - if (insufficient.length) - return reject({ - InsufficientBalance: insufficient - }) - //Calculate totalSentAmount and check if totalBalance is sufficient - let totalSendAmt = totalFee; - for (let floID in receivers) - totalSendAmt += receivers[floID]; - if (totalBalance < totalSendAmt) - return reject("Insufficient total Balance"); - //Get the UTXOs of the senders - let promises = []; - for (let floID in senders) - promises.push(promisedAPI(`api/addr/${floID}/utxo`)); - Promise.all(promises).then(results => { - let wifSeq = []; - var trx = bitjs.transaction(); - for (let floID in senders) { - let utxos = results.shift(); - let sendAmt; - if (preserveRatio) { - let ratio = (balance[floID] / totalBalance); - sendAmt = totalSendAmt * ratio; - } else - sendAmt = senders[floID].coins + dividedFee; - let wif = senders[floID].wif; - let utxoAmt = 0.0; - for (let i = utxos.length - 1; - (i >= 0) && (utxoAmt < sendAmt); i--) { - if (utxos[i].confirmations) { - trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); - wifSeq.push(wif); - utxoAmt += utxos[i].amount; - } - } - if (utxoAmt < sendAmt) - return reject("Insufficient balance:" + floID); - let change = (utxoAmt - sendAmt); - if (change > 0) - trx.addoutput(floID, change); - } - for (let floID in receivers) - trx.addoutput(floID, receivers[floID]); - trx.addflodata(floData.replace(/\n/g, ' ')); - for (let i = 0; i < wifSeq.length; i++) - trx.signinput(i, wifSeq[i], 1); - var signedTxHash = trx.serialize(); - broadcastTx(signedTxHash) - .then(txid => resolve(txid)) - .catch(error => reject(error)) - }).catch(error => reject(error)) - }).catch(error => reject(error)) - }) - } - - //Broadcast signed Tx in blockchain using API - const broadcastTx = floBlockchainAPI.broadcastTx = function (signedTxHash) { - return new Promise((resolve, reject) => { - if (signedTxHash.length < 1) - return reject("Empty Signature"); - var url = serverList[curPos] + 'api/tx/send'; - fetch(url, { - method: "POST", - headers: { - 'Content-Type': 'application/json' - }, - body: `{"rawtx":"${signedTxHash}"}` - }).then(response => { - if (response.ok) - response.json().then(data => resolve(data.txid.result)); - else - response.text().then(data => resolve(data)); - }).catch(error => reject(error)); - }) - } - - floBlockchainAPI.getTx = function (txid) { - return new Promise((resolve, reject) => { - promisedAPI(`api/tx/${txid}`) - .then(response => resolve(response)) - .catch(error => reject(error)) - }) - } - - //Read Txs of Address between from and to - const readTxs = floBlockchainAPI.readTxs = function (addr, from, to) { - return new Promise((resolve, reject) => { - promisedAPI(`api/addrs/${addr}/txs?from=${from}&to=${to}`) - .then(response => resolve(response)) - .catch(error => reject(error)) - }); - } - - //Read All Txs of Address (newest first) - floBlockchainAPI.readAllTxs = function (addr) { - return new Promise((resolve, reject) => { - promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => { - promisedAPI(`api/addrs/${addr}/txs?from=0&to=${response.totalItems}0`) - .then(response => resolve(response.items)) - .catch(error => reject(error)); - }).catch(error => reject(error)) - }); - } - - /*Read flo Data from txs of given Address - options can be used to filter data - limit : maximum number of filtered data (default = 1000, negative = no limit) - ignoreOld : ignore old txs (default = 0) - sentOnly : filters only sent data - receivedOnly: filters only received data - pattern : filters data that with JSON pattern - filter : custom filter funtion for floData (eg . filter: d => {return d[0] == '$'}) - tx : (boolean) resolve tx data or not (resolves an Array of Object with tx details) - sender : flo-id(s) of sender - receiver : flo-id(s) of receiver - */ - floBlockchainAPI.readData = function (addr, options = {}) { - options.limit = options.limit || 0; - options.ignoreOld = options.ignoreOld || 0; - if (typeof options.senders === "string") options.senders = [options.senders]; - if (typeof options.receivers === "string") options.receivers = [options.receivers]; - return new Promise((resolve, reject) => { - promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => { - var newItems = response.totalItems - options.ignoreOld; - promisedAPI(`api/addrs/${addr}/txs?from=0&to=${newItems * 2}`).then(response => { - if (options.limit <= 0) - options.limit = response.items.length; - var filteredData = []; - let numToRead = response.totalItems - options.ignoreOld, - unconfirmedCount = 0; - for (let i = 0; i < numToRead && filteredData.length < options.limit; i++) { - if (!response.items[i].confirmations) { //unconfirmed transactions - unconfirmedCount++; - if (numToRead < response.items[i].length) - numToRead++; - continue; - } - if (options.pattern) { - try { - let jsonContent = JSON.parse(response.items[i].floData); - if (!Object.keys(jsonContent).includes(options.pattern)) - continue; - } catch (error) { - continue; - } - } - if (options.sentOnly) { - let flag = false; - for (let vin of response.items[i].vin) - if (vin.addr === addr) { - flag = true; - break; - } - if (!flag) continue; - } - if (Array.isArray(options.senders)) { - let flag = false; - for (let vin of response.items[i].vin) - if (options.senders.includes(vin.addr)) { - flag = true; - break; - } - if (!flag) continue; - } - if (options.receivedOnly) { - let flag = false; - for (let vout of response.items[i].vout) - if (vout.scriptPubKey.addresses[0] === addr) { - flag = true; - break; - } - if (!flag) continue; - } - if (Array.isArray(options.receivers)) { - let flag = false; - for (let vout of response.items[i].vout) - if (options.receivers.includes(vout.scriptPubKey.addresses[0])) { - flag = true; - break; - } - if (!flag) continue; - } - if (options.filter && !options.filter(response.items[i].floData)) - continue; - - if (options.tx) { - let d = {} - d.txid = response.items[i].txid; - d.time = response.items[i].time; - d.blockheight = response.items[i].blockheight; - d.senders = new Set(response.items[i].vin.map(v => v.addr)); - d.receivers = new Set(response.items[i].vout.map(v => v.scriptPubKey.addresses[0])); - d.data = response.items[i].floData; - filteredData.push(d); - } else - filteredData.push(response.items[i].floData); - } - resolve({ - totalTxs: response.totalItems - unconfirmedCount, - data: filteredData - }); - }).catch(error => { - reject(error); - }); - }).catch(error => { - reject(error); - }); - }); - } - - -})('object' === typeof module ? module.exports : window.floBlockchainAPI = {}); \ No newline at end of file diff --git a/docs/scripts/floCrypto.js b/docs/scripts/floCrypto.js deleted file mode 100644 index 563d77f..0000000 --- a/docs/scripts/floCrypto.js +++ /dev/null @@ -1,442 +0,0 @@ -(function (EXPORTS) { //floCrypto v2.3.3e - /* FLO Crypto Operators */ - 'use strict'; - const floCrypto = EXPORTS; - - const p = BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16); - const ecparams = EllipticCurve.getSECCurveByName("secp256k1"); - const ascii_alternatives = `‘ '\n’ '\n“ "\n” "\n– --\n— ---\n≥ >=\n≤ <=\n≠ !=\n× *\n÷ /\n← <-\n→ ->\n↔ <->\n⇒ =>\n⇐ <=\n⇔ <=>`; - const exponent1 = () => p.add(BigInteger.ONE).divide(BigInteger("4")); - coinjs.compressed = true; //defaulting coinjs compressed to true; - - function calculateY(x) { - let exp = exponent1(); - // x is x value of public key in BigInteger format without 02 or 03 or 04 prefix - return x.modPow(BigInteger("3"), p).add(BigInteger("7")).mod(p).modPow(exp, p) - } - - function getUncompressedPublicKey(compressedPublicKey) { - // Fetch x from compressedPublicKey - let pubKeyBytes = Crypto.util.hexToBytes(compressedPublicKey); - const prefix = pubKeyBytes.shift() // remove prefix - let prefix_modulus = prefix % 2; - pubKeyBytes.unshift(0) // add prefix 0 - let x = new BigInteger(pubKeyBytes) - let xDecimalValue = x.toString() - // Fetch y - let y = calculateY(x); - let yDecimalValue = y.toString(); - // verify y value - let resultBigInt = y.mod(BigInteger("2")); - let check = resultBigInt.toString() % 2; - if (prefix_modulus !== check) - yDecimalValue = y.negate().mod(p).toString(); - return { - x: xDecimalValue, - y: yDecimalValue - }; - } - - function getSenderPublicKeyString() { - let privateKey = ellipticCurveEncryption.senderRandom(); - var senderPublicKeyString = ellipticCurveEncryption.senderPublicString(privateKey); - return { - privateKey: privateKey, - senderPublicKeyString: senderPublicKeyString - } - } - - function deriveSharedKeySender(receiverPublicKeyHex, senderPrivateKey) { - let receiverPublicKeyString = getUncompressedPublicKey(receiverPublicKeyHex); - var senderDerivedKey = ellipticCurveEncryption.senderSharedKeyDerivation( - receiverPublicKeyString.x, receiverPublicKeyString.y, senderPrivateKey); - return senderDerivedKey; - } - - function deriveSharedKeyReceiver(senderPublicKeyString, receiverPrivateKey) { - return ellipticCurveEncryption.receiverSharedKeyDerivation( - senderPublicKeyString.XValuePublicString, senderPublicKeyString.YValuePublicString, receiverPrivateKey); - } - - function getReceiverPublicKeyString(privateKey) { - return ellipticCurveEncryption.receiverPublicString(privateKey); - } - - function wifToDecimal(pk_wif, isPubKeyCompressed = false) { - let pk = Bitcoin.Base58.decode(pk_wif) - pk.shift() - pk.splice(-4, 4) - //If the private key corresponded to a compressed public key, also drop the last byte (it should be 0x01). - if (isPubKeyCompressed == true) pk.pop() - pk.unshift(0) - let privateKeyDecimal = BigInteger(pk).toString() - let privateKeyHex = Crypto.util.bytesToHex(pk) - return { - privateKeyDecimal: privateKeyDecimal, - privateKeyHex: privateKeyHex - } - } - - //generate a random Interger within range - floCrypto.randInt = function (min, max) { - min = Math.ceil(min); - max = Math.floor(max); - return Math.floor(securedMathRandom() * (max - min + 1)) + min; - } - - //generate a random String within length (options : alphaNumeric chars only) - floCrypto.randString = function (length, alphaNumeric = true) { - var result = ''; - var characters = alphaNumeric ? 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' : - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+-./*?@#&$<>=[]{}():'; - for (var i = 0; i < length; i++) - result += characters.charAt(Math.floor(securedMathRandom() * characters.length)); - return result; - } - - //Encrypt Data using public-key - floCrypto.encryptData = function (data, receiverPublicKeyHex) { - var senderECKeyData = getSenderPublicKeyString(); - var senderDerivedKey = deriveSharedKeySender(receiverPublicKeyHex, senderECKeyData.privateKey); - let senderKey = senderDerivedKey.XValue + senderDerivedKey.YValue; - let secret = Crypto.AES.encrypt(data, senderKey); - return { - secret: secret, - senderPublicKeyString: senderECKeyData.senderPublicKeyString - }; - } - - //Decrypt Data using private-key - floCrypto.decryptData = function (data, privateKeyHex) { - var receiverECKeyData = {}; - if (typeof privateKeyHex !== "string") throw new Error("No private key found."); - let privateKey = wifToDecimal(privateKeyHex, true); - if (typeof privateKey.privateKeyDecimal !== "string") throw new Error("Failed to detremine your private key."); - receiverECKeyData.privateKey = privateKey.privateKeyDecimal; - var receiverDerivedKey = deriveSharedKeyReceiver(data.senderPublicKeyString, receiverECKeyData.privateKey); - let receiverKey = receiverDerivedKey.XValue + receiverDerivedKey.YValue; - let decryptMsg = Crypto.AES.decrypt(data.secret, receiverKey); - return decryptMsg; - } - - //Sign data using private-key - floCrypto.signData = function (data, privateKeyHex) { - var key = new Bitcoin.ECKey(privateKeyHex); - var messageHash = Crypto.SHA256(data); - var messageSign = Bitcoin.ECDSA.sign(messageHash, key.priv); - var sighex = Crypto.util.bytesToHex(messageSign); - return sighex; - } - - //Verify signatue of the data using public-key - floCrypto.verifySign = function (data, signatureHex, publicKeyHex) { - var msgHash = Crypto.SHA256(data); - var sigBytes = Crypto.util.hexToBytes(signatureHex); - var publicKeyPoint = ecparams.getCurve().decodePointHex(publicKeyHex); - var verify = Bitcoin.ECDSA.verify(msgHash, sigBytes, publicKeyPoint); - return verify; - } - - //Generates a new flo ID and returns private-key, public-key and floID - const generateNewID = floCrypto.generateNewID = function () { - var key = new Bitcoin.ECKey(false); - key.setCompressed(true); - return { - floID: key.getBitcoinAddress(), - pubKey: key.getPubKeyHex(), - privKey: key.getBitcoinWalletImportFormat() - } - } - - Object.defineProperties(floCrypto, { - newID: { - get: () => generateNewID() - }, - tmpID: { - get: () => { - let bytes = Crypto.util.randomBytes(20); - bytes.unshift(bitjs.pub); - var hash = Crypto.SHA256(Crypto.SHA256(bytes, { - asBytes: true - }), { - asBytes: true - }); - var checksum = hash.slice(0, 4); - return bitjs.Base58.encode(bytes.concat(checksum)); - } - } - }); - - //Returns public-key from private-key - floCrypto.getPubKeyHex = function (privateKeyHex) { - if (!privateKeyHex) - return null; - var key = new Bitcoin.ECKey(privateKeyHex); - if (key.priv == null) - return null; - key.setCompressed(true); - return key.getPubKeyHex(); - } - - //Returns flo-ID from public-key or private-key - floCrypto.getFloID = function (keyHex) { - if (!keyHex) - return null; - try { - var key = new Bitcoin.ECKey(keyHex); - if (key.priv == null) - key.setPub(keyHex); - return key.getBitcoinAddress(); - } catch { - return null; - } - } - - floCrypto.getAddress = function (privateKeyHex, strict = false) { - if (!privateKeyHex) - return; - var key = new Bitcoin.ECKey(privateKeyHex); - if (key.priv == null) - return null; - key.setCompressed(true); - let pubKey = key.getPubKeyHex(), - version = bitjs.Base58.decode(privateKeyHex)[0]; - switch (version) { - case coinjs.priv: //BTC - return coinjs.bech32Address(pubKey).address; - case bitjs.priv: //FLO - return bitjs.pubkey2address(pubKey); - default: - return strict ? false : bitjs.pubkey2address(pubKey); //default to FLO address (if strict=false) - } - } - - //Verify the private-key for the given public-key or flo-ID - floCrypto.verifyPrivKey = function (privateKeyHex, pubKey_floID, isfloID = true) { - if (!privateKeyHex || !pubKey_floID) - return false; - try { - var key = new Bitcoin.ECKey(privateKeyHex); - if (key.priv == null) - return false; - key.setCompressed(true); - if (isfloID && pubKey_floID == key.getBitcoinAddress()) - return true; - else if (!isfloID && pubKey_floID == key.getPubKeyHex()) - return true; - else - return false; - } catch { - return null; - } - } - - //Check if the given flo-id is valid or not - floCrypto.validateFloID = function (floID) { - if (!floID) - return false; - try { - let addr = new Bitcoin.Address(floID); - return true; - } catch { - return false; - } - } - - //Check if the given address (any blockchain) is valid or not - floCrypto.validateAddr = function (address, std = true, bech = true) { - let raw = decodeAddress(address); - if (!raw) - return false; - if (typeof raw.version !== 'undefined') { //legacy or segwit - if (std == false) - return false; - else if (std === true || (!Array.isArray(std) && std === raw.version) || (Array.isArray(std) && std.includes(raw.version))) - return true; - else - return false; - } else if (typeof raw.bech_version !== 'undefined') { //bech32 - if (bech === false) - return false; - else if (bech === true || (!Array.isArray(bech) && bech === raw.bech_version) || (Array.isArray(bech) && bech.includes(raw.bech_version))) - return true; - else - return false; - } else //unknown - return false; - } - - //Check the public-key for the address (any blockchain) - floCrypto.verifyPubKey = function (pubKeyHex, address) { - let raw = decodeAddress(address), - pub_hash = Crypto.util.bytesToHex(ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubKeyHex), { - asBytes: true - }))); - return raw ? pub_hash === raw.hex : false; - } - - //Convert the given address (any blockchain) to equivalent floID - floCrypto.toFloID = function (address, options = null) { - if (!address) - return; - let raw = decodeAddress(address); - if (!raw) - return; - else if (options) { - if (typeof raw.version !== 'undefined' && (!options.std || !options.std.includes(raw.version))) - return; - if (typeof raw.bech_version !== 'undefined' && (!options.bech || !options.bech.includes(raw.bech_version))) - return; - } - raw.bytes.unshift(bitjs.pub); - let hash = Crypto.SHA256(Crypto.SHA256(raw.bytes, { - asBytes: true - }), { - asBytes: true - }); - return bitjs.Base58.encode(raw.bytes.concat(hash.slice(0, 4))); - } - - //Checks if the given addresses (any blockchain) are same (w.r.t keys) - floCrypto.isSameAddr = function (addr1, addr2) { - if (!addr1 || !addr2) - return; - let raw1 = decodeAddress(addr1), - raw2 = decodeAddress(addr2); - if (!raw1 || !raw2) - return false; - else - return raw1.hex === raw2.hex; - } - - const decodeAddress = floCrypto.decodeAddr = function (address) { - if (!address) - return; - else if (address.length == 33 || address.length == 34) { //legacy encoding - let decode = bitjs.Base58.decode(address); - let bytes = decode.slice(0, decode.length - 4); - let checksum = decode.slice(decode.length - 4), - hash = Crypto.SHA256(Crypto.SHA256(bytes, { - asBytes: true - }), { - asBytes: true - }); - return (hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3]) ? null : { - version: bytes.shift(), - hex: Crypto.util.bytesToHex(bytes), - bytes - } - } else if (address.length == 42) { //bech encoding - let decode = coinjs.bech32_decode(address); - if (decode) { - let bytes = decode.data; - let bech_version = bytes.shift(); - bytes = coinjs.bech32_convert(bytes, 5, 8, false); - return { - bech_version, - hrp: decode.hrp, - hex: Crypto.util.bytesToHex(bytes), - bytes - } - } else - return null; - } - } - - //Split the str using shamir's Secret and Returns the shares - floCrypto.createShamirsSecretShares = function (str, total_shares, threshold_limit) { - try { - if (str.length > 0) { - var strHex = shamirSecretShare.str2hex(str); - var shares = shamirSecretShare.share(strHex, total_shares, threshold_limit); - return shares; - } - return false; - } catch { - return false - } - } - - //Returns the retrived secret by combining the shamirs shares - const retrieveShamirSecret = floCrypto.retrieveShamirSecret = function (sharesArray) { - try { - if (sharesArray.length > 0) { - var comb = shamirSecretShare.combine(sharesArray.slice(0, sharesArray.length)); - comb = shamirSecretShare.hex2str(comb); - return comb; - } - return false; - } catch { - return false; - } - } - - //Verifies the shares and str - floCrypto.verifyShamirsSecret = function (sharesArray, str) { - if (!str) - return null; - else if (retrieveShamirSecret(sharesArray) === str) - return true; - else - return false; - } - - const validateASCII = floCrypto.validateASCII = function (string, bool = true) { - if (typeof string !== "string") - return null; - if (bool) { - let x; - for (let i = 0; i < string.length; i++) { - x = string.charCodeAt(i); - if (x < 32 || x > 127) - return false; - } - return true; - } else { - let x, invalids = {}; - for (let i = 0; i < string.length; i++) { - x = string.charCodeAt(i); - if (x < 32 || x > 127) - if (x in invalids) - invalids[string[i]].push(i) - else - invalids[string[i]] = [i]; - } - if (Object.keys(invalids).length) - return invalids; - else - return true; - } - } - - floCrypto.convertToASCII = function (string, mode = 'soft-remove') { - let chars = validateASCII(string, false); - if (chars === true) - return string; - else if (chars === null) - return null; - let convertor, result = string, - refAlt = {}; - ascii_alternatives.split('\n').forEach(a => refAlt[a[0]] = a.slice(2)); - mode = mode.toLowerCase(); - if (mode === "hard-unicode") - convertor = (c) => `\\u${('000' + c.charCodeAt().toString(16)).slice(-4)}`; - else if (mode === "soft-unicode") - convertor = (c) => refAlt[c] || `\\u${('000' + c.charCodeAt().toString(16)).slice(-4)}`; - else if (mode === "hard-remove") - convertor = c => ""; - else if (mode === "soft-remove") - convertor = c => refAlt[c] || ""; - else - return null; - for (let c in chars) - result = result.replaceAll(c, convertor(c)); - return result; - } - - floCrypto.revertUnicode = function (string) { - return string.replace(/\\u[\dA-F]{4}/gi, - m => String.fromCharCode(parseInt(m.replace(/\\u/g, ''), 16))); - } - -})('object' === typeof module ? module.exports : window.floCrypto = {}); \ No newline at end of file diff --git a/docs/scripts/floTokenAPI.js b/docs/scripts/floTokenAPI.js deleted file mode 100644 index 3f4cb5f..0000000 --- a/docs/scripts/floTokenAPI.js +++ /dev/null @@ -1,102 +0,0 @@ -(function(EXPORTS) { //floTokenAPI v1.0.3c - /* Token Operator to send/receive tokens via blockchain using API calls*/ - 'use strict'; - const tokenAPI = EXPORTS; - - const DEFAULT = { - apiURL: floGlobals.tokenURL || "https://ranchimallflo.duckdns.org/", - currency: "rupee" - } - - Object.defineProperties(tokenAPI, { - URL: { - get: () => DEFAULT.apiURL - }, - currency: { - get: () => DEFAULT.currency, - set: currency => DEFAULT.currency = currency - } - }); - - if (floGlobals.currency) tokenAPI.currency = floGlobals.currency; - - Object.defineProperties(floGlobals, { - currency: { - get: () => DEFAULT.currency, - set: currency => DEFAULT.currency = currency - } - }); - - const fetch_api = tokenAPI.fetch = function(apicall) { - return new Promise((resolve, reject) => { - console.debug(DEFAULT.apiURL + apicall); - fetch(DEFAULT.apiURL + apicall).then(response => { - if (response.ok) - response.json().then(data => resolve(data)); - else - reject(response) - }).catch(error => reject(error)) - }) - } - - const getBalance = tokenAPI.getBalance = function(floID, token = DEFAULT.currency) { - return new Promise((resolve, reject) => { - fetch_api(`api/v1.0/getFloAddressBalance?token=${token}&floAddress=${floID}`) - .then(result => resolve(result.balance || 0)) - .catch(error => reject(error)) - }) - } - - tokenAPI.getTx = function(txID) { - return new Promise((resolve, reject) => { - fetch_api(`api/v1.0/getTransactionDetails/${txID}`).then(res => { - if (res.result === "error") - reject(res.description); - else if (!res.parsedFloData) - reject("Data piece (parsedFloData) missing"); - else if (!res.transactionDetails) - reject("Data piece (transactionDetails) missing"); - else - resolve(res); - }).catch(error => reject(error)) - }) - } - - tokenAPI.sendToken = function(privKey, amount, receiverID, message = "", token = DEFAULT.currency, options = {}) { - return new Promise((resolve, reject) => { - let senderID = floCrypto.getFloID(privKey); - if (typeof amount !== "number" || isNaN(amount) || amount <= 0) - return reject("Invalid amount"); - getBalance(senderID, token).then(bal => { - if (amount > bal) - return reject(`Insufficient ${token}# balance`); - floBlockchainAPI.writeData(senderID, `send ${amount} ${token}# ${message}`, privKey, receiverID, options) - .then(txid => resolve(txid)) - .catch(error => reject(error)) - }).catch(error => reject(error)) - }); - } - - tokenAPI.getAllTxs = function(floID, token = DEFAULT.currency) { - return new Promise((resolve, reject) => { - fetch_api(`api/v1.0/getFloAddressTransactions?token=${token}&floAddress=${floID}`) - .then(result => resolve(result)) - .catch(error => reject(error)) - }) - } - - const util = tokenAPI.util = {}; - - util.parseTxData = function(txData) { - let parsedData = {}; - for (let p in txData.parsedFloData) - parsedData[p] = txData.parsedFloData[p]; - parsedData.sender = txData.transactionDetails.vin[0].addr; - for (let vout of txData.transactionDetails.vout) - if (vout.scriptPubKey.addresses[0] !== parsedData.sender) - parsedData.receiver = vout.scriptPubKey.addresses[0]; - parsedData.time = txData.transactionDetails.time; - return parsedData; - } - -})('object' === typeof module ? module.exports : window.floTokenAPI = {}); \ No newline at end of file diff --git a/docs/scripts/lib.js b/docs/scripts/lib.js deleted file mode 100644 index b435194..0000000 --- a/docs/scripts/lib.js +++ /dev/null @@ -1,9356 +0,0 @@ -(function(GLOBAL) { //lib v1.3.1 - 'use strict'; - /* Utility Libraries required for Standard operations - * All credits for these codes belong to their respective creators, moderators and owners. - * For more info (including license and terms of use), please visit respective source. - */ - GLOBAL.cryptocoin = (typeof floGlobals === 'undefined' ? null : floGlobals.blockchain) || 'FLO'; - - const getRandomBytes = (function() { - if (typeof require === 'function') { - const crypto = require('crypto'); - return function(buf) { - var bytes = crypto.randomBytes(buf.length); - buf.set(bytes); - return buf; - } - } else if (GLOBAL.crypto && GLOBAL.crypto.getRandomValues) { - return function(buf) { - return GLOBAL.crypto.getRandomValues(buf); - } - } else - throw Error('Unable to define getRandomBytes'); - })(); - - - GLOBAL.securedMathRandom = (function() { - if (typeof require === 'function') { - const crypto = require('crypto'); - return function() { - return crypto.randomBytes(4).readUInt32LE() / 0xffffffff; - } - } else if (GLOBAL.crypto && GLOBAL.crypto.getRandomValues) { - return function() { - return (GLOBAL.crypto.getRandomValues(new Uint32Array(1))[0] / 0xffffffff); - } - } else - throw Error('Unable to define securedMathRandom'); - })(); - - //Crypto.js - (function() { - // Global Crypto object - var Crypto = GLOBAL.Crypto = {}; - /*! - * Crypto-JS v2.5.4 Crypto.js - * http://code.google.com/p/crypto-js/ - * Copyright (c) 2009-2013, Jeff Mott. All rights reserved. - * http://code.google.com/p/crypto-js/wiki/License - */ - (function() { - - var base64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - // Crypto utilities - var util = Crypto.util = { - - // Bit-wise rotate left - rotl: function(n, b) { - return (n << b) | (n >>> (32 - b)); - }, - - // Bit-wise rotate right - rotr: function(n, b) { - return (n << (32 - b)) | (n >>> b); - }, - - // Swap big-endian to little-endian and vice versa - endian: function(n) { - - // If number given, swap endian - if (n.constructor == Number) { - return util.rotl(n, 8) & 0x00FF00FF | - util.rotl(n, 24) & 0xFF00FF00; - } - - // Else, assume array and swap all items - for (var i = 0; i < n.length; i++) - n[i] = util.endian(n[i]); - return n; - - }, - - // Generate an array of any length of random bytes - randomBytes: function(n) { - for (var bytes = []; n > 0; n--) - bytes.push(Math.floor(securedMathRandom() * 256)); - return bytes; - }, - - // Convert a byte array to big-endian 32-bit words - bytesToWords: function(bytes) { - for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) - words[b >>> 5] |= (bytes[i] & 0xFF) << (24 - b % 32); - return words; - }, - - // Convert big-endian 32-bit words to a byte array - wordsToBytes: function(words) { - for (var bytes = [], b = 0; b < words.length * 32; b += 8) - bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); - return bytes; - }, - - // Convert a byte array to a hex string - bytesToHex: function(bytes) { - for (var hex = [], i = 0; i < bytes.length; i++) { - hex.push((bytes[i] >>> 4).toString(16)); - hex.push((bytes[i] & 0xF).toString(16)); - } - return hex.join(""); - }, - - // Convert a hex string to a byte array - hexToBytes: function(hex) { - for (var bytes = [], c = 0; c < hex.length; c += 2) - bytes.push(parseInt(hex.substr(c, 2), 16)); - return bytes; - }, - - // Convert a byte array to a base-64 string - bytesToBase64: function(bytes) { - for (var base64 = [], i = 0; i < bytes.length; i += 3) { - var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; - for (var j = 0; j < 4; j++) { - if (i * 8 + j * 6 <= bytes.length * 8) - base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F)); - else base64.push("="); - } - } - - return base64.join(""); - }, - - // Convert a base-64 string to a byte array - base64ToBytes: function(base64) { - // Remove non-base-64 characters - base64 = base64.replace(/[^A-Z0-9+\/]/ig, ""); - - for (var bytes = [], i = 0, imod4 = 0; i < base64.length; imod4 = ++i % 4) { - if (imod4 == 0) continue; - bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) | - (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); - } - - return bytes; - } - - }; - - // Crypto character encodings - var charenc = Crypto.charenc = {}; - - // UTF-8 encoding - var UTF8 = charenc.UTF8 = { - - // Convert a string to a byte array - stringToBytes: function(str) { - return Binary.stringToBytes(unescape(encodeURIComponent(str))); - }, - - // Convert a byte array to a string - bytesToString: function(bytes) { - return decodeURIComponent(escape(Binary.bytesToString(bytes))); - } - - }; - - // Binary encoding - var Binary = charenc.Binary = { - - // Convert a string to a byte array - stringToBytes: function(str) { - for (var bytes = [], i = 0; i < str.length; i++) - bytes.push(str.charCodeAt(i) & 0xFF); - return bytes; - }, - - // Convert a byte array to a string - bytesToString: function(bytes) { - for (var str = [], i = 0; i < bytes.length; i++) - str.push(String.fromCharCode(bytes[i])); - return str.join(""); - } - - }; - - })(); - //Adding SHA1 to fix basic PKBDF2 - /* - * Crypto-JS v2.5.4 - * http://code.google.com/p/crypto-js/ - * (c) 2009-2012 by Jeff Mott. All rights reserved. - * http://code.google.com/p/crypto-js/wiki/License - */ - (function() { - - // Shortcuts - var C = Crypto, - util = C.util, - charenc = C.charenc, - UTF8 = charenc.UTF8, - Binary = charenc.Binary; - - // Public API - var SHA1 = C.SHA1 = function(message, options) { - var digestbytes = util.wordsToBytes(SHA1._sha1(message)); - return options && options.asBytes ? digestbytes : - options && options.asString ? Binary.bytesToString(digestbytes) : - util.bytesToHex(digestbytes); - }; - - // The core - SHA1._sha1 = function(message) { - - // Convert to byte array - if (message.constructor == String) message = UTF8.stringToBytes(message); - /* else, assume byte array already */ - - var m = util.bytesToWords(message), - l = message.length * 8, - w = [], - H0 = 1732584193, - H1 = -271733879, - H2 = -1732584194, - H3 = 271733878, - H4 = -1009589776; - - // Padding - m[l >> 5] |= 0x80 << (24 - l % 32); - m[((l + 64 >>> 9) << 4) + 15] = l; - - for (var i = 0; i < m.length; i += 16) { - - var a = H0, - b = H1, - c = H2, - d = H3, - e = H4; - - for (var j = 0; j < 80; j++) { - - if (j < 16) w[j] = m[i + j]; - else { - var n = w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16]; - w[j] = (n << 1) | (n >>> 31); - } - - var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + ( - j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 : - j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 : - j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 : - (H1 ^ H2 ^ H3) - 899497514); - - H4 = H3; - H3 = H2; - H2 = (H1 << 30) | (H1 >>> 2); - H1 = H0; - H0 = t; - - } - - H0 += a; - H1 += b; - H2 += c; - H3 += d; - H4 += e; - - } - - return [H0, H1, H2, H3, H4]; - - }; - - // Package private blocksize - SHA1._blocksize = 16; - - SHA1._digestsize = 20; - - })(); - - //Added to make PKBDF2 work - /* - * Crypto-JS v2.5.4 - * http://code.google.com/p/crypto-js/ - * (c) 2009-2012 by Jeff Mott. All rights reserved. - * http://code.google.com/p/crypto-js/wiki/License - */ - (function() { - - // Shortcuts - var C = Crypto, - util = C.util, - charenc = C.charenc, - UTF8 = charenc.UTF8, - Binary = charenc.Binary; - - C.HMAC = function(hasher, message, key, options) { - - // Convert to byte arrays - if (message.constructor == String) message = UTF8.stringToBytes(message); - if (key.constructor == String) key = UTF8.stringToBytes(key); - /* else, assume byte arrays already */ - - // Allow arbitrary length keys - if (key.length > hasher._blocksize * 4) - key = hasher(key, { - asBytes: true - }); - - // XOR keys with pad constants - var okey = key.slice(0), - ikey = key.slice(0); - for (var i = 0; i < hasher._blocksize * 4; i++) { - okey[i] ^= 0x5C; - ikey[i] ^= 0x36; - } - - var hmacbytes = hasher(okey.concat(hasher(ikey.concat(message), { - asBytes: true - })), { - asBytes: true - }); - - return options && options.asBytes ? hmacbytes : - options && options.asString ? Binary.bytesToString(hmacbytes) : - util.bytesToHex(hmacbytes); - - }; - - })(); - - - //crypto-sha256-hmac.js - /* - * Crypto-JS v2.5.4 - * http://code.google.com/p/crypto-js/ - * (c) 2009-2012 by Jeff Mott. All rights reserved. - * http://code.google.com/p/crypto-js/wiki/License - */ - (function() { - var d = Crypto, - k = d.util, - g = d.charenc, - b = g.UTF8, - a = g.Binary, - c = [1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, - 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, - 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, - 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, - 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, - 2730485921, - 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, - 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, - 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 - ], - e = d.SHA256 = function(b, c) { - var f = k.wordsToBytes(e._sha256(b)); - return c && c.asBytes ? f : c && c.asString ? a.bytesToString(f) : k.bytesToHex(f) - }; - e._sha256 = function(a) { - a.constructor == String && (a = b.stringToBytes(a)); - var e = k.bytesToWords(a), - f = a.length * 8, - a = [1779033703, 3144134277, - 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225 - ], - d = [], - g, m, r, i, n, o, s, t, h, l, j; - e[f >> 5] |= 128 << 24 - f % 32; - e[(f + 64 >> 9 << 4) + 15] = f; - for (t = 0; t < e.length; t += 16) { - f = a[0]; - g = a[1]; - m = a[2]; - r = a[3]; - i = a[4]; - n = a[5]; - o = a[6]; - s = a[7]; - for (h = 0; h < 64; h++) { - h < 16 ? d[h] = e[h + t] : (l = d[h - 15], j = d[h - 2], d[h] = ((l << 25 | l >>> 7) ^ - (l << 14 | l >>> 18) ^ l >>> 3) + (d[h - 7] >>> 0) + ((j << 15 | j >>> 17) ^ - (j << 13 | j >>> 19) ^ j >>> 10) + (d[h - 16] >>> 0)); - j = f & g ^ f & m ^ g & m; - var u = (f << 30 | f >>> 2) ^ (f << 19 | f >>> 13) ^ (f << 10 | f >>> 22); - l = (s >>> 0) + ((i << 26 | i >>> 6) ^ (i << 21 | i >>> 11) ^ (i << 7 | i >>> 25)) + - (i & n ^ ~i & o) + c[h] + (d[h] >>> 0); - j = u + j; - s = o; - o = n; - n = i; - i = r + l >>> 0; - r = m; - m = g; - g = f; - f = l + j >>> 0 - } - a[0] += f; - a[1] += g; - a[2] += m; - a[3] += r; - a[4] += i; - a[5] += n; - a[6] += o; - a[7] += s - } - return a - }; - e._blocksize = 16; - e._digestsize = 32 - })(); - (function() { - var d = Crypto, - k = d.util, - g = d.charenc, - b = g.UTF8, - a = g.Binary; - d.HMAC = function(c, e, d, g) { - e.constructor == String && (e = b.stringToBytes(e)); - d.constructor == String && (d = b.stringToBytes(d)); - d.length > c._blocksize * 4 && (d = c(d, { - asBytes: !0 - })); - for (var f = d.slice(0), d = d.slice(0), q = 0; q < c._blocksize * 4; q++) f[q] ^= 92, d[q] ^= - 54; - c = c(f.concat(c(d.concat(e), { - asBytes: !0 - })), { - asBytes: !0 - }); - return g && g.asBytes ? c : g && g.asString ? a.bytesToString(c) : k.bytesToHex(c) - } - })(); - })(); - - //SecureRandom.js - (function() { - - - /*! - * Random number generator with ArcFour PRNG - * - * NOTE: For best results, put code like - * - * in your main HTML document. - * - * Copyright Tom Wu, bitaddress.org BSD License. - * http://www-cs-students.stanford.edu/~tjw/jsbn/LICENSE - */ - - // Constructor function of Global SecureRandom object - var sr = GLOBAL.SecureRandom = function() {}; - - // Properties - sr.state; - sr.pool; - sr.pptr; - sr.poolCopyOnInit; - - // Pool size must be a multiple of 4 and greater than 32. - // An array of bytes the size of the pool will be passed to init() - sr.poolSize = 256; - - // --- object methods --- - - // public method - // ba: byte array - sr.prototype.nextBytes = function(ba) { - var i; - if (getRandomBytes && GLOBAL.Uint8Array) { - try { - var rvBytes = new Uint8Array(ba.length); - getRandomBytes(rvBytes); - for (i = 0; i < ba.length; ++i) - ba[i] = sr.getByte() ^ rvBytes[i]; - return; - } catch (e) { - alert(e); - } - } - for (i = 0; i < ba.length; ++i) ba[i] = sr.getByte(); - }; - - - // --- static methods --- - - // Mix in the current time (w/milliseconds) into the pool - // NOTE: this method should be called from body click/keypress event handlers to increase entropy - sr.seedTime = function() { - sr.seedInt(new Date().getTime()); - } - - sr.getByte = function() { - if (sr.state == null) { - sr.seedTime(); - sr.state = sr.ArcFour(); // Plug in your RNG constructor here - sr.state.init(sr.pool); - sr.poolCopyOnInit = []; - for (sr.pptr = 0; sr.pptr < sr.pool.length; ++sr.pptr) - sr.poolCopyOnInit[sr.pptr] = sr.pool[sr.pptr]; - sr.pptr = 0; - } - // TODO: allow reseeding after first request - return sr.state.next(); - } - - // Mix in a 32-bit integer into the pool - sr.seedInt = function(x) { - sr.seedInt8(x); - sr.seedInt8((x >> 8)); - sr.seedInt8((x >> 16)); - sr.seedInt8((x >> 24)); - } - - // Mix in a 16-bit integer into the pool - sr.seedInt16 = function(x) { - sr.seedInt8(x); - sr.seedInt8((x >> 8)); - } - - // Mix in a 8-bit integer into the pool - sr.seedInt8 = function(x) { - sr.pool[sr.pptr++] ^= x & 255; - if (sr.pptr >= sr.poolSize) sr.pptr -= sr.poolSize; - } - - // Arcfour is a PRNG - sr.ArcFour = function() { - function Arcfour() { - this.i = 0; - this.j = 0; - this.S = new Array(); - } - - // Initialize arcfour context from key, an array of ints, each from [0..255] - function ARC4init(key) { - var i, j, t; - for (i = 0; i < 256; ++i) - this.S[i] = i; - j = 0; - for (i = 0; i < 256; ++i) { - j = (j + this.S[i] + key[i % key.length]) & 255; - t = this.S[i]; - this.S[i] = this.S[j]; - this.S[j] = t; - } - this.i = 0; - this.j = 0; - } - - function ARC4next() { - var t; - this.i = (this.i + 1) & 255; - this.j = (this.j + this.S[this.i]) & 255; - t = this.S[this.i]; - this.S[this.i] = this.S[this.j]; - this.S[this.j] = t; - return this.S[(t + this.S[this.i]) & 255]; - } - - Arcfour.prototype.init = ARC4init; - Arcfour.prototype.next = ARC4next; - - return new Arcfour(); - }; - - - // Initialize the pool with junk if needed. - if (sr.pool == null) { - sr.pool = new Array(); - sr.pptr = 0; - var t; - if (getRandomBytes && GLOBAL.Uint8Array) { - try { - // Use webcrypto if available - var ua = new Uint8Array(sr.poolSize); - getRandomBytes(ua); - for (t = 0; t < sr.poolSize; ++t) - sr.pool[sr.pptr++] = ua[t]; - } catch (e) { - alert(e); - } - } - while (sr.pptr < sr.poolSize) { // extract some randomness from securedMathRandom() - t = Math.floor(65536 * securedMathRandom()); - sr.pool[sr.pptr++] = t >>> 8; - sr.pool[sr.pptr++] = t & 255; - } - sr.pptr = Math.floor(sr.poolSize * securedMathRandom()); - sr.seedTime(); - // entropy - var entropyStr = ""; - // screen size and color depth: ~4.8 to ~5.4 bits - entropyStr += (GLOBAL.screen.height * GLOBAL.screen.width * GLOBAL.screen.colorDepth); - entropyStr += (GLOBAL.screen.availHeight * GLOBAL.screen.availWidth * GLOBAL.screen.pixelDepth); - // time zone offset: ~4 bits - var dateObj = new Date(); - var timeZoneOffset = dateObj.getTimezoneOffset(); - entropyStr += timeZoneOffset; - // user agent: ~8.3 to ~11.6 bits - entropyStr += navigator.userAgent; - // browser plugin details: ~16.2 to ~21.8 bits - var pluginsStr = ""; - for (var i = 0; i < navigator.plugins.length; i++) { - pluginsStr += navigator.plugins[i].name + " " + navigator.plugins[i].filename + " " + navigator.plugins[i].description + " " + navigator.plugins[i].version + ", "; - } - var mimeTypesStr = ""; - for (var i = 0; i < navigator.mimeTypes.length; i++) { - mimeTypesStr += navigator.mimeTypes[i].description + " " + navigator.mimeTypes[i].type + " " + navigator.mimeTypes[i].suffixes + ", "; - } - entropyStr += pluginsStr + mimeTypesStr; - // cookies and storage: 1 bit - entropyStr += navigator.cookieEnabled + typeof(sessionStorage) + typeof(localStorage); - // language: ~7 bit - entropyStr += navigator.language; - // history: ~2 bit - entropyStr += GLOBAL.history.length; - // location - entropyStr += GLOBAL.location; - - var entropyBytes = Crypto.SHA256(entropyStr, { - asBytes: true - }); - for (var i = 0; i < entropyBytes.length; i++) { - sr.seedInt8(entropyBytes[i]); - } - } - })(); - - //ripemd160.js - (function() { - - /* - CryptoJS v3.1.2 - code.google.com/p/crypto-js - (c) 2009-2013 by Jeff Mott. All rights reserved. - code.google.com/p/crypto-js/wiki/License - */ - /** @preserve - (c) 2012 by Cédric Mesnil. All rights reserved. - Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - // Constants table - var zl = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 - ]; - var zr = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 - ]; - var sl = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 - ]; - var sr = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 - ]; - - var hl = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]; - var hr = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]; - - var bytesToWords = function(bytes) { - var words = []; - for (var i = 0, b = 0; i < bytes.length; i++, b += 8) { - words[b >>> 5] |= bytes[i] << (24 - b % 32); - } - return words; - }; - - var wordsToBytes = function(words) { - var bytes = []; - for (var b = 0; b < words.length * 32; b += 8) { - bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); - } - return bytes; - }; - - var processBlock = function(H, M, offset) { - - // Swap endian - for (var i = 0; i < 16; i++) { - var offset_i = offset + i; - var M_offset_i = M[offset_i]; - - // Swap - M[offset_i] = ( - (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | - (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) - ); - } - - // Working variables - var al, bl, cl, dl, el; - var ar, br, cr, dr, er; - - ar = al = H[0]; - br = bl = H[1]; - cr = cl = H[2]; - dr = dl = H[3]; - er = el = H[4]; - // Computation - var t; - for (var i = 0; i < 80; i += 1) { - t = (al + M[offset + zl[i]]) | 0; - if (i < 16) { - t += f1(bl, cl, dl) + hl[0]; - } else if (i < 32) { - t += f2(bl, cl, dl) + hl[1]; - } else if (i < 48) { - t += f3(bl, cl, dl) + hl[2]; - } else if (i < 64) { - t += f4(bl, cl, dl) + hl[3]; - } else { // if (i<80) { - t += f5(bl, cl, dl) + hl[4]; - } - t = t | 0; - t = rotl(t, sl[i]); - t = (t + el) | 0; - al = el; - el = dl; - dl = rotl(cl, 10); - cl = bl; - bl = t; - - t = (ar + M[offset + zr[i]]) | 0; - if (i < 16) { - t += f5(br, cr, dr) + hr[0]; - } else if (i < 32) { - t += f4(br, cr, dr) + hr[1]; - } else if (i < 48) { - t += f3(br, cr, dr) + hr[2]; - } else if (i < 64) { - t += f2(br, cr, dr) + hr[3]; - } else { // if (i<80) { - t += f1(br, cr, dr) + hr[4]; - } - t = t | 0; - t = rotl(t, sr[i]); - t = (t + er) | 0; - ar = er; - er = dr; - dr = rotl(cr, 10); - cr = br; - br = t; - } - // Intermediate hash value - t = (H[1] + cl + dr) | 0; - H[1] = (H[2] + dl + er) | 0; - H[2] = (H[3] + el + ar) | 0; - H[3] = (H[4] + al + br) | 0; - H[4] = (H[0] + bl + cr) | 0; - H[0] = t; - }; - - function f1(x, y, z) { - return ((x) ^ (y) ^ (z)); - } - - function f2(x, y, z) { - return (((x) & (y)) | ((~x) & (z))); - } - - function f3(x, y, z) { - return (((x) | (~(y))) ^ (z)); - } - - function f4(x, y, z) { - return (((x) & (z)) | ((y) & (~(z)))); - } - - function f5(x, y, z) { - return ((x) ^ ((y) | (~(z)))); - } - - function rotl(x, n) { - return (x << n) | (x >>> (32 - n)); - } - - GLOBAL.ripemd160 = function ripemd160(message) { - var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]; - - var m = bytesToWords(message); - - var nBitsLeft = message.length * 8; - var nBitsTotal = message.length * 8; - - // Add padding - m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( - (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | - (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) - ); - - for (var i = 0; i < m.length; i += 16) { - processBlock(H, m, i); - } - - // Swap endian - for (var i = 0; i < 5; i++) { - // Shortcut - var H_i = H[i]; - - // Swap - H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | - (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); - } - - var digestbytes = wordsToBytes(H); - return digestbytes; - } - })(); - - //BigInteger.js - (function() { - // Upstream 'BigInteger' here: - // Original Author: http://www-cs-students.stanford.edu/~tjw/jsbn/ - // Follows 'jsbn' on Github: https://github.com/jasondavies/jsbn - // Review and Testing: https://github.com/cryptocoinjs/bigi/ - /*! - * Basic JavaScript BN library - subset useful for RSA encryption. v1.4 - * - * Copyright (c) 2005 Tom Wu - * All Rights Reserved. - * BSD License - * http://www-cs-students.stanford.edu/~tjw/jsbn/LICENSE - * - * Copyright Stephan Thomas - * Copyright pointbiz - */ - - // (public) Constructor function of Global BigInteger object - var BigInteger = GLOBAL.BigInteger = function BigInteger(a, b, c) { - if (!(this instanceof BigInteger)) - return new BigInteger(a, b, c); - - if (a != null) - if ("number" == typeof a) this.fromNumber(a, b, c); - else if (b == null && "string" != typeof a) this.fromString(a, 256); - else this.fromString(a, b); - }; - - // Bits per digit - var dbits; - - // JavaScript engine analysis - var canary = 0xdeadbeefcafe; - var j_lm = ((canary & 0xffffff) == 0xefcafe); - - // return new, unset BigInteger - function nbi() { - return new BigInteger(null); - } - - // am: Compute w_j += (x*this_i), propagate carries, - // c is initial carry, returns final carry. - // c < 3*dvalue, x < 2*dvalue, this_i < dvalue - // We need to select the fastest one that works in this environment. - - // am1: use a single mult and divide to get the high bits, - // max digit bits should be 26 because - // max internal value = 2*dvalue^2-2*dvalue (< 2^53) - function am1(i, x, w, j, c, n) { - while (--n >= 0) { - var v = x * this[i++] + w[j] + c; - c = Math.floor(v / 0x4000000); - w[j++] = v & 0x3ffffff; - } - return c; - } - // am2 avoids a big mult-and-extract completely. - // Max digit bits should be <= 30 because we do bitwise ops - // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) - function am2(i, x, w, j, c, n) { - var xl = x & 0x7fff, - xh = x >> 15; - while (--n >= 0) { - var l = this[i] & 0x7fff; - var h = this[i++] >> 15; - var m = xh * l + h * xl; - l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); - c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); - w[j++] = l & 0x3fffffff; - } - return c; - } - // Alternately, set max digit bits to 28 since some - // browsers slow down when dealing with 32-bit numbers. - function am3(i, x, w, j, c, n) { - var xl = x & 0x3fff, - xh = x >> 14; - while (--n >= 0) { - var l = this[i] & 0x3fff; - var h = this[i++] >> 14; - var m = xh * l + h * xl; - l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; - c = (l >> 28) + (m >> 14) + xh * h; - w[j++] = l & 0xfffffff; - } - return c; - } - if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) { - BigInteger.prototype.am = am2; - dbits = 30; - } else if (j_lm && (navigator.appName != "Netscape")) { - BigInteger.prototype.am = am1; - dbits = 26; - } else { // Mozilla/Netscape seems to prefer am3 - BigInteger.prototype.am = am3; - dbits = 28; - } - - BigInteger.prototype.DB = dbits; - BigInteger.prototype.DM = ((1 << dbits) - 1); - BigInteger.prototype.DV = (1 << dbits); - - var BI_FP = 52; - BigInteger.prototype.FV = Math.pow(2, BI_FP); - BigInteger.prototype.F1 = BI_FP - dbits; - BigInteger.prototype.F2 = 2 * dbits - BI_FP; - - // Digit conversions - var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; - var BI_RC = new Array(); - var rr, vv; - rr = "0".charCodeAt(0); - for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; - rr = "a".charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - rr = "A".charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - - function int2char(n) { - return BI_RM.charAt(n); - } - - function intAt(s, i) { - var c = BI_RC[s.charCodeAt(i)]; - return (c == null) ? -1 : c; - } - - - - // return bigint initialized to value - function nbv(i) { - var r = nbi(); - r.fromInt(i); - return r; - } - - - // returns bit length of the integer x - function nbits(x) { - var r = 1, - t; - if ((t = x >>> 16) != 0) { - x = t; - r += 16; - } - if ((t = x >> 8) != 0) { - x = t; - r += 8; - } - if ((t = x >> 4) != 0) { - x = t; - r += 4; - } - if ((t = x >> 2) != 0) { - x = t; - r += 2; - } - if ((t = x >> 1) != 0) { - x = t; - r += 1; - } - return r; - } - - - - - - - - // (protected) copy this to r - BigInteger.prototype.copyTo = function(r) { - for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; - r.t = this.t; - r.s = this.s; - }; - - - // (protected) set from integer value x, -DV <= x < DV - BigInteger.prototype.fromInt = function(x) { - this.t = 1; - this.s = (x < 0) ? -1 : 0; - if (x > 0) this[0] = x; - else if (x < -1) this[0] = x + this.DV; - else this.t = 0; - }; - - // (protected) set from string and radix - BigInteger.prototype.fromString = function(s, b) { - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 256) k = 8; // byte array - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else { - this.fromRadix(s, b); - return; - } - this.t = 0; - this.s = 0; - var i = s.length, - mi = false, - sh = 0; - while (--i >= 0) { - var x = (k == 8) ? s[i] & 0xff : intAt(s, i); - if (x < 0) { - if (s.charAt(i) == "-") mi = true; - continue; - } - mi = false; - if (sh == 0) - this[this.t++] = x; - else if (sh + k > this.DB) { - this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; - this[this.t++] = (x >> (this.DB - sh)); - } else - this[this.t - 1] |= x << sh; - sh += k; - if (sh >= this.DB) sh -= this.DB; - } - if (k == 8 && (s[0] & 0x80) != 0) { - this.s = -1; - if (sh > 0) this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; - } - this.clamp(); - if (mi) BigInteger.ZERO.subTo(this, this); - }; - - - // (protected) clamp off excess high words - BigInteger.prototype.clamp = function() { - var c = this.s & this.DM; - while (this.t > 0 && this[this.t - 1] == c) --this.t; - }; - - // (protected) r = this << n*DB - BigInteger.prototype.dlShiftTo = function(n, r) { - var i; - for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; - for (i = n - 1; i >= 0; --i) r[i] = 0; - r.t = this.t + n; - r.s = this.s; - }; - - // (protected) r = this >> n*DB - BigInteger.prototype.drShiftTo = function(n, r) { - for (var i = n; i < this.t; ++i) r[i - n] = this[i]; - r.t = Math.max(this.t - n, 0); - r.s = this.s; - }; - - - // (protected) r = this << n - BigInteger.prototype.lShiftTo = function(n, r) { - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << cbs) - 1; - var ds = Math.floor(n / this.DB), - c = (this.s << bs) & this.DM, - i; - for (i = this.t - 1; i >= 0; --i) { - r[i + ds + 1] = (this[i] >> cbs) | c; - c = (this[i] & bm) << bs; - } - for (i = ds - 1; i >= 0; --i) r[i] = 0; - r[ds] = c; - r.t = this.t + ds + 1; - r.s = this.s; - r.clamp(); - }; - - - // (protected) r = this >> n - BigInteger.prototype.rShiftTo = function(n, r) { - r.s = this.s; - var ds = Math.floor(n / this.DB); - if (ds >= this.t) { - r.t = 0; - return; - } - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << bs) - 1; - r[0] = this[ds] >> bs; - for (var i = ds + 1; i < this.t; ++i) { - r[i - ds - 1] |= (this[i] & bm) << cbs; - r[i - ds] = this[i] >> bs; - } - if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; - r.t = this.t - ds; - r.clamp(); - }; - - - // (protected) r = this - a - BigInteger.prototype.subTo = function(a, r) { - var i = 0, - c = 0, - m = Math.min(a.t, this.t); - while (i < m) { - c += this[i] - a[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - if (a.t < this.t) { - c -= a.s; - while (i < this.t) { - c += this[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c -= a[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c -= a.s; - } - r.s = (c < 0) ? -1 : 0; - if (c < -1) r[i++] = this.DV + c; - else if (c > 0) r[i++] = c; - r.t = i; - r.clamp(); - }; - - - // (protected) r = this * a, r != this,a (HAC 14.12) - // "this" should be the larger one if appropriate. - BigInteger.prototype.multiplyTo = function(a, r) { - var x = this.abs(), - y = a.abs(); - var i = x.t; - r.t = i + y.t; - while (--i >= 0) r[i] = 0; - for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); - r.s = 0; - r.clamp(); - if (this.s != a.s) BigInteger.ZERO.subTo(r, r); - }; - - - // (protected) r = this^2, r != this (HAC 14.16) - BigInteger.prototype.squareTo = function(r) { - var x = this.abs(); - var i = r.t = 2 * x.t; - while (--i >= 0) r[i] = 0; - for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x[i], r, 2 * i, 0, 1); - if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { - r[i + x.t] -= x.DV; - r[i + x.t + 1] = 1; - } - } - if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); - r.s = 0; - r.clamp(); - }; - - - - // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) - // r != q, this != m. q or r may be null. - BigInteger.prototype.divRemTo = function(m, q, r) { - var pm = m.abs(); - if (pm.t <= 0) return; - var pt = this.abs(); - if (pt.t < pm.t) { - if (q != null) q.fromInt(0); - if (r != null) this.copyTo(r); - return; - } - if (r == null) r = nbi(); - var y = nbi(), - ts = this.s, - ms = m.s; - var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus - if (nsh > 0) { - pm.lShiftTo(nsh, y); - pt.lShiftTo(nsh, r); - } else { - pm.copyTo(y); - pt.copyTo(r); - } - var ys = y.t; - var y0 = y[ys - 1]; - if (y0 == 0) return; - var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); - var d1 = this.FV / yt, - d2 = (1 << this.F1) / yt, - e = 1 << this.F2; - var i = r.t, - j = i - ys, - t = (q == null) ? nbi() : q; - y.dlShiftTo(j, t); - if (r.compareTo(t) >= 0) { - r[r.t++] = 1; - r.subTo(t, r); - } - BigInteger.ONE.dlShiftTo(ys, t); - t.subTo(y, y); // "negative" y so we can replace sub with am later - while (y.t < ys) y[y.t++] = 0; - while (--j >= 0) { - // Estimate quotient digit - var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); - if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out - y.dlShiftTo(j, t); - r.subTo(t, r); - while (r[i] < --qd) r.subTo(t, r); - } - } - if (q != null) { - r.drShiftTo(ys, q); - if (ts != ms) BigInteger.ZERO.subTo(q, q); - } - r.t = ys; - r.clamp(); - if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder - if (ts < 0) BigInteger.ZERO.subTo(r, r); - }; - - - // (protected) return "-1/this % 2^DB"; useful for Mont. reduction - // justification: - // xy == 1 (mod m) - // xy = 1+km - // xy(2-xy) = (1+km)(1-km) - // x[y(2-xy)] = 1-k^2m^2 - // x[y(2-xy)] == 1 (mod m^2) - // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 - // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. - // JS multiply "overflows" differently from C/C++, so care is needed here. - BigInteger.prototype.invDigit = function() { - if (this.t < 1) return 0; - var x = this[0]; - if ((x & 1) == 0) return 0; - var y = x & 3; // y == 1/x mod 2^2 - y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 - y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 - y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly; - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return (y > 0) ? this.DV - y : -y; - }; - - - // (protected) true iff this is even - BigInteger.prototype.isEven = function() { - return ((this.t > 0) ? (this[0] & 1) : this.s) == 0; - }; - - - // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) - BigInteger.prototype.exp = function(e, z) { - if (e > 0xffffffff || e < 1) return BigInteger.ONE; - var r = nbi(), - r2 = nbi(), - g = z.convert(this), - i = nbits(e) - 1; - g.copyTo(r); - while (--i >= 0) { - z.sqrTo(r, r2); - if ((e & (1 << i)) > 0) z.mulTo(r2, g, r); - else { - var t = r; - r = r2; - r2 = t; - } - } - return z.revert(r); - }; - - - // (public) return string representation in given radix - BigInteger.prototype.toString = function(b) { - if (this.s < 0) return "-" + this.negate().toString(b); - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else return this.toRadix(b); - var km = (1 << k) - 1, - d, m = false, - r = "", - i = this.t; - var p = this.DB - (i * this.DB) % k; - if (i-- > 0) { - if (p < this.DB && (d = this[i] >> p) > 0) { - m = true; - r = int2char(d); - } - while (i >= 0) { - if (p < k) { - d = (this[i] & ((1 << p) - 1)) << (k - p); - d |= this[--i] >> (p += this.DB - k); - } else { - d = (this[i] >> (p -= k)) & km; - if (p <= 0) { - p += this.DB; - --i; - } - } - if (d > 0) m = true; - if (m) r += int2char(d); - } - } - return m ? r : "0"; - }; - - - // (public) -this - BigInteger.prototype.negate = function() { - var r = nbi(); - BigInteger.ZERO.subTo(this, r); - return r; - }; - - // (public) |this| - BigInteger.prototype.abs = function() { - return (this.s < 0) ? this.negate() : this; - }; - - // (public) return + if this > a, - if this < a, 0 if equal - BigInteger.prototype.compareTo = function(a) { - var r = this.s - a.s; - if (r != 0) return r; - var i = this.t; - r = i - a.t; - if (r != 0) return (this.s < 0) ? -r : r; - while (--i >= 0) - if ((r = this[i] - a[i]) != 0) return r; - return 0; - } - - // (public) return the number of bits in "this" - BigInteger.prototype.bitLength = function() { - if (this.t <= 0) return 0; - return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); - }; - - // (public) this mod a - BigInteger.prototype.mod = function(a) { - var r = nbi(); - this.abs().divRemTo(a, null, r); - if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); - return r; - } - - // (public) this^e % m, 0 <= e < 2^32 - BigInteger.prototype.modPowInt = function(e, m) { - var z; - if (e < 256 || m.isEven()) z = new Classic(m); - else z = new Montgomery(m); - return this.exp(e, z); - }; - - // "constants" - BigInteger.ZERO = nbv(0); - BigInteger.ONE = nbv(1); - - - - - - - - // Copyright (c) 2005-2009 Tom Wu - // All Rights Reserved. - // See "LICENSE" for details. - // Extended JavaScript BN functions, required for RSA private ops. - // Version 1.1: new BigInteger("0", 10) returns "proper" zero - // Version 1.2: square() API, isProbablePrime fix - - - // return index of lowest 1-bit in x, x < 2^31 - function lbit(x) { - if (x == 0) return -1; - var r = 0; - if ((x & 0xffff) == 0) { - x >>= 16; - r += 16; - } - if ((x & 0xff) == 0) { - x >>= 8; - r += 8; - } - if ((x & 0xf) == 0) { - x >>= 4; - r += 4; - } - if ((x & 3) == 0) { - x >>= 2; - r += 2; - } - if ((x & 1) == 0) ++r; - return r; - } - - // return number of 1 bits in x - function cbit(x) { - var r = 0; - while (x != 0) { - x &= x - 1; - ++r; - } - return r; - } - - var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, - 89, - 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, - 193, - 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, - 311, - 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, - 433, - 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, - 569, - 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, - 683, - 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, - 827, - 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, - 971, - 977, 983, 991, 997 - ]; - var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; - - - - // (protected) return x s.t. r^x < DV - BigInteger.prototype.chunkSize = function(r) { - return Math.floor(Math.LN2 * this.DB / Math.log(r)); - }; - - // (protected) convert to radix string - BigInteger.prototype.toRadix = function(b) { - if (b == null) b = 10; - if (this.signum() == 0 || b < 2 || b > 36) return "0"; - var cs = this.chunkSize(b); - var a = Math.pow(b, cs); - var d = nbv(a), - y = nbi(), - z = nbi(), - r = ""; - this.divRemTo(d, y, z); - while (y.signum() > 0) { - r = (a + z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d, y, z); - } - return z.intValue().toString(b) + r; - }; - - // (protected) convert from radix string - BigInteger.prototype.fromRadix = function(s, b) { - this.fromInt(0); - if (b == null) b = 10; - var cs = this.chunkSize(b); - var d = Math.pow(b, cs), - mi = false, - j = 0, - w = 0; - for (var i = 0; i < s.length; ++i) { - var x = intAt(s, i); - if (x < 0) { - if (s.charAt(i) == "-" && this.signum() == 0) mi = true; - continue; - } - w = b * w + x; - if (++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w, 0); - j = 0; - w = 0; - } - } - if (j > 0) { - this.dMultiply(Math.pow(b, j)); - this.dAddOffset(w, 0); - } - if (mi) BigInteger.ZERO.subTo(this, this); - }; - - // (protected) alternate constructor - BigInteger.prototype.fromNumber = function(a, b, c) { - if ("number" == typeof b) { - // new BigInteger(int,int,RNG) - if (a < 2) this.fromInt(1); - else { - this.fromNumber(a, c); - if (!this.testBit(a - 1)) // force MSB set - this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); - if (this.isEven()) this.dAddOffset(1, 0); // force odd - while (!this.isProbablePrime(b)) { - this.dAddOffset(2, 0); - if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); - } - } - } else { - // new BigInteger(int,RNG) - var x = new Array(), - t = a & 7; - x.length = (a >> 3) + 1; - b.nextBytes(x); - if (t > 0) x[0] &= ((1 << t) - 1); - else x[0] = 0; - this.fromString(x, 256); - } - }; - - // (protected) r = this op a (bitwise) - BigInteger.prototype.bitwiseTo = function(a, op, r) { - var i, f, m = Math.min(a.t, this.t); - for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); - if (a.t < this.t) { - f = a.s & this.DM; - for (i = m; i < this.t; ++i) r[i] = op(this[i], f); - r.t = this.t; - } else { - f = this.s & this.DM; - for (i = m; i < a.t; ++i) r[i] = op(f, a[i]); - r.t = a.t; - } - r.s = op(this.s, a.s); - r.clamp(); - }; - - // (protected) this op (1<>= this.DB; - } - if (a.t < this.t) { - c += a.s; - while (i < this.t) { - c += this[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c += a[i]; - r[i++] = c & this.DM; - c >>= this.DB; - } - c += a.s; - } - r.s = (c < 0) ? -1 : 0; - if (c > 0) r[i++] = c; - else if (c < -1) r[i++] = this.DV + c; - r.t = i; - r.clamp(); - }; - - // (protected) this *= n, this >= 0, 1 < n < DV - BigInteger.prototype.dMultiply = function(n) { - this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); - ++this.t; - this.clamp(); - }; - - // (protected) this += n << w words, this >= 0 - BigInteger.prototype.dAddOffset = function(n, w) { - if (n == 0) return; - while (this.t <= w) this[this.t++] = 0; - this[w] += n; - while (this[w] >= this.DV) { - this[w] -= this.DV; - if (++w >= this.t) this[this.t++] = 0; - ++this[w]; - } - }; - - // (protected) r = lower n words of "this * a", a.t <= n - // "this" should be the larger one if appropriate. - BigInteger.prototype.multiplyLowerTo = function(a, n, r) { - var i = Math.min(this.t + a.t, n); - r.s = 0; // assumes a,this >= 0 - r.t = i; - while (i > 0) r[--i] = 0; - var j; - for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); - for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i); - r.clamp(); - }; - - - // (protected) r = "this * a" without lower n words, n > 0 - // "this" should be the larger one if appropriate. - BigInteger.prototype.multiplyUpperTo = function(a, n, r) { - --n; - var i = r.t = this.t + a.t - n; - r.s = 0; // assumes a,this >= 0 - while (--i >= 0) r[i] = 0; - for (i = Math.max(n - this.t, 0); i < a.t; ++i) - r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); - r.clamp(); - r.drShiftTo(1, r); - }; - - // (protected) this % n, n < 2^26 - BigInteger.prototype.modInt = function(n) { - if (n <= 0) return 0; - var d = this.DV % n, - r = (this.s < 0) ? n - 1 : 0; - if (this.t > 0) - if (d == 0) r = this[0] % n; - else - for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n; - return r; - }; - - - // (protected) true if probably prime (HAC 4.24, Miller-Rabin) - BigInteger.prototype.millerRabin = function(t) { - var n1 = this.subtract(BigInteger.ONE); - var k = n1.getLowestSetBit(); - if (k <= 0) return false; - var r = n1.shiftRight(k); - t = (t + 1) >> 1; - if (t > lowprimes.length) t = lowprimes.length; - var a = nbi(); - for (var i = 0; i < t; ++i) { - //Pick bases at random, instead of starting at 2 - a.fromInt(lowprimes[Math.floor(securedMathRandom() * lowprimes.length)]); - var y = a.modPow(r, this); - if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while (j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2, this); - if (y.compareTo(BigInteger.ONE) == 0) return false; - } - if (y.compareTo(n1) != 0) return false; - } - } - return true; - }; - - - - // (public) - BigInteger.prototype.clone = function() { - var r = nbi(); - this.copyTo(r); - return r; - }; - - // (public) return value as integer - BigInteger.prototype.intValue = function() { - if (this.s < 0) { - if (this.t == 1) return this[0] - this.DV; - else if (this.t == 0) return -1; - } else if (this.t == 1) return this[0]; - else if (this.t == 0) return 0; - // assumes 16 < DB < 32 - return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; - }; - - - // (public) return value as byte - BigInteger.prototype.byteValue = function() { - return (this.t == 0) ? this.s : (this[0] << 24) >> 24; - }; - - // (public) return value as short (assumes DB>=16) - BigInteger.prototype.shortValue = function() { - return (this.t == 0) ? this.s : (this[0] << 16) >> 16; - }; - - // (public) 0 if this == 0, 1 if this > 0 - BigInteger.prototype.signum = function() { - if (this.s < 0) return -1; - else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; - else return 1; - }; - - - // (public) convert to bigendian byte array - BigInteger.prototype.toByteArray = function() { - var i = this.t, - r = new Array(); - r[0] = this.s; - var p = this.DB - (i * this.DB) % 8, - d, k = 0; - if (i-- > 0) { - if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) - r[k++] = d | (this.s << (this.DB - p)); - while (i >= 0) { - if (p < 8) { - d = (this[i] & ((1 << p) - 1)) << (8 - p); - d |= this[--i] >> (p += this.DB - 8); - } else { - d = (this[i] >> (p -= 8)) & 0xff; - if (p <= 0) { - p += this.DB; - --i; - } - } - if ((d & 0x80) != 0) d |= -256; - if (k == 0 && (this.s & 0x80) != (d & 0x80)) ++k; - if (k > 0 || d != this.s) r[k++] = d; - } - } - return r; - }; - - BigInteger.prototype.equals = function(a) { - return (this.compareTo(a) == 0); - }; - BigInteger.prototype.min = function(a) { - return (this.compareTo(a) < 0) ? this : a; - }; - BigInteger.prototype.max = function(a) { - return (this.compareTo(a) > 0) ? this : a; - }; - - // (public) this & a - function op_and(x, y) { - return x & y; - } - BigInteger.prototype.and = function(a) { - var r = nbi(); - this.bitwiseTo(a, op_and, r); - return r; - }; - - // (public) this | a - function op_or(x, y) { - return x | y; - } - BigInteger.prototype.or = function(a) { - var r = nbi(); - this.bitwiseTo(a, op_or, r); - return r; - }; - - // (public) this ^ a - function op_xor(x, y) { - return x ^ y; - } - BigInteger.prototype.xor = function(a) { - var r = nbi(); - this.bitwiseTo(a, op_xor, r); - return r; - }; - - // (public) this & ~a - function op_andnot(x, y) { - return x & ~y; - } - BigInteger.prototype.andNot = function(a) { - var r = nbi(); - this.bitwiseTo(a, op_andnot, r); - return r; - }; - - // (public) ~this - BigInteger.prototype.not = function() { - var r = nbi(); - for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; - r.t = this.t; - r.s = ~this.s; - return r; - }; - - // (public) this << n - BigInteger.prototype.shiftLeft = function(n) { - var r = nbi(); - if (n < 0) this.rShiftTo(-n, r); - else this.lShiftTo(n, r); - return r; - }; - - // (public) this >> n - BigInteger.prototype.shiftRight = function(n) { - var r = nbi(); - if (n < 0) this.lShiftTo(-n, r); - else this.rShiftTo(n, r); - return r; - }; - - // (public) returns index of lowest 1-bit (or -1 if none) - BigInteger.prototype.getLowestSetBit = function() { - for (var i = 0; i < this.t; ++i) - if (this[i] != 0) return i * this.DB + lbit(this[i]); - if (this.s < 0) return this.t * this.DB; - return -1; - }; - - // (public) return number of set bits - BigInteger.prototype.bitCount = function() { - var r = 0, - x = this.s & this.DM; - for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); - return r; - }; - - // (public) true iff nth bit is set - BigInteger.prototype.testBit = function(n) { - var j = Math.floor(n / this.DB); - if (j >= this.t) return (this.s != 0); - return ((this[j] & (1 << (n % this.DB))) != 0); - }; - - // (public) this | (1< 1) { - var g2 = nbi(); - z.sqrTo(g[1], g2); - while (n <= km) { - g[n] = nbi(); - z.mulTo(g2, g[n - 2], g[n]); - n += 2; - } - } - - var j = e.t - 1, - w, is1 = true, - r2 = nbi(), - t; - i = nbits(e[j]) - 1; - while (j >= 0) { - if (i >= k1) w = (e[j] >> (i - k1)) & km; - else { - w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); - if (j > 0) w |= e[j - 1] >> (this.DB + i - k1); - } - - n = k; - while ((w & 1) == 0) { - w >>= 1; - --n; - } - if ((i -= n) < 0) { - i += this.DB; - --j; - } - if (is1) { // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r); - is1 = false; - } else { - while (n > 1) { - z.sqrTo(r, r2); - z.sqrTo(r2, r); - n -= 2; - } - if (n > 0) z.sqrTo(r, r2); - else { - t = r; - r = r2; - r2 = t; - } - z.mulTo(r2, g[w], r); - } - - while (j >= 0 && (e[j] & (1 << i)) == 0) { - z.sqrTo(r, r2); - t = r; - r = r2; - r2 = t; - if (--i < 0) { - i = this.DB - 1; - --j; - } - } - } - return z.revert(r); - }; - - // (public) 1/this % m (HAC 14.61) - BigInteger.prototype.modInverse = function(m) { - var ac = m.isEven(); - if (this.signum() === 0) throw new Error('division by zero'); - if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; - var u = m.clone(), - v = this.clone(); - var a = nbv(1), - b = nbv(0), - c = nbv(0), - d = nbv(1); - while (u.signum() != 0) { - while (u.isEven()) { - u.rShiftTo(1, u); - if (ac) { - if (!a.isEven() || !b.isEven()) { - a.addTo(this, a); - b.subTo(m, b); - } - a.rShiftTo(1, a); - } else if (!b.isEven()) b.subTo(m, b); - b.rShiftTo(1, b); - } - while (v.isEven()) { - v.rShiftTo(1, v); - if (ac) { - if (!c.isEven() || !d.isEven()) { - c.addTo(this, c); - d.subTo(m, d); - } - c.rShiftTo(1, c); - } else if (!d.isEven()) d.subTo(m, d); - d.rShiftTo(1, d); - } - if (u.compareTo(v) >= 0) { - u.subTo(v, u); - if (ac) a.subTo(c, a); - b.subTo(d, b); - } else { - v.subTo(u, v); - if (ac) c.subTo(a, c); - d.subTo(b, d); - } - } - if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; - while (d.compareTo(m) >= 0) d.subTo(m, d); - while (d.signum() < 0) d.addTo(m, d); - return d; - }; - - - // (public) this^e - BigInteger.prototype.pow = function(e) { - return this.exp(e, new NullExp()); - }; - - // (public) gcd(this,a) (HAC 14.54) - BigInteger.prototype.gcd = function(a) { - var x = (this.s < 0) ? this.negate() : this.clone(); - var y = (a.s < 0) ? a.negate() : a.clone(); - if (x.compareTo(y) < 0) { - var t = x; - x = y; - y = t; - } - var i = x.getLowestSetBit(), - g = y.getLowestSetBit(); - if (g < 0) return x; - if (i < g) g = i; - if (g > 0) { - x.rShiftTo(g, x); - y.rShiftTo(g, y); - } - while (x.signum() > 0) { - if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); - if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); - if (x.compareTo(y) >= 0) { - x.subTo(y, x); - x.rShiftTo(1, x); - } else { - y.subTo(x, y); - y.rShiftTo(1, y); - } - } - if (g > 0) y.lShiftTo(g, y); - return y; - }; - - // (public) test primality with certainty >= 1-.5^t - BigInteger.prototype.isProbablePrime = function(t) { - var i, x = this.abs(); - if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { - for (i = 0; i < lowprimes.length; ++i) - if (x[0] == lowprimes[i]) return true; - return false; - } - if (x.isEven()) return false; - i = 1; - while (i < lowprimes.length) { - var m = lowprimes[i], - j = i + 1; - while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; - m = x.modInt(m); - while (i < j) - if (m % lowprimes[i++] == 0) return false; - } - return x.millerRabin(t); - }; - - - // JSBN-specific extension - - // (public) this^2 - BigInteger.prototype.square = function() { - var r = nbi(); - this.squareTo(r); - return r; - }; - - - // NOTE: BigInteger interfaces not implemented in jsbn: - // BigInteger(int signum, byte[] magnitude) - // double doubleValue() - // float floatValue() - // int hashCode() - // long longValue() - // static BigInteger valueOf(long val) - - - - // Copyright Stephan Thomas (start) --- // - // https://raw.github.com/bitcoinjs/bitcoinjs-lib/07f9d55ccb6abd962efb6befdd37671f85ea4ff9/src/util.js - // BigInteger monkey patching - BigInteger.valueOf = nbv; - - /** - * Returns a byte array representation of the big integer. - * - * This returns the absolute of the contained value in big endian - * form. A value of zero results in an empty array. - */ - BigInteger.prototype.toByteArrayUnsigned = function() { - var ba = this.abs().toByteArray(); - if (ba.length) { - if (ba[0] == 0) { - ba = ba.slice(1); - } - return ba.map(function(v) { - return (v < 0) ? v + 256 : v; - }); - } else { - // Empty array, nothing to do - return ba; - } - }; - - /** - * Turns a byte array into a big integer. - * - * This function will interpret a byte array as a big integer in big - * endian notation and ignore leading zeros. - */ - BigInteger.fromByteArrayUnsigned = function(ba) { - if (!ba.length) { - return ba.valueOf(0); - } else if (ba[0] & 0x80) { - // Prepend a zero so the BigInteger class doesn't mistake this - // for a negative integer. - return new BigInteger([0].concat(ba)); - } else { - return new BigInteger(ba); - } - }; - - /** - * Converts big integer to signed byte representation. - * - * The format for this value uses a the most significant bit as a sign - * bit. If the most significant bit is already occupied by the - * absolute value, an extra byte is prepended and the sign bit is set - * there. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0x81 - * 127 => 0x7f - * -127 => 0xff - * 128 => 0x0080 - * -128 => 0x8080 - * 255 => 0x00ff - * -255 => 0x80ff - * 16300 => 0x3fac - * -16300 => 0xbfac - * 62300 => 0x00f35c - * -62300 => 0x80f35c - */ - BigInteger.prototype.toByteArraySigned = function() { - var val = this.abs().toByteArrayUnsigned(); - var neg = this.compareTo(BigInteger.ZERO) < 0; - - if (neg) { - if (val[0] & 0x80) { - val.unshift(0x80); - } else { - val[0] |= 0x80; - } - } else { - if (val[0] & 0x80) { - val.unshift(0x00); - } - } - - return val; - }; - - /** - * Parse a signed big integer byte representation. - * - * For details on the format please see BigInteger.toByteArraySigned. - */ - BigInteger.fromByteArraySigned = function(ba) { - // Check for negative value - if (ba[0] & 0x80) { - // Remove sign bit - ba[0] &= 0x7f; - - return BigInteger.fromByteArrayUnsigned(ba).negate(); - } else { - return BigInteger.fromByteArrayUnsigned(ba); - } - }; - // Copyright Stephan Thomas (end) --- // - - - - - // ****** REDUCTION ******* // - - // Modular reduction using "classic" algorithm - var Classic = GLOBAL.Classic = function Classic(m) { - this.m = m; - } - Classic.prototype.convert = function(x) { - if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; - }; - Classic.prototype.revert = function(x) { - return x; - }; - Classic.prototype.reduce = function(x) { - x.divRemTo(this.m, null, x); - }; - Classic.prototype.mulTo = function(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - }; - Classic.prototype.sqrTo = function(x, r) { - x.squareTo(r); - this.reduce(r); - }; - - - - - - // Montgomery reduction - var Montgomery = GLOBAL.Montgomery = function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp & 0x7fff; - this.mph = this.mp >> 15; - this.um = (1 << (m.DB - 15)) - 1; - this.mt2 = 2 * m.t; - } - // xR mod m - Montgomery.prototype.convert = function(x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t, r); - r.divRemTo(this.m, null, r); - if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); - return r; - } - // x/R mod m - Montgomery.prototype.revert = function(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - }; - // x = x/R mod m (HAC 14.32) - Montgomery.prototype.reduce = function(x) { - while (x.t <= this.mt2) // pad x so am has enough room later - x[x.t++] = 0; - for (var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i] & 0x7fff; - var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; - // use am to combine the multiply-shift-add into one call - j = i + this.m.t; - x[j] += this.m.am(0, u0, x, i, 0, this.m.t); - // propagate carry - while (x[j] >= x.DV) { - x[j] -= x.DV; - x[++j]++; - } - } - x.clamp(); - x.drShiftTo(this.m.t, x); - if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - }; - // r = "xy/R mod m"; x,y != r - Montgomery.prototype.mulTo = function(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - }; - // r = "x^2/R mod m"; x != r - Montgomery.prototype.sqrTo = function(x, r) { - x.squareTo(r); - this.reduce(r); - }; - - - - - - // A "null" reducer - var NullExp = GLOBAL.NullExp = function NullExp() {} - NullExp.prototype.convert = function(x) { - return x; - }; - NullExp.prototype.revert = function(x) { - return x; - }; - NullExp.prototype.mulTo = function(x, y, r) { - x.multiplyTo(y, r); - }; - NullExp.prototype.sqrTo = function(x, r) { - x.squareTo(r); - }; - - - - - - // Barrett modular reduction - var Barrett = GLOBAL.Barrett = function Barrett(m) { - // setup Barrett - this.r2 = nbi(); - this.q3 = nbi(); - BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); - this.mu = this.r2.divide(m); - this.m = m; - } - Barrett.prototype.convert = function(x) { - if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); - else if (x.compareTo(this.m) < 0) return x; - else { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - }; - Barrett.prototype.revert = function(x) { - return x; - }; - // x = x mod m (HAC 14.42) - Barrett.prototype.reduce = function(x) { - x.drShiftTo(this.m.t - 1, this.r2); - if (x.t > this.m.t + 1) { - x.t = this.m.t + 1; - x.clamp(); - } - this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); - this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); - while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); - x.subTo(this.r2, x); - while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - }; - // r = x*y mod m; x,y != r - Barrett.prototype.mulTo = function(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - }; - // r = x^2 mod m; x != r - Barrett.prototype.sqrTo = function(x, r) { - x.squareTo(r); - this.reduce(r); - }; - - // BigInteger interfaces not implemented in jsbn: - - // BigInteger(int signum, byte[] magnitude) - // double doubleValue() - // float floatValue() - // int hashCode() - // long longValue() - // static BigInteger valueOf(long val) - })(); - - //ellipticcurve.js - (function() { - /*! - * Basic Javascript Elliptic Curve implementation - * Ported loosely from BouncyCastle's Java EC code - * Only Fp curves implemented for now - * - * Copyright Tom Wu, bitaddress.org BSD License. - * http://www-cs-students.stanford.edu/~tjw/jsbn/LICENSE - */ - // Constructor function of Global EllipticCurve object - var ec = GLOBAL.EllipticCurve = function() {}; - - // ---------------- - // ECFieldElementFp constructor - // q instanceof BigInteger - // x instanceof BigInteger - ec.FieldElementFp = function(q, x) { - this.x = x; - // TODO if(x.compareTo(q) >= 0) error - this.q = q; - }; - - ec.FieldElementFp.prototype.equals = function(other) { - if (other == this) return true; - return (this.q.equals(other.q) && this.x.equals(other.x)); - }; - - ec.FieldElementFp.prototype.toBigInteger = function() { - return this.x; - }; - - ec.FieldElementFp.prototype.negate = function() { - return new ec.FieldElementFp(this.q, this.x.negate().mod(this.q)); - }; - - ec.FieldElementFp.prototype.add = function(b) { - return new ec.FieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); - }; - - ec.FieldElementFp.prototype.subtract = function(b) { - return new ec.FieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); - }; - - ec.FieldElementFp.prototype.multiply = function(b) { - return new ec.FieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); - }; - - ec.FieldElementFp.prototype.square = function() { - return new ec.FieldElementFp(this.q, this.x.square().mod(this.q)); - }; - - ec.FieldElementFp.prototype.divide = function(b) { - return new ec.FieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod( - this.q)); - }; - - ec.FieldElementFp.prototype.getByteLength = function() { - return Math.floor((this.toBigInteger().bitLength() + 7) / 8); - }; - - // D.1.4 91 - /** - * return a sqrt root - the routine verifies that the calculation - * returns the right value - if none exists it returns null. - * - * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) - * Ported to JavaScript by bitaddress.org - */ - ec.FieldElementFp.prototype.sqrt = function() { - if (!this.q.testBit(0)) throw new Error("even value of q"); - - // p mod 4 == 3 - if (this.q.testBit(1)) { - // z = g^(u+1) + p, p = 4u + 3 - var z = new ec.FieldElementFp(this.q, this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE), - this.q)); - return z.square().equals(this) ? z : null; - } - - // p mod 4 == 1 - var qMinusOne = this.q.subtract(BigInteger.ONE); - var legendreExponent = qMinusOne.shiftRight(1); - if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) return null; - var u = qMinusOne.shiftRight(2); - var k = u.shiftLeft(1).add(BigInteger.ONE); - var Q = this.x; - var fourQ = Q.shiftLeft(2).mod(this.q); - var U, V; - - do { - var rand = new SecureRandom(); - var P; - do { - P = new BigInteger(this.q.bitLength(), rand); - } - while (P.compareTo(this.q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, - this.q).equals(qMinusOne))); - - var result = ec.FieldElementFp.fastLucasSequence(this.q, P, Q, k); - - U = result[0]; - V = result[1]; - if (V.multiply(V).mod(this.q).equals(fourQ)) { - // Integer division by 2, mod q - if (V.testBit(0)) { - V = V.add(this.q); - } - V = V.shiftRight(1); - return new ec.FieldElementFp(this.q, V); - } - } - while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); - - return null; - }; - /*! - * Crypto-JS 2.5.4 BlockModes.js - * contribution from Simon Greatrix - */ - - (function(C) { - - // Create pad namespace - var C_pad = C.pad = {}; - - // Calculate the number of padding bytes required. - function _requiredPadding(cipher, message) { - var blockSizeInBytes = cipher._blocksize * 4; - var reqd = blockSizeInBytes - message.length % blockSizeInBytes; - return reqd; - } - - // Remove padding when the final byte gives the number of padding bytes. - var _unpadLength = function(cipher, message, alg, padding) { - var pad = message.pop(); - if (pad == 0) { - throw new Error("Invalid zero-length padding specified for " + alg + - ". Wrong cipher specification or key used?"); - } - var maxPad = cipher._blocksize * 4; - if (pad > maxPad) { - throw new Error("Invalid padding length of " + pad + - " specified for " + alg + - ". Wrong cipher specification or key used?"); - } - for (var i = 1; i < pad; i++) { - var b = message.pop(); - if (padding != undefined && padding != b) { - throw new Error("Invalid padding byte of 0x" + b.toString(16) + - " specified for " + alg + - ". Wrong cipher specification or key used?"); - } - } - }; - - // No-operation padding, used for stream ciphers - C_pad.NoPadding = { - pad: function(cipher, message) {}, - unpad: function(cipher, message) {} - }; - - // Zero Padding. - // - // If the message is not an exact number of blocks, the final block is - // completed with 0x00 bytes. There is no unpadding. - C_pad.ZeroPadding = { - pad: function(cipher, message) { - var blockSizeInBytes = cipher._blocksize * 4; - var reqd = message.length % blockSizeInBytes; - if (reqd != 0) { - for (reqd = blockSizeInBytes - reqd; reqd > 0; reqd--) { - message.push(0x00); - } - } - }, - - unpad: function(cipher, message) { - while (message[message.length - 1] == 0) { - message.pop(); - } - } - }; - - // ISO/IEC 7816-4 padding. - // - // Pads the plain text with an 0x80 byte followed by as many 0x00 - // bytes are required to complete the block. - C_pad.iso7816 = { - pad: function(cipher, message) { - var reqd = _requiredPadding(cipher, message); - message.push(0x80); - for (; reqd > 1; reqd--) { - message.push(0x00); - } - }, - - unpad: function(cipher, message) { - var padLength; - for (padLength = cipher._blocksize * 4; padLength > 0; padLength--) { - var b = message.pop(); - if (b == 0x80) return; - if (b != 0x00) { - throw new Error("ISO-7816 padding byte must be 0, not 0x" + b.toString(16) + - ". Wrong cipher specification or key used?"); - } - } - throw new Error( - "ISO-7816 padded beyond cipher block size. Wrong cipher specification or key used?" - ); - } - }; - - // ANSI X.923 padding - // - // The final block is padded with zeros except for the last byte of the - // last block which contains the number of padding bytes. - C_pad.ansix923 = { - pad: function(cipher, message) { - var reqd = _requiredPadding(cipher, message); - for (var i = 1; i < reqd; i++) { - message.push(0x00); - } - message.push(reqd); - }, - - unpad: function(cipher, message) { - _unpadLength(cipher, message, "ANSI X.923", 0); - } - }; - - // ISO 10126 - // - // The final block is padded with random bytes except for the last - // byte of the last block which contains the number of padding bytes. - C_pad.iso10126 = { - pad: function(cipher, message) { - var reqd = _requiredPadding(cipher, message); - for (var i = 1; i < reqd; i++) { - message.push(Math.floor(securedMathRandom() * 256)); - } - message.push(reqd); - }, - - unpad: function(cipher, message) { - _unpadLength(cipher, message, "ISO 10126", undefined); - } - }; - - // PKCS7 padding - // - // PKCS7 is described in RFC 5652. Padding is in whole bytes. The - // value of each added byte is the number of bytes that are added, - // i.e. N bytes, each of value N are added. - C_pad.pkcs7 = { - pad: function(cipher, message) { - var reqd = _requiredPadding(cipher, message); - for (var i = 0; i < reqd; i++) { - message.push(reqd); - } - }, - - unpad: function(cipher, message) { - _unpadLength(cipher, message, "PKCS 7", message[message.length - 1]); - } - }; - - // Create mode namespace - var C_mode = C.mode = {}; - - /** - * Mode base "class". - */ - var Mode = C_mode.Mode = function(padding) { - if (padding) { - this._padding = padding; - } - }; - - Mode.prototype = { - encrypt: function(cipher, m, iv) { - this._padding.pad(cipher, m); - this._doEncrypt(cipher, m, iv); - }, - - decrypt: function(cipher, m, iv) { - this._doDecrypt(cipher, m, iv); - this._padding.unpad(cipher, m); - }, - - // Default padding - _padding: C_pad.iso7816 - }; - - - /** - * Electronic Code Book mode. - * - * ECB applies the cipher directly against each block of the input. - * - * ECB does not require an initialization vector. - */ - var ECB = C_mode.ECB = function() { - // Call parent constructor - Mode.apply(this, arguments); - }; - - // Inherit from Mode - var ECB_prototype = ECB.prototype = new Mode; - - // Concrete steps for Mode template - ECB_prototype._doEncrypt = function(cipher, m, iv) { - var blockSizeInBytes = cipher._blocksize * 4; - // Encrypt each block - for (var offset = 0; offset < m.length; offset += blockSizeInBytes) { - cipher._encryptblock(m, offset); - } - }; - ECB_prototype._doDecrypt = function(cipher, c, iv) { - var blockSizeInBytes = cipher._blocksize * 4; - // Decrypt each block - for (var offset = 0; offset < c.length; offset += blockSizeInBytes) { - cipher._decryptblock(c, offset); - } - }; - - // ECB never uses an IV - ECB_prototype.fixOptions = function(options) { - options.iv = []; - }; - - - /** - * Cipher block chaining - * - * The first block is XORed with the IV. Subsequent blocks are XOR with the - * previous cipher output. - */ - var CBC = C_mode.CBC = function() { - // Call parent constructor - Mode.apply(this, arguments); - }; - - // Inherit from Mode - var CBC_prototype = CBC.prototype = new Mode; - - // Concrete steps for Mode template - CBC_prototype._doEncrypt = function(cipher, m, iv) { - var blockSizeInBytes = cipher._blocksize * 4; - - // Encrypt each block - for (var offset = 0; offset < m.length; offset += blockSizeInBytes) { - if (offset == 0) { - // XOR first block using IV - for (var i = 0; i < blockSizeInBytes; i++) - m[i] ^= iv[i]; - } else { - // XOR this block using previous crypted block - for (var i = 0; i < blockSizeInBytes; i++) - m[offset + i] ^= m[offset + i - blockSizeInBytes]; - } - // Encrypt block - cipher._encryptblock(m, offset); - } - }; - CBC_prototype._doDecrypt = function(cipher, c, iv) { - var blockSizeInBytes = cipher._blocksize * 4; - - // At the start, the previously crypted block is the IV - var prevCryptedBlock = iv; - - // Decrypt each block - for (var offset = 0; offset < c.length; offset += blockSizeInBytes) { - // Save this crypted block - var thisCryptedBlock = c.slice(offset, offset + blockSizeInBytes); - // Decrypt block - cipher._decryptblock(c, offset); - // XOR decrypted block using previous crypted block - for (var i = 0; i < blockSizeInBytes; i++) { - c[offset + i] ^= prevCryptedBlock[i]; - } - prevCryptedBlock = thisCryptedBlock; - } - }; - - - /** - * Cipher feed back - * - * The cipher output is XORed with the plain text to produce the cipher output, - * which is then fed back into the cipher to produce a bit pattern to XOR the - * next block with. - * - * This is a stream cipher mode and does not require padding. - */ - var CFB = C_mode.CFB = function() { - // Call parent constructor - Mode.apply(this, arguments); - }; - - // Inherit from Mode - var CFB_prototype = CFB.prototype = new Mode; - - // Override padding - CFB_prototype._padding = C_pad.NoPadding; - - // Concrete steps for Mode template - CFB_prototype._doEncrypt = function(cipher, m, iv) { - var blockSizeInBytes = cipher._blocksize * 4, - keystream = iv.slice(0); - - // Encrypt each byte - for (var i = 0; i < m.length; i++) { - - var j = i % blockSizeInBytes; - if (j == 0) cipher._encryptblock(keystream, 0); - - m[i] ^= keystream[j]; - keystream[j] = m[i]; - } - }; - CFB_prototype._doDecrypt = function(cipher, c, iv) { - var blockSizeInBytes = cipher._blocksize * 4, - keystream = iv.slice(0); - - // Encrypt each byte - for (var i = 0; i < c.length; i++) { - - var j = i % blockSizeInBytes; - if (j == 0) cipher._encryptblock(keystream, 0); - - var b = c[i]; - c[i] ^= keystream[j]; - keystream[j] = b; - } - }; - - - /** - * Output feed back - * - * The cipher repeatedly encrypts its own output. The output is XORed with the - * plain text to produce the cipher text. - * - * This is a stream cipher mode and does not require padding. - */ - var OFB = C_mode.OFB = function() { - // Call parent constructor - Mode.apply(this, arguments); - }; - - // Inherit from Mode - var OFB_prototype = OFB.prototype = new Mode; - - // Override padding - OFB_prototype._padding = C_pad.NoPadding; - - // Concrete steps for Mode template - OFB_prototype._doEncrypt = function(cipher, m, iv) { - - var blockSizeInBytes = cipher._blocksize * 4, - keystream = iv.slice(0); - - // Encrypt each byte - for (var i = 0; i < m.length; i++) { - - // Generate keystream - if (i % blockSizeInBytes == 0) - cipher._encryptblock(keystream, 0); - - // Encrypt byte - m[i] ^= keystream[i % blockSizeInBytes]; - - } - }; - OFB_prototype._doDecrypt = OFB_prototype._doEncrypt; - - /** - * Counter - * @author Gergely Risko - * - * After every block the last 4 bytes of the IV is increased by one - * with carry and that IV is used for the next block. - * - * This is a stream cipher mode and does not require padding. - */ - var CTR = C_mode.CTR = function() { - // Call parent constructor - Mode.apply(this, arguments); - }; - - // Inherit from Mode - var CTR_prototype = CTR.prototype = new Mode; - - // Override padding - CTR_prototype._padding = C_pad.NoPadding; - - CTR_prototype._doEncrypt = function(cipher, m, iv) { - var blockSizeInBytes = cipher._blocksize * 4; - var counter = iv.slice(0); - - for (var i = 0; i < m.length;) { - // do not lose iv - var keystream = counter.slice(0); - - // Generate keystream for next block - cipher._encryptblock(keystream, 0); - - // XOR keystream with block - for (var j = 0; i < m.length && j < blockSizeInBytes; j++, i++) { - m[i] ^= keystream[j]; - } - - // Increase counter - if (++(counter[blockSizeInBytes - 1]) == 256) { - counter[blockSizeInBytes - 1] = 0; - if (++(counter[blockSizeInBytes - 2]) == 256) { - counter[blockSizeInBytes - 2] = 0; - if (++(counter[blockSizeInBytes - 3]) == 256) { - counter[blockSizeInBytes - 3] = 0; - ++(counter[blockSizeInBytes - 4]); - } - } - } - } - }; - CTR_prototype._doDecrypt = CTR_prototype._doEncrypt; - - })(Crypto); - - /*! - * Crypto-JS v2.5.4 PBKDF2.js - * http://code.google.com/p/crypto-js/ - * Copyright (c) 2009-2013, Jeff Mott. All rights reserved. - * http://code.google.com/p/crypto-js/wiki/License - */ - (function() { - - // Shortcuts - var C = Crypto, - util = C.util, - charenc = C.charenc, - UTF8 = charenc.UTF8, - Binary = charenc.Binary; - - C.PBKDF2 = function(password, salt, keylen, options) { - - // Convert to byte arrays - if (password.constructor == String) password = UTF8.stringToBytes(password); - if (salt.constructor == String) salt = UTF8.stringToBytes(salt); - /* else, assume byte arrays already */ - - // Defaults - var hasher = options && options.hasher || C.SHA1, - iterations = options && options.iterations || 1; - - // Pseudo-random function - function PRF(password, salt) { - return C.HMAC(hasher, salt, password, { - asBytes: true - }); - } - - // Generate key - var derivedKeyBytes = [], - blockindex = 1; - while (derivedKeyBytes.length < keylen) { - var block = PRF(password, salt.concat(util.wordsToBytes([blockindex]))); - for (var u = block, i = 1; i < iterations; i++) { - u = PRF(password, u); - for (var j = 0; j < block.length; j++) block[j] ^= u[j]; - } - derivedKeyBytes = derivedKeyBytes.concat(block); - blockindex++; - } - - // Truncate excess bytes - derivedKeyBytes.length = keylen; - - return options && options.asBytes ? derivedKeyBytes : - options && options.asString ? Binary.bytesToString(derivedKeyBytes) : - util.bytesToHex(derivedKeyBytes); - - }; - - })(); - - /* - * Copyright (c) 2010-2011 Intalio Pte, All Rights Reserved - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - // https://github.com/cheongwy/node-scrypt-js - (function() { - - var MAX_VALUE = 2147483647; - var workerUrl = null; - - //function scrypt(byte[] passwd, byte[] salt, int N, int r, int p, int dkLen) - /* - * N = Cpu cost - * r = Memory cost - * p = parallelization cost - * - */ - GLOBAL.Crypto_scrypt = function(passwd, salt, N, r, p, dkLen, callback) { - if (N == 0 || (N & (N - 1)) != 0) throw Error("N must be > 0 and a power of 2"); - - if (N > MAX_VALUE / 128 / r) throw Error("Parameter N is too large"); - if (r > MAX_VALUE / 128 / p) throw Error("Parameter r is too large"); - - var PBKDF2_opts = { - iterations: 1, - hasher: Crypto.SHA256, - asBytes: true - }; - - var B = Crypto.PBKDF2(passwd, salt, p * 128 * r, PBKDF2_opts); - - try { - var i = 0; - var worksDone = 0; - var makeWorker = function() { - if (!workerUrl) { - var code = '(' + scryptCore.toString() + ')()'; - var blob; - try { - blob = new Blob([code], { - type: "text/javascript" - }); - } catch (e) { - GLOBAL.BlobBuilder = GLOBAL.BlobBuilder || GLOBAL.WebKitBlobBuilder || - GLOBAL.MozBlobBuilder || - GLOBAL.MSBlobBuilder; - blob = new BlobBuilder(); - blob.append(code); - blob = blob.getBlob("text/javascript"); - } - workerUrl = URL.createObjectURL(blob); - } - var worker = new Worker(workerUrl); - worker.onmessage = function(event) { - var Bi = event.data[0], - Bslice = event.data[1]; - worksDone++; - - if (i < p) { - worker.postMessage([N, r, p, B, i++]); - } - - var length = Bslice.length, - destPos = Bi * 128 * r, - srcPos = 0; - while (length--) { - B[destPos++] = Bslice[srcPos++]; - } - - if (worksDone == p) { - callback(Crypto.PBKDF2(passwd, B, dkLen, PBKDF2_opts)); - } - }; - return worker; - }; - var workers = [makeWorker(), makeWorker()]; - workers[0].postMessage([N, r, p, B, i++]); - if (p > 1) { - workers[1].postMessage([N, r, p, B, i++]); - } - } catch (e) { - GLOBAL.setTimeout(function() { - scryptCore(); - callback(Crypto.PBKDF2(passwd, B, dkLen, PBKDF2_opts)); - }, 0); - } - - // using this function to enclose everything needed to create a worker (but also invokable directly for synchronous use) - function scryptCore() { - var XY = [], - V = []; - - if (typeof B === 'undefined') { - onmessage = function(event) { - var data = event.data; - var N = data[0], - r = data[1], - p = data[2], - B = data[3], - i = data[4]; - - var Bslice = []; - arraycopy32(B, i * 128 * r, Bslice, 0, 128 * r); - smix(Bslice, 0, r, N, V, XY); - - postMessage([i, Bslice]); - }; - } else { - for (var i = 0; i < p; i++) { - smix(B, i * 128 * r, r, N, V, XY); - } - } - - function smix(B, Bi, r, N, V, XY) { - var Xi = 0; - var Yi = 128 * r; - var i; - - arraycopy32(B, Bi, XY, Xi, Yi); - - for (i = 0; i < N; i++) { - arraycopy32(XY, Xi, V, i * Yi, Yi); - blockmix_salsa8(XY, Xi, Yi, r); - } - - for (i = 0; i < N; i++) { - var j = integerify(XY, Xi, r) & (N - 1); - blockxor(V, j * Yi, XY, Xi, Yi); - blockmix_salsa8(XY, Xi, Yi, r); - } - - arraycopy32(XY, Xi, B, Bi, Yi); - } - - function blockmix_salsa8(BY, Bi, Yi, r) { - var X = []; - var i; - - arraycopy32(BY, Bi + (2 * r - 1) * 64, X, 0, 64); - - for (i = 0; i < 2 * r; i++) { - blockxor(BY, i * 64, X, 0, 64); - salsa20_8(X); - arraycopy32(X, 0, BY, Yi + (i * 64), 64); - } - - for (i = 0; i < r; i++) { - arraycopy32(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64); - } - - for (i = 0; i < r; i++) { - arraycopy32(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64); - } - } - - function R(a, b) { - return (a << b) | (a >>> (32 - b)); - } - - function salsa20_8(B) { - var B32 = new Array(32); - var x = new Array(32); - var i; - - for (i = 0; i < 16; i++) { - B32[i] = (B[i * 4 + 0] & 0xff) << 0; - B32[i] |= (B[i * 4 + 1] & 0xff) << 8; - B32[i] |= (B[i * 4 + 2] & 0xff) << 16; - B32[i] |= (B[i * 4 + 3] & 0xff) << 24; - } - - arraycopy(B32, 0, x, 0, 16); - - for (i = 8; i > 0; i -= 2) { - x[4] ^= R(x[0] + x[12], 7); - x[8] ^= R(x[4] + x[0], 9); - x[12] ^= R(x[8] + x[4], 13); - x[0] ^= R(x[12] + x[8], 18); - x[9] ^= R(x[5] + x[1], 7); - x[13] ^= R(x[9] + x[5], 9); - x[1] ^= R(x[13] + x[9], 13); - x[5] ^= R(x[1] + x[13], 18); - x[14] ^= R(x[10] + x[6], 7); - x[2] ^= R(x[14] + x[10], 9); - x[6] ^= R(x[2] + x[14], 13); - x[10] ^= R(x[6] + x[2], 18); - x[3] ^= R(x[15] + x[11], 7); - x[7] ^= R(x[3] + x[15], 9); - x[11] ^= R(x[7] + x[3], 13); - x[15] ^= R(x[11] + x[7], 18); - x[1] ^= R(x[0] + x[3], 7); - x[2] ^= R(x[1] + x[0], 9); - x[3] ^= R(x[2] + x[1], 13); - x[0] ^= R(x[3] + x[2], 18); - x[6] ^= R(x[5] + x[4], 7); - x[7] ^= R(x[6] + x[5], 9); - x[4] ^= R(x[7] + x[6], 13); - x[5] ^= R(x[4] + x[7], 18); - x[11] ^= R(x[10] + x[9], 7); - x[8] ^= R(x[11] + x[10], 9); - x[9] ^= R(x[8] + x[11], 13); - x[10] ^= R(x[9] + x[8], 18); - x[12] ^= R(x[15] + x[14], 7); - x[13] ^= R(x[12] + x[15], 9); - x[14] ^= R(x[13] + x[12], 13); - x[15] ^= R(x[14] + x[13], 18); - } - - for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]; - - for (i = 0; i < 16; i++) { - var bi = i * 4; - B[bi + 0] = (B32[i] >> 0 & 0xff); - B[bi + 1] = (B32[i] >> 8 & 0xff); - B[bi + 2] = (B32[i] >> 16 & 0xff); - B[bi + 3] = (B32[i] >> 24 & 0xff); - } - } - - function blockxor(S, Si, D, Di, len) { - var i = len >> 6; - while (i--) { - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - D[Di++] ^= S[Si++]; - } - } - - function integerify(B, bi, r) { - var n; - - bi += (2 * r - 1) * 64; - - n = (B[bi + 0] & 0xff) << 0; - n |= (B[bi + 1] & 0xff) << 8; - n |= (B[bi + 2] & 0xff) << 16; - n |= (B[bi + 3] & 0xff) << 24; - - return n; - } - - function arraycopy(src, srcPos, dest, destPos, length) { - while (length--) { - dest[destPos++] = src[srcPos++]; - } - } - - function arraycopy32(src, srcPos, dest, destPos, length) { - var i = length >> 5; - while (i--) { - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - dest[destPos++] = src[srcPos++]; - } - } - } // scryptCore - }; // GLOBAL.Crypto_scrypt - })(); - - /*! - * Crypto-JS v2.5.4 AES.js - * http://code.google.com/p/crypto-js/ - * Copyright (c) 2009-2013, Jeff Mott. All rights reserved. - * http://code.google.com/p/crypto-js/wiki/License - */ - (function() { - - // Shortcuts - var C = Crypto, - util = C.util, - charenc = C.charenc, - UTF8 = charenc.UTF8; - - // Precomputed SBOX - var SBOX = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, - 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, - 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, - 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, - 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, - 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, - 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, - 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, - 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, - 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, - 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, - 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, - 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, - 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, - 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, - 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, - 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, - 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, - 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, - 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, - 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, - 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, - 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, - 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, - 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, - 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, - 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, - 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, - 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, - 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, - 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, - 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 - ]; - - // Compute inverse SBOX lookup table - for (var INVSBOX = [], i = 0; i < 256; i++) INVSBOX[SBOX[i]] = i; - - // Compute multiplication in GF(2^8) lookup tables - var MULT2 = [], - MULT3 = [], - MULT9 = [], - MULTB = [], - MULTD = [], - MULTE = []; - - function xtime(a, b) { - for (var result = 0, i = 0; i < 8; i++) { - if (b & 1) result ^= a; - var hiBitSet = a & 0x80; - a = (a << 1) & 0xFF; - if (hiBitSet) a ^= 0x1b; - b >>>= 1; - } - return result; - } - - for (var i = 0; i < 256; i++) { - MULT2[i] = xtime(i, 2); - MULT3[i] = xtime(i, 3); - MULT9[i] = xtime(i, 9); - MULTB[i] = xtime(i, 0xB); - MULTD[i] = xtime(i, 0xD); - MULTE[i] = xtime(i, 0xE); - } - - // Precomputed RCon lookup - var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; - - // Inner state - var state = [ - [], - [], - [], - [] - ], - keylength, - nrounds, - keyschedule; - - var AES = C.AES = { - - /** - * Public API - */ - - encrypt: function(message, password, options) { - - options = options || {}; - - // Determine mode - var mode = options.mode || new C.mode.OFB; - - // Allow mode to override options - if (mode.fixOptions) mode.fixOptions(options); - - var - - // Convert to bytes if message is a string - m = ( - message.constructor == String ? - UTF8.stringToBytes(message) : - message - ), - - // Generate random IV - iv = options.iv || util.randomBytes(AES._blocksize * 4), - - // Generate key - k = ( - password.constructor == String ? - // Derive key from pass-phrase - C.PBKDF2(password, iv, 32, { - asBytes: true - }) : - // else, assume byte array representing cryptographic key - password - ); - - // Encrypt - AES._init(k); - mode.encrypt(AES, m, iv); - - // Return ciphertext - m = options.iv ? m : iv.concat(m); - return (options && options.asBytes) ? m : util.bytesToBase64(m); - - }, - - decrypt: function(ciphertext, password, options) { - - options = options || {}; - - // Determine mode - var mode = options.mode || new C.mode.OFB; - - // Allow mode to override options - if (mode.fixOptions) mode.fixOptions(options); - - var - - // Convert to bytes if ciphertext is a string - c = ( - ciphertext.constructor == String ? - util.base64ToBytes(ciphertext) : - ciphertext - ), - - // Separate IV and message - iv = options.iv || c.splice(0, AES._blocksize * 4), - - // Generate key - k = ( - password.constructor == String ? - // Derive key from pass-phrase - C.PBKDF2(password, iv, 32, { - asBytes: true - }) : - // else, assume byte array representing cryptographic key - password - ); - - // Decrypt - AES._init(k); - mode.decrypt(AES, c, iv); - - // Return plaintext - return (options && options.asBytes) ? c : UTF8.bytesToString(c); - - }, - - - /** - * Package private methods and properties - */ - - _blocksize: 4, - - _encryptblock: function(m, offset) { - - // Set input - for (var row = 0; row < AES._blocksize; row++) { - for (var col = 0; col < 4; col++) - state[row][col] = m[offset + col * 4 + row]; - } - - // Add round key - for (var row = 0; row < 4; row++) { - for (var col = 0; col < 4; col++) - state[row][col] ^= keyschedule[col][row]; - } - - for (var round = 1; round < nrounds; round++) { - - // Sub bytes - for (var row = 0; row < 4; row++) { - for (var col = 0; col < 4; col++) - state[row][col] = SBOX[state[row][col]]; - } - - // Shift rows - state[1].push(state[1].shift()); - state[2].push(state[2].shift()); - state[2].push(state[2].shift()); - state[3].unshift(state[3].pop()); - - // Mix columns - for (var col = 0; col < 4; col++) { - - var s0 = state[0][col], - s1 = state[1][col], - s2 = state[2][col], - s3 = state[3][col]; - - state[0][col] = MULT2[s0] ^ MULT3[s1] ^ s2 ^ s3; - state[1][col] = s0 ^ MULT2[s1] ^ MULT3[s2] ^ s3; - state[2][col] = s0 ^ s1 ^ MULT2[s2] ^ MULT3[s3]; - state[3][col] = MULT3[s0] ^ s1 ^ s2 ^ MULT2[s3]; - - } - - // Add round key - for (var row = 0; row < 4; row++) { - for (var col = 0; col < 4; col++) - state[row][col] ^= keyschedule[round * 4 + col][row]; - } - - } - - // Sub bytes - for (var row = 0; row < 4; row++) { - for (var col = 0; col < 4; col++) - state[row][col] = SBOX[state[row][col]]; - } - - // Shift rows - state[1].push(state[1].shift()); - state[2].push(state[2].shift()); - state[2].push(state[2].shift()); - state[3].unshift(state[3].pop()); - - // Add round key - for (var row = 0; row < 4; row++) { - for (var col = 0; col < 4; col++) - state[row][col] ^= keyschedule[nrounds * 4 + col][row]; - } - - // Set output - for (var row = 0; row < AES._blocksize; row++) { - for (var col = 0; col < 4; col++) - m[offset + col * 4 + row] = state[row][col]; - } - - }, - - _decryptblock: function(c, offset) { - - // Set input - for (var row = 0; row < AES._blocksize; row++) { - for (var col = 0; col < 4; col++) - state[row][col] = c[offset + col * 4 + row]; - } - - // Add round key - for (var row = 0; row < 4; row++) { - for (var col = 0; col < 4; col++) - state[row][col] ^= keyschedule[nrounds * 4 + col][row]; - } - - for (var round = 1; round < nrounds; round++) { - - // Inv shift rows - state[1].unshift(state[1].pop()); - state[2].push(state[2].shift()); - state[2].push(state[2].shift()); - state[3].push(state[3].shift()); - - // Inv sub bytes - for (var row = 0; row < 4; row++) { - for (var col = 0; col < 4; col++) - state[row][col] = INVSBOX[state[row][col]]; - } - - // Add round key - for (var row = 0; row < 4; row++) { - for (var col = 0; col < 4; col++) - state[row][col] ^= keyschedule[(nrounds - round) * 4 + col][row]; - } - - // Inv mix columns - for (var col = 0; col < 4; col++) { - - var s0 = state[0][col], - s1 = state[1][col], - s2 = state[2][col], - s3 = state[3][col]; - - state[0][col] = MULTE[s0] ^ MULTB[s1] ^ MULTD[s2] ^ MULT9[s3]; - state[1][col] = MULT9[s0] ^ MULTE[s1] ^ MULTB[s2] ^ MULTD[s3]; - state[2][col] = MULTD[s0] ^ MULT9[s1] ^ MULTE[s2] ^ MULTB[s3]; - state[3][col] = MULTB[s0] ^ MULTD[s1] ^ MULT9[s2] ^ MULTE[s3]; - - } - - } - - // Inv shift rows - state[1].unshift(state[1].pop()); - state[2].push(state[2].shift()); - state[2].push(state[2].shift()); - state[3].push(state[3].shift()); - - // Inv sub bytes - for (var row = 0; row < 4; row++) { - for (var col = 0; col < 4; col++) - state[row][col] = INVSBOX[state[row][col]]; - } - - // Add round key - for (var row = 0; row < 4; row++) { - for (var col = 0; col < 4; col++) - state[row][col] ^= keyschedule[col][row]; - } - - // Set output - for (var row = 0; row < AES._blocksize; row++) { - for (var col = 0; col < 4; col++) - c[offset + col * 4 + row] = state[row][col]; - } - - }, - - - /** - * Private methods - */ - - _init: function(k) { - keylength = k.length / 4; - nrounds = keylength + 6; - AES._keyexpansion(k); - }, - - // Generate a key schedule - _keyexpansion: function(k) { - - keyschedule = []; - - for (var row = 0; row < keylength; row++) { - keyschedule[row] = [ - k[row * 4], - k[row * 4 + 1], - k[row * 4 + 2], - k[row * 4 + 3] - ]; - } - - for (var row = keylength; row < AES._blocksize * (nrounds + 1); row++) { - - var temp = [ - keyschedule[row - 1][0], - keyschedule[row - 1][1], - keyschedule[row - 1][2], - keyschedule[row - 1][3] - ]; - - if (row % keylength == 0) { - - // Rot word - temp.push(temp.shift()); - - // Sub word - temp[0] = SBOX[temp[0]]; - temp[1] = SBOX[temp[1]]; - temp[2] = SBOX[temp[2]]; - temp[3] = SBOX[temp[3]]; - - temp[0] ^= RCON[row / keylength]; - - } else if (keylength > 6 && row % keylength == 4) { - - // Sub word - temp[0] = SBOX[temp[0]]; - temp[1] = SBOX[temp[1]]; - temp[2] = SBOX[temp[2]]; - temp[3] = SBOX[temp[3]]; - - } - - keyschedule[row] = [ - keyschedule[row - keylength][0] ^ temp[0], - keyschedule[row - keylength][1] ^ temp[1], - keyschedule[row - keylength][2] ^ temp[2], - keyschedule[row - keylength][3] ^ temp[3] - ]; - - } - - } - - }; - - })(); - - /* - * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) - * Ported to JavaScript by bitaddress.org - */ - ec.FieldElementFp.fastLucasSequence = function(p, P, Q, k) { - // TODO Research and apply "common-multiplicand multiplication here" - - var n = k.bitLength(); - var s = k.getLowestSetBit(); - var Uh = BigInteger.ONE; - var Vl = BigInteger.TWO; - var Vh = P; - var Ql = BigInteger.ONE; - var Qh = BigInteger.ONE; - - for (var j = n - 1; j >= s + 1; --j) { - Ql = Ql.multiply(Qh).mod(p); - if (k.testBit(j)) { - Qh = Ql.multiply(Q).mod(p); - Uh = Uh.multiply(Vh).mod(p); - Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); - Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p); - } else { - Qh = Ql; - Uh = Uh.multiply(Vl).subtract(Ql).mod(p); - Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); - Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); - } - } - - Ql = Ql.multiply(Qh).mod(p); - Qh = Ql.multiply(Q).mod(p); - Uh = Uh.multiply(Vl).subtract(Ql).mod(p); - Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); - Ql = Ql.multiply(Qh).mod(p); - - for (var j = 1; j <= s; ++j) { - Uh = Uh.multiply(Vl).mod(p); - Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); - Ql = Ql.multiply(Ql).mod(p); - } - - return [Uh, Vl]; - }; - - // ---------------- - // ECPointFp constructor - ec.PointFp = function(curve, x, y, z, compressed) { - this.curve = curve; - this.x = x; - this.y = y; - // Projective coordinates: either zinv == null or z * zinv == 1 - // z and zinv are just BigIntegers, not fieldElements - if (z == null) { - this.z = BigInteger.ONE; - } else { - this.z = z; - } - this.zinv = null; - // compression flag - this.compressed = !!compressed; - }; - - ec.PointFp.prototype.getX = function() { - if (this.zinv == null) { - this.zinv = this.z.modInverse(this.curve.q); - } - var r = this.x.toBigInteger().multiply(this.zinv); - this.curve.reduce(r); - return this.curve.fromBigInteger(r); - }; - - ec.PointFp.prototype.getY = function() { - if (this.zinv == null) { - this.zinv = this.z.modInverse(this.curve.q); - } - var r = this.y.toBigInteger().multiply(this.zinv); - this.curve.reduce(r); - return this.curve.fromBigInteger(r); - }; - - ec.PointFp.prototype.equals = function(other) { - if (other == this) return true; - if (this.isInfinity()) return other.isInfinity(); - if (other.isInfinity()) return this.isInfinity(); - var u, v; - // u = Y2 * Z1 - Y1 * Z2 - u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod( - this.curve.q); - if (!u.equals(BigInteger.ZERO)) return false; - // v = X2 * Z1 - X1 * Z2 - v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod( - this.curve.q); - return v.equals(BigInteger.ZERO); - }; - - ec.PointFp.prototype.isInfinity = function() { - if ((this.x == null) && (this.y == null)) return true; - return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); - }; - - ec.PointFp.prototype.negate = function() { - return new ec.PointFp(this.curve, this.x, this.y.negate(), this.z); - }; - - ec.PointFp.prototype.add = function(b) { - if (this.isInfinity()) return b; - if (b.isInfinity()) return this; - - // u = Y2 * Z1 - Y1 * Z2 - var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod( - this.curve.q); - // v = X2 * Z1 - X1 * Z2 - var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod( - this.curve.q); - - - if (BigInteger.ZERO.equals(v)) { - if (BigInteger.ZERO.equals(u)) { - return this.twice(); // this == b, so double - } - return this.curve.getInfinity(); // this = -b, so infinity - } - - var THREE = new BigInteger("3"); - var x1 = this.x.toBigInteger(); - var y1 = this.y.toBigInteger(); - var x2 = b.x.toBigInteger(); - var y2 = b.y.toBigInteger(); - - var v2 = v.square(); - var v3 = v2.multiply(v); - var x1v2 = x1.multiply(v2); - var zu2 = u.square().multiply(this.z); - - // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) - var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); - // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 - var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply( - b.z).add(u.multiply(v3)).mod(this.curve.q); - // z3 = v^3 * z1 * z2 - var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); - - return new ec.PointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), - z3); - }; - - ec.PointFp.prototype.twice = function() { - if (this.isInfinity()) return this; - if (this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); - - // TODO: optimized handling of constants - var THREE = new BigInteger("3"); - var x1 = this.x.toBigInteger(); - var y1 = this.y.toBigInteger(); - - var y1z1 = y1.multiply(this.z); - var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); - var a = this.curve.a.toBigInteger(); - - // w = 3 * x1^2 + a * z1^2 - var w = x1.square().multiply(THREE); - if (!BigInteger.ZERO.equals(a)) { - w = w.add(this.z.square().multiply(a)); - } - w = w.mod(this.curve.q); - //this.curve.reduce(w); - // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) - var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod( - this.curve.q); - // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 - var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply( - y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); - // z3 = 8 * (y1 * z1)^3 - var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); - - return new ec.PointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), - z3); - }; - - // Simple NAF (Non-Adjacent Form) multiplication algorithm - // TODO: modularize the multiplication algorithm - ec.PointFp.prototype.multiply = function(k) { - if (this.isInfinity()) return this; - if (k.signum() == 0) return this.curve.getInfinity(); - - var e = k; - var h = e.multiply(new BigInteger("3")); - - var neg = this.negate(); - var R = this; - - var i; - for (i = h.bitLength() - 2; i > 0; --i) { - R = R.twice(); - - var hBit = h.testBit(i); - var eBit = e.testBit(i); - - if (hBit != eBit) { - R = R.add(hBit ? this : neg); - } - } - - return R; - }; - - // Compute this*j + x*k (simultaneous multiplication) - ec.PointFp.prototype.multiplyTwo = function(j, x, k) { - var i; - if (j.bitLength() > k.bitLength()) - i = j.bitLength() - 1; - else - i = k.bitLength() - 1; - - var R = this.curve.getInfinity(); - var both = this.add(x); - while (i >= 0) { - R = R.twice(); - if (j.testBit(i)) { - if (k.testBit(i)) { - R = R.add(both); - } else { - R = R.add(this); - } - } else { - if (k.testBit(i)) { - R = R.add(x); - } - } - --i; - } - - return R; - }; - - // patched by bitaddress.org and Casascius for use with Bitcoin.ECKey - // patched by coretechs to support compressed public keys - ec.PointFp.prototype.getEncoded = function(compressed) { - var x = this.getX().toBigInteger(); - var y = this.getY().toBigInteger(); - var len = 32; // integerToBytes will zero pad if integer is less than 32 bytes. 32 bytes length is required by the Bitcoin protocol. - var enc = ec.integerToBytes(x, len); - - // when compressed prepend byte depending if y point is even or odd - if (compressed) { - if (y.isEven()) { - enc.unshift(0x02); - } else { - enc.unshift(0x03); - } - } else { - enc.unshift(0x04); - enc = enc.concat(ec.integerToBytes(y, len)); // uncompressed public key appends the bytes of the y point - } - return enc; - }; - - ec.PointFp.decodeFrom = function(curve, enc) { - var type = enc[0]; - var dataLen = enc.length - 1; - - // Extract x and y as byte arrays - var xBa = enc.slice(1, 1 + dataLen / 2); - var yBa = enc.slice(1 + dataLen / 2, 1 + dataLen); - - // Prepend zero byte to prevent interpretation as negative integer - xBa.unshift(0); - yBa.unshift(0); - - // Convert to BigIntegers - var x = new BigInteger(xBa); - var y = new BigInteger(yBa); - - // Return point - return new ec.PointFp(curve, curve.fromBigInteger(x), curve.fromBigInteger(y)); - }; - - ec.PointFp.prototype.add2D = function(b) { - if (this.isInfinity()) return b; - if (b.isInfinity()) return this; - - if (this.x.equals(b.x)) { - if (this.y.equals(b.y)) { - // this = b, i.e. this must be doubled - return this.twice(); - } - // this = -b, i.e. the result is the point at infinity - return this.curve.getInfinity(); - } - - var x_x = b.x.subtract(this.x); - var y_y = b.y.subtract(this.y); - var gamma = y_y.divide(x_x); - - var x3 = gamma.square().subtract(this.x).subtract(b.x); - var y3 = gamma.multiply(this.x.subtract(x3)).subtract(this.y); - - return new ec.PointFp(this.curve, x3, y3); - }; - - ec.PointFp.prototype.twice2D = function() { - if (this.isInfinity()) return this; - if (this.y.toBigInteger().signum() == 0) { - // if y1 == 0, then (x1, y1) == (x1, -y1) - // and hence this = -this and thus 2(x1, y1) == infinity - return this.curve.getInfinity(); - } - - var TWO = this.curve.fromBigInteger(BigInteger.valueOf(2)); - var THREE = this.curve.fromBigInteger(BigInteger.valueOf(3)); - var gamma = this.x.square().multiply(THREE).add(this.curve.a).divide(this.y.multiply(TWO)); - - var x3 = gamma.square().subtract(this.x.multiply(TWO)); - var y3 = gamma.multiply(this.x.subtract(x3)).subtract(this.y); - - return new ec.PointFp(this.curve, x3, y3); - }; - - ec.PointFp.prototype.multiply2D = function(k) { - if (this.isInfinity()) return this; - if (k.signum() == 0) return this.curve.getInfinity(); - - var e = k; - var h = e.multiply(new BigInteger("3")); - - var neg = this.negate(); - var R = this; - - var i; - for (i = h.bitLength() - 2; i > 0; --i) { - R = R.twice(); - - var hBit = h.testBit(i); - var eBit = e.testBit(i); - - if (hBit != eBit) { - R = R.add2D(hBit ? this : neg); - } - } - - return R; - }; - - ec.PointFp.prototype.isOnCurve = function() { - var x = this.getX().toBigInteger(); - var y = this.getY().toBigInteger(); - var a = this.curve.getA().toBigInteger(); - var b = this.curve.getB().toBigInteger(); - var n = this.curve.getQ(); - var lhs = y.multiply(y).mod(n); - var rhs = x.multiply(x).multiply(x).add(a.multiply(x)).add(b).mod(n); - return lhs.equals(rhs); - }; - - ec.PointFp.prototype.toString = function() { - return '(' + this.getX().toBigInteger().toString() + ',' + this.getY().toBigInteger().toString() + - ')'; - }; - - /** - * Validate an elliptic curve point. - * - * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive - */ - ec.PointFp.prototype.validate = function() { - var n = this.curve.getQ(); - - // Check Q != O - if (this.isInfinity()) { - throw new Error("Point is at infinity."); - } - - // Check coordinate bounds - var x = this.getX().toBigInteger(); - var y = this.getY().toBigInteger(); - if (x.compareTo(BigInteger.ONE) < 0 || x.compareTo(n.subtract(BigInteger.ONE)) > 0) { - throw new Error('x coordinate out of bounds'); - } - if (y.compareTo(BigInteger.ONE) < 0 || y.compareTo(n.subtract(BigInteger.ONE)) > 0) { - throw new Error('y coordinate out of bounds'); - } - - // Check y^2 = x^3 + ax + b (mod n) - if (!this.isOnCurve()) { - throw new Error("Point is not on the curve."); - } - - // Check nQ = 0 (Q is a scalar multiple of G) - if (this.multiply(n).isInfinity()) { - // TODO: This check doesn't work - fix. - throw new Error("Point is not a scalar multiple of G."); - } - - return true; - }; - - - - - // ---------------- - // ECCurveFp constructor - ec.CurveFp = function(q, a, b) { - this.q = q; - this.a = this.fromBigInteger(a); - this.b = this.fromBigInteger(b); - this.infinity = new ec.PointFp(this, null, null); - this.reducer = new Barrett(this.q); - } - - ec.CurveFp.prototype.getQ = function() { - return this.q; - }; - - ec.CurveFp.prototype.getA = function() { - return this.a; - }; - - ec.CurveFp.prototype.getB = function() { - return this.b; - }; - - ec.CurveFp.prototype.equals = function(other) { - if (other == this) return true; - return (this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); - }; - - ec.CurveFp.prototype.getInfinity = function() { - return this.infinity; - }; - - ec.CurveFp.prototype.fromBigInteger = function(x) { - return new ec.FieldElementFp(this.q, x); - }; - - ec.CurveFp.prototype.reduce = function(x) { - this.reducer.reduce(x); - }; - - // for now, work with hex strings because they're easier in JS - // compressed support added by bitaddress.org - ec.CurveFp.prototype.decodePointHex = function(s) { - var firstByte = parseInt(s.substr(0, 2), 16); - switch (firstByte) { // first byte - case 0: - return this.infinity; - case 2: // compressed - case 3: // compressed - var yTilde = firstByte & 1; - var xHex = s.substr(2, s.length - 2); - var X1 = new BigInteger(xHex, 16); - return this.decompressPoint(yTilde, X1); - case 4: // uncompressed - case 6: // hybrid - case 7: // hybrid - var len = (s.length - 2) / 2; - var xHex = s.substr(2, len); - var yHex = s.substr(len + 2, len); - - return new ec.PointFp(this, - this.fromBigInteger(new BigInteger(xHex, 16)), - this.fromBigInteger(new BigInteger(yHex, 16))); - - default: // unsupported - return null; - } - }; - - ec.CurveFp.prototype.encodePointHex = function(p) { - if (p.isInfinity()) return "00"; - var xHex = p.getX().toBigInteger().toString(16); - var yHex = p.getY().toBigInteger().toString(16); - var oLen = this.getQ().toString(16).length; - if ((oLen % 2) != 0) oLen++; - while (xHex.length < oLen) { - xHex = "0" + xHex; - } - while (yHex.length < oLen) { - yHex = "0" + yHex; - } - return "04" + xHex + yHex; - }; - - /* - * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) - * Ported to JavaScript by bitaddress.org - * - * Number yTilde - * BigInteger X1 - */ - ec.CurveFp.prototype.decompressPoint = function(yTilde, X1) { - var x = this.fromBigInteger(X1); - var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); - var beta = alpha.sqrt(); - // if we can't find a sqrt we haven't got a point on the curve - run! - if (beta == null) throw new Error("Invalid point compression"); - var betaValue = beta.toBigInteger(); - var bit0 = betaValue.testBit(0) ? 1 : 0; - if (bit0 != yTilde) { - // Use the other root - beta = this.fromBigInteger(this.getQ().subtract(betaValue)); - } - return new ec.PointFp(this, x, beta, null, true); - }; - - - ec.fromHex = function(s) { - return new BigInteger(s, 16); - }; - - ec.integerToBytes = function(i, len) { - var bytes = i.toByteArrayUnsigned(); - if (len < bytes.length) { - bytes = bytes.slice(bytes.length - len); - } else - while (len > bytes.length) { - bytes.unshift(0); - } - return bytes; - }; - - - // Named EC curves - // ---------------- - // X9ECParameters constructor - ec.X9Parameters = function(curve, g, n, h) { - this.curve = curve; - this.g = g; - this.n = n; - this.h = h; - } - ec.X9Parameters.prototype.getCurve = function() { - return this.curve; - }; - ec.X9Parameters.prototype.getG = function() { - return this.g; - }; - ec.X9Parameters.prototype.getN = function() { - return this.n; - }; - ec.X9Parameters.prototype.getH = function() { - return this.h; - }; - - // secp256k1 is the Curve used by Bitcoin - ec.secNamedCurves = { - // used by Bitcoin - "secp256k1": function() { - // p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 - var p = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"); - var a = BigInteger.ZERO; - var b = ec.fromHex("7"); - var n = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); - var h = BigInteger.ONE; - var curve = new ec.CurveFp(p, a, b); - var G = curve.decodePointHex("04" + - "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798" + - "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8"); - return new ec.X9Parameters(curve, G, n, h); - } - }; - - // secp256k1 called by Bitcoin's ECKEY - ec.getSECCurveByName = function(name) { - if (ec.secNamedCurves[name] == undefined) return null; - return ec.secNamedCurves[name](); - } - })(); - - //bitTrx.js - (function() { - - var bitjs = GLOBAL.bitjs = function() {}; - - function ascii_to_hexa(str) { - var arr1 = []; - for (var n = 0, l = str.length; n < l; n++) { - var hex = Number(str.charCodeAt(n)).toString(16); - arr1.push(hex); - } - return arr1.join(''); - } - - /* public vars */ - bitjs.pub = 0x23; // flochange - changed the prefix to FLO Mainnet PublicKey Prefix 0x23 - bitjs.priv = 0xa3; //flochange - changed the prefix to FLO Mainnet Private key prefix 0xa3 - bitjs.compressed = false; - - /* provide a privkey and return an WIF */ - bitjs.privkey2wif = function(h) { - var r = Crypto.util.hexToBytes(h); - - if (bitjs.compressed == true) { - r.push(0x01); - } - - r.unshift(bitjs.priv); - var hash = Crypto.SHA256(Crypto.SHA256(r, { - asBytes: true - }), { - asBytes: true - }); - var checksum = hash.slice(0, 4); - - return B58.encode(r.concat(checksum)); - } - - /* convert a wif key back to a private key */ - bitjs.wif2privkey = function(wif) { - var compressed = false; - var decode = B58.decode(wif); - var key = decode.slice(0, decode.length - 4); - key = key.slice(1, key.length); - if (key.length >= 33 && key[key.length - 1] == 0x01) { - key = key.slice(0, key.length - 1); - compressed = true; - } - return { - 'privkey': Crypto.util.bytesToHex(key), - 'compressed': compressed - }; - } - - /* convert a wif to a pubkey */ - bitjs.wif2pubkey = function(wif) { - var compressed = bitjs.compressed; - var r = bitjs.wif2privkey(wif); - bitjs.compressed = r['compressed']; - var pubkey = bitjs.newPubkey(r['privkey']); - bitjs.compressed = compressed; - return { - 'pubkey': pubkey, - 'compressed': r['compressed'] - }; - } - - /* convert a wif to a address */ - bitjs.wif2address = function(wif) { - var r = bitjs.wif2pubkey(wif); - return { - 'address': bitjs.pubkey2address(r['pubkey']), - 'compressed': r['compressed'] - }; - } - - /* generate a public key from a private key */ - bitjs.newPubkey = function(hash) { - var privateKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(hash)); - var curve = EllipticCurve.getSECCurveByName("secp256k1"); - - var curvePt = curve.getG().multiply(privateKeyBigInt); - var x = curvePt.getX().toBigInteger(); - var y = curvePt.getY().toBigInteger(); - - var publicKeyBytes = EllipticCurve.integerToBytes(x, 32); - publicKeyBytes = publicKeyBytes.concat(EllipticCurve.integerToBytes(y, 32)); - publicKeyBytes.unshift(0x04); - - if (bitjs.compressed == true) { - var publicKeyBytesCompressed = EllipticCurve.integerToBytes(x, 32) - if (y.isEven()) { - publicKeyBytesCompressed.unshift(0x02) - } else { - publicKeyBytesCompressed.unshift(0x03) - } - return Crypto.util.bytesToHex(publicKeyBytesCompressed); - } else { - return Crypto.util.bytesToHex(publicKeyBytes); - } - } - - /* provide a public key and return address */ - bitjs.pubkey2address = function(h, byte) { - var r = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(h), { - asBytes: true - })); - r.unshift(byte || bitjs.pub); - var hash = Crypto.SHA256(Crypto.SHA256(r, { - asBytes: true - }), { - asBytes: true - }); - var checksum = hash.slice(0, 4); - return B58.encode(r.concat(checksum)); - } - - bitjs.transaction = function() { - var btrx = {}; - btrx.version = 2; //flochange look at this version - btrx.inputs = []; - btrx.outputs = []; - btrx.locktime = 0; - btrx.floData = ""; //flochange .. look at this - - - btrx.addinput = function(txid, index, scriptPubKey, sequence) { - var o = {}; - o.outpoint = { - 'hash': txid, - 'index': index - }; - //o.script = []; Signature and Public Key should be added after singning - o.script = Crypto.util.hexToBytes(scriptPubKey); //push previous output pubkey script - o.sequence = sequence || ((btrx.locktime == 0) ? 4294967295 : 0); - return this.inputs.push(o); - } - - btrx.addoutput = function(address, value) { - var o = {}; - var buf = []; - var addrDecoded = btrx.addressDecode(address); - o.value = new BigInteger('' + Math.round((value * 1) * 1e8), 10); - buf.push(118); //OP_DUP - buf.push(169); //OP_HASH160 - buf.push(addrDecoded.length); - buf = buf.concat(addrDecoded); // address in bytes - buf.push(136); //OP_EQUALVERIFY - buf.push(172); // OP_CHECKSIG - o.script = buf; - return this.outputs.push(o); - } - - - btrx.addflodata = function(txcomments) { // flochange - this whole function needs to be done - this.floData = txcomments; - return this.floData; //flochange .. returning the txcomments -- check if the function return will assign - } - - - // Only standard addresses - btrx.addressDecode = function(address) { - var bytes = B58.decode(address); - var front = bytes.slice(0, bytes.length - 4); - var back = bytes.slice(bytes.length - 4); - var checksum = Crypto.SHA256(Crypto.SHA256(front, { - asBytes: true - }), { - asBytes: true - }).slice(0, 4); - if (checksum + "" == back + "") { - return front.slice(1); - } - } - - /* generate the transaction hash to sign from a transaction input */ - btrx.transactionHash = function(index, sigHashType) { - - var clone = bitjs.clone(this); - var shType = sigHashType || 1; - - /* black out all other ins, except this one */ - for (var i = 0; i < clone.inputs.length; i++) { - if (index != i) { - clone.inputs[i].script = []; - } - } - - - if ((clone.inputs) && clone.inputs[index]) { - - /* SIGHASH : For more info on sig hashs see https://en.bitcoin.it/wiki/OP_CHECKSIG - and https://bitcoin.org/en/developer-guide#signature-hash-type */ - - if (shType == 1) { - //SIGHASH_ALL 0x01 - - } else if (shType == 2) { - //SIGHASH_NONE 0x02 - clone.outputs = []; - for (var i = 0; i < clone.inputs.length; i++) { - if (index != i) { - clone.inputs[i].sequence = 0; - } - } - - } else if (shType == 3) { - - //SIGHASH_SINGLE 0x03 - clone.outputs.length = index + 1; - - for (var i = 0; i < index; i++) { - clone.outputs[i].value = -1; - clone.outputs[i].script = []; - } - - for (var i = 0; i < clone.inputs.length; i++) { - if (index != i) { - clone.inputs[i].sequence = 0; - } - } - - } else if (shType >= 128) { - //SIGHASH_ANYONECANPAY 0x80 - clone.inputs = [clone.inputs[index]]; - - if (shType == 129) { - // SIGHASH_ALL + SIGHASH_ANYONECANPAY - - } else if (shType == 130) { - // SIGHASH_NONE + SIGHASH_ANYONECANPAY - clone.outputs = []; - - } else if (shType == 131) { - // SIGHASH_SINGLE + SIGHASH_ANYONECANPAY - clone.outputs.length = index + 1; - for (var i = 0; i < index; i++) { - clone.outputs[i].value = -1; - clone.outputs[i].script = []; - } - } - } - - var buffer = Crypto.util.hexToBytes(clone.serialize()); - buffer = buffer.concat(bitjs.numToBytes(parseInt(shType), 4)); - var hash = Crypto.SHA256(buffer, { - asBytes: true - }); - var r = Crypto.util.bytesToHex(Crypto.SHA256(hash, { - asBytes: true - })); - return r; - } else { - return false; - } - } - - /* generate a signature from a transaction hash */ - btrx.transactionSig = function(index, wif, sigHashType, txhash) { - - function serializeSig(r, s) { - var rBa = r.toByteArraySigned(); - var sBa = s.toByteArraySigned(); - - var sequence = []; - sequence.push(0x02); // INTEGER - sequence.push(rBa.length); - sequence = sequence.concat(rBa); - - sequence.push(0x02); // INTEGER - sequence.push(sBa.length); - sequence = sequence.concat(sBa); - - sequence.unshift(sequence.length); - sequence.unshift(0x30); // SEQUENCE - - return sequence; - } - - var shType = sigHashType || 1; - var hash = txhash || Crypto.util.hexToBytes(this.transactionHash(index, shType)); - - if (hash) { - var curve = EllipticCurve.getSECCurveByName("secp256k1"); - var key = bitjs.wif2privkey(wif); - var priv = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(key['privkey'])); - var n = curve.getN(); - var e = BigInteger.fromByteArrayUnsigned(hash); - var badrs = 0 - do { - var k = this.deterministicK(wif, hash, badrs); - var G = curve.getG(); - var Q = G.multiply(k); - var r = Q.getX().toBigInteger().mod(n); - var s = k.modInverse(n).multiply(e.add(priv.multiply(r))).mod(n); - badrs++ - } while (r.compareTo(BigInteger.ZERO) <= 0 || s.compareTo(BigInteger.ZERO) <= 0); - - // Force lower s values per BIP62 - var halfn = n.shiftRight(1); - if (s.compareTo(halfn) > 0) { - s = n.subtract(s); - }; - - var sig = serializeSig(r, s); - sig.push(parseInt(shType, 10)); - - return Crypto.util.bytesToHex(sig); - } else { - return false; - } - } - - // https://tools.ietf.org/html/rfc6979#section-3.2 - btrx.deterministicK = function(wif, hash, badrs) { - // if r or s were invalid when this function was used in signing, - // we do not want to actually compute r, s here for efficiency, so, - // we can increment badrs. explained at end of RFC 6979 section 3.2 - - // wif is b58check encoded wif privkey. - // hash is byte array of transaction digest. - // badrs is used only if the k resulted in bad r or s. - - // some necessary things out of the way for clarity. - badrs = badrs || 0; - var key = bitjs.wif2privkey(wif); - var x = Crypto.util.hexToBytes(key['privkey']) - var curve = EllipticCurve.getSECCurveByName("secp256k1"); - var N = curve.getN(); - - // Step: a - // hash is a byteArray of the message digest. so h1 == hash in our case - - // Step: b - var v = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1 - ]; - - // Step: c - var k = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0 - ]; - - // Step: d - k = Crypto.HMAC(Crypto.SHA256, v.concat([0]).concat(x).concat(hash), k, { - asBytes: true - }); - - // Step: e - v = Crypto.HMAC(Crypto.SHA256, v, k, { - asBytes: true - }); - - // Step: f - k = Crypto.HMAC(Crypto.SHA256, v.concat([1]).concat(x).concat(hash), k, { - asBytes: true - }); - - // Step: g - v = Crypto.HMAC(Crypto.SHA256, v, k, { - asBytes: true - }); - - // Step: h1 - var T = []; - - // Step: h2 (since we know tlen = qlen, just copy v to T.) - v = Crypto.HMAC(Crypto.SHA256, v, k, { - asBytes: true - }); - T = v; - - // Step: h3 - var KBigInt = BigInteger.fromByteArrayUnsigned(T); - - // loop if KBigInt is not in the range of [1, N-1] or if badrs needs incrementing. - var i = 0 - while (KBigInt.compareTo(N) >= 0 || KBigInt.compareTo(BigInteger.ZERO) <= 0 || i < - badrs) { - k = Crypto.HMAC(Crypto.SHA256, v.concat([0]), k, { - asBytes: true - }); - v = Crypto.HMAC(Crypto.SHA256, v, k, { - asBytes: true - }); - v = Crypto.HMAC(Crypto.SHA256, v, k, { - asBytes: true - }); - T = v; - KBigInt = BigInteger.fromByteArrayUnsigned(T); - i++ - }; - - return KBigInt; - }; - - /* sign a "standard" input */ - btrx.signinput = function(index, wif, sigHashType) { - var key = bitjs.wif2pubkey(wif); - var shType = sigHashType || 1; - var signature = this.transactionSig(index, wif, shType); - var buf = []; - var sigBytes = Crypto.util.hexToBytes(signature); - buf.push(sigBytes.length); - buf = buf.concat(sigBytes); - var pubKeyBytes = Crypto.util.hexToBytes(key['pubkey']); - buf.push(pubKeyBytes.length); - buf = buf.concat(pubKeyBytes); - this.inputs[index].script = buf; - return true; - } - - /* sign inputs */ - btrx.sign = function(wif, sigHashType) { - var shType = sigHashType || 1; - for (var i = 0; i < this.inputs.length; i++) { - this.signinput(i, wif, shType); - } - return this.serialize(); - } - - - /* serialize a transaction */ - btrx.serialize = function() { - var buffer = []; - buffer = buffer.concat(bitjs.numToBytes(parseInt(this.version), 4)); - - buffer = buffer.concat(bitjs.numToVarInt(this.inputs.length)); - for (var i = 0; i < this.inputs.length; i++) { - var txin = this.inputs[i]; - buffer = buffer.concat(Crypto.util.hexToBytes(txin.outpoint.hash).reverse()); - buffer = buffer.concat(bitjs.numToBytes(parseInt(txin.outpoint.index), 4)); - var scriptBytes = txin.script; - buffer = buffer.concat(bitjs.numToVarInt(scriptBytes.length)); - buffer = buffer.concat(scriptBytes); - buffer = buffer.concat(bitjs.numToBytes(parseInt(txin.sequence), 4)); - - } - buffer = buffer.concat(bitjs.numToVarInt(this.outputs.length)); - - for (var i = 0; i < this.outputs.length; i++) { - var txout = this.outputs[i]; - buffer = buffer.concat(bitjs.numToBytes(txout.value, 8)); - var scriptBytes = txout.script; - buffer = buffer.concat(bitjs.numToVarInt(scriptBytes.length)); - buffer = buffer.concat(scriptBytes); - } - - buffer = buffer.concat(bitjs.numToBytes(parseInt(this.locktime), 4)); - var flohex = ascii_to_hexa(this.floData); - var floDataCount = this.floData.length; - var floDataCountString; - //flochange -- creating unique data character count logic for floData. This string is prefixed before actual floData string in Raw Transaction - if (floDataCount < 16) { - floDataCountString = floDataCount.toString(16); - floDataCountString = "0" + floDataCountString; - } else if (floDataCount < 253) { - floDataCountString = floDataCount.toString(16); - } else if (floDataCount <= 1040) { - let floDataCountAdjusted = (floDataCount - 253) + parseInt("0xfd00fd"); - let floDataCountStringAdjusted = floDataCountAdjusted.toString(16); - floDataCountString = floDataCountStringAdjusted.substr(0, 2) + floDataCountStringAdjusted.substr(4, 2) + floDataCountStringAdjusted.substr(2, 2); - } else { - floDataCountString = "Character Limit Exceeded"; - } - - - return Crypto.util.bytesToHex(buffer) + floDataCountString + flohex; // flochange -- Addition of floDataCountString and floData in serialization - } - - - - return btrx; - - } - - bitjs.numToBytes = function(num, bytes) { - if (typeof bytes === "undefined") bytes = 8; - if (bytes == 0) { - return []; - } else if (num == -1) { - return Crypto.util.hexToBytes("ffffffffffffffff"); - } else { - return [num % 256].concat(bitjs.numToBytes(Math.floor(num / 256), bytes - 1)); - } - } - - bitjs.numToByteArray = function(num) { - if (num <= 256) { - return [num]; - } else { - return [num % 256].concat(bitjs.numToByteArray(Math.floor(num / 256))); - } - } - - bitjs.numToVarInt = function(num) { - if (num < 253) { - return [num]; - } else if (num < 65536) { - return [253].concat(bitjs.numToBytes(num, 2)); - } else if (num < 4294967296) { - return [254].concat(bitjs.numToBytes(num, 4)); - } else { - return [255].concat(bitjs.numToBytes(num, 8)); - } - } - - bitjs.bytesToNum = function(bytes) { - if (bytes.length == 0) return 0; - else return bytes[0] + 256 * bitjs.bytesToNum(bytes.slice(1)); - } - - /* clone an object */ - bitjs.clone = function(obj) { - if (obj == null || typeof(obj) != 'object') return obj; - var temp = new obj.constructor(); - - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - temp[key] = bitjs.clone(obj[key]); - } - } - return temp; - } - - var B58 = bitjs.Base58 = { - alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", - validRegex: /^[1-9A-HJ-NP-Za-km-z]+$/, - base: BigInteger.valueOf(58), - - /** - * Convert a byte array to a base58-encoded string. - * - * Written by Mike Hearn for BitcoinJ. - * Copyright (c) 2011 Google Inc. - * - * Ported to JavaScript by Stefan Thomas. - */ - encode: function(input) { - var bi = BigInteger.fromByteArrayUnsigned(input); - var chars = []; - - while (bi.compareTo(B58.base) >= 0) { - var mod = bi.mod(B58.base); - chars.unshift(B58.alphabet[mod.intValue()]); - bi = bi.subtract(mod).divide(B58.base); - } - chars.unshift(B58.alphabet[bi.intValue()]); - - // Convert leading zeros too. - for (var i = 0; i < input.length; i++) { - if (input[i] == 0x00) { - chars.unshift(B58.alphabet[0]); - } else break; - } - - return chars.join(''); - }, - - /** - * Convert a base58-encoded string to a byte array. - * - * Written by Mike Hearn for BitcoinJ. - * Copyright (c) 2011 Google Inc. - * - * Ported to JavaScript by Stefan Thomas. - */ - decode: function(input) { - var bi = BigInteger.valueOf(0); - var leadingZerosNum = 0; - for (var i = input.length - 1; i >= 0; i--) { - var alphaIndex = B58.alphabet.indexOf(input[i]); - if (alphaIndex < 0) { - throw "Invalid character"; - } - bi = bi.add(BigInteger.valueOf(alphaIndex) - .multiply(B58.base.pow(input.length - 1 - i))); - - // This counts leading zero bytes - if (input[i] == "1") leadingZerosNum++; - else leadingZerosNum = 0; - } - var bytes = bi.toByteArrayUnsigned(); - - // Add leading zeros - while (leadingZerosNum-- > 0) bytes.unshift(0); - - return bytes; - } - } - return bitjs; - - })(); - - //Bitcoin.js - (function() { - /* - Copyright (c) 2011 Stefan Thomas - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - var Bitcoin = GLOBAL.Bitcoin = {}; - - //https://raw.github.com/bitcoinjs/bitcoinjs-lib/c952aaeb3ee472e3776655b8ea07299ebed702c7/src/base58.js - var B58 = Bitcoin.Base58 = { - alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", - validRegex: /^[1-9A-HJ-NP-Za-km-z]+$/, - base: BigInteger.valueOf(58), - - /** - * Convert a byte array to a base58-encoded string. - * - * Written by Mike Hearn for BitcoinJ. - * Copyright (c) 2011 Google Inc. - * - * Ported to JavaScript by Stefan Thomas. - */ - encode: function(input) { - var bi = BigInteger.fromByteArrayUnsigned(input); - var chars = []; - - while (bi.compareTo(B58.base) >= 0) { - var mod = bi.mod(B58.base); - chars.unshift(B58.alphabet[mod.intValue()]); - bi = bi.subtract(mod).divide(B58.base); - } - chars.unshift(B58.alphabet[bi.intValue()]); - - // Convert leading zeros too. - for (var i = 0; i < input.length; i++) { - if (input[i] == 0x00) { - chars.unshift(B58.alphabet[0]); - } else break; - } - - return chars.join(''); - }, - - /** - * Convert a base58-encoded string to a byte array. - * - * Written by Mike Hearn for BitcoinJ. - * Copyright (c) 2011 Google Inc. - * - * Ported to JavaScript by Stefan Thomas. - */ - decode: function(input) { - var bi = BigInteger.valueOf(0); - var leadingZerosNum = 0; - for (var i = input.length - 1; i >= 0; i--) { - var alphaIndex = B58.alphabet.indexOf(input[i]); - if (alphaIndex < 0) { - throw "Invalid character"; - } - bi = bi.add(BigInteger.valueOf(alphaIndex) - .multiply(B58.base.pow(input.length - 1 - i))); - - // This counts leading zero bytes - if (input[i] == "1") leadingZerosNum++; - else leadingZerosNum = 0; - } - var bytes = bi.toByteArrayUnsigned(); - - // Add leading zeros - while (leadingZerosNum-- > 0) bytes.unshift(0); - - return bytes; - } - }; - - //https://raw.github.com/bitcoinjs/bitcoinjs-lib/09e8c6e184d6501a0c2c59d73ca64db5c0d3eb95/src/address.js - Bitcoin.Address = function(bytes) { - if (GLOBAL.cryptocoin == "FLO") - this.version = 0x23; // FLO mainnet public address - else if (GLOBAL.cryptocoin == "FLO_TEST") - this.version = 0x73; // FLO testnet public address - if ("string" == typeof bytes) { - bytes = Bitcoin.Address.decodeString(bytes, this.version); - } - this.hash = bytes; - }; - - Bitcoin.Address.networkVersion = 0x23; // (FLO mainnet 0x23, 35D), (Bitcoin Mainnet, 0x00, 0D) // *this has no effect * - - /** - * Serialize this object as a standard Bitcoin address. - * - * Returns the address as a base58-encoded string in the standardized format. - */ - Bitcoin.Address.prototype.toString = function(version = null) { - // Get a copy of the hash - var hash = this.hash.slice(0); - - // Version - hash.unshift(version !== null ? version : this.version); - var checksum = Crypto.SHA256(Crypto.SHA256(hash, { - asBytes: true - }), { - asBytes: true - }); - var bytes = hash.concat(checksum.slice(0, 4)); - return Bitcoin.Base58.encode(bytes); - }; - - Bitcoin.Address.prototype.getHashBase64 = function() { - return Crypto.util.bytesToBase64(this.hash); - }; - - /** - * Parse a Bitcoin address contained in a string. - */ - Bitcoin.Address.decodeString = function(string, version) { - var bytes = Bitcoin.Base58.decode(string); - var hash = bytes.slice(0, 21); - var checksum = Crypto.SHA256(Crypto.SHA256(hash, { - asBytes: true - }), { - asBytes: true - }); - - if (checksum[0] != bytes[21] || - checksum[1] != bytes[22] || - checksum[2] != bytes[23] || - checksum[3] != bytes[24]) { - throw "Checksum validation failed!"; - } - - if (version != hash.shift()) { - throw "Version " + hash.shift() + " not supported!"; - } - - return hash; - }; - //https://raw.github.com/bitcoinjs/bitcoinjs-lib/e90780d3d3b8fc0d027d2bcb38b80479902f223e/src/ecdsa.js - Bitcoin.ECDSA = (function() { - var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); - var rng = new SecureRandom(); - - var P_OVER_FOUR = null; - - function implShamirsTrick(P, k, Q, l) { - var m = Math.max(k.bitLength(), l.bitLength()); - var Z = P.add2D(Q); - var R = P.curve.getInfinity(); - - for (var i = m - 1; i >= 0; --i) { - R = R.twice2D(); - - R.z = BigInteger.ONE; - - if (k.testBit(i)) { - if (l.testBit(i)) { - R = R.add2D(Z); - } else { - R = R.add2D(P); - } - } else { - if (l.testBit(i)) { - R = R.add2D(Q); - } - } - } - - return R; - }; - - var ECDSA = { - getBigRandom: function(limit) { - return new BigInteger(limit.bitLength(), rng) - .mod(limit.subtract(BigInteger.ONE)) - .add(BigInteger.ONE); - }, - sign: function(hash, priv) { - var d = priv; - var n = ecparams.getN(); - var e = BigInteger.fromByteArrayUnsigned(hash); - - do { - var k = ECDSA.getBigRandom(n); - var G = ecparams.getG(); - var Q = G.multiply(k); - var r = Q.getX().toBigInteger().mod(n); - } while (r.compareTo(BigInteger.ZERO) <= 0); - - var s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n); - - return ECDSA.serializeSig(r, s); - }, - - verify: function(hash, sig, pubkey) { - var r, s; - if (Bitcoin.Util.isArray(sig)) { - var obj = ECDSA.parseSig(sig); - r = obj.r; - s = obj.s; - } else if ("object" === typeof sig && sig.r && sig.s) { - r = sig.r; - s = sig.s; - } else { - throw "Invalid value for signature"; - } - - var Q; - if (pubkey instanceof EllipticCurve.PointFp) { - Q = pubkey; - } else if (Bitcoin.Util.isArray(pubkey)) { - Q = EllipticCurve.PointFp.decodeFrom(ecparams.getCurve(), pubkey); - } else { - throw "Invalid format for pubkey value, must be byte array or ec.PointFp"; - } - var e = BigInteger.fromByteArrayUnsigned(hash); - - return ECDSA.verifyRaw(e, r, s, Q); - }, - - verifyRaw: function(e, r, s, Q) { - var n = ecparams.getN(); - var G = ecparams.getG(); - - if (r.compareTo(BigInteger.ONE) < 0 || - r.compareTo(n) >= 0) - return false; - - if (s.compareTo(BigInteger.ONE) < 0 || - s.compareTo(n) >= 0) - return false; - - var c = s.modInverse(n); - - var u1 = e.multiply(c).mod(n); - var u2 = r.multiply(c).mod(n); - - // TODO(!!!): For some reason Shamir's trick isn't working with - // signed message verification!? Probably an implementation - // error! - //var point = implShamirsTrick(G, u1, Q, u2); - var point = G.multiply(u1).add(Q.multiply(u2)); - - var v = point.getX().toBigInteger().mod(n); - - return v.equals(r); - }, - - /** - * Serialize a signature into DER format. - * - * Takes two BigIntegers representing r and s and returns a byte array. - */ - serializeSig: function(r, s) { - var rBa = r.toByteArraySigned(); - var sBa = s.toByteArraySigned(); - - var sequence = []; - sequence.push(0x02); // INTEGER - sequence.push(rBa.length); - sequence = sequence.concat(rBa); - - sequence.push(0x02); // INTEGER - sequence.push(sBa.length); - sequence = sequence.concat(sBa); - - sequence.unshift(sequence.length); - sequence.unshift(0x30); // SEQUENCE - - return sequence; - }, - - /** - * Parses a byte array containing a DER-encoded signature. - * - * This function will return an object of the form: - * - * { - * r: BigInteger, - * s: BigInteger - * } - */ - parseSig: function(sig) { - var cursor; - if (sig[0] != 0x30) - throw new Error("Signature not a valid DERSequence"); - - cursor = 2; - if (sig[cursor] != 0x02) - throw new Error("First element in signature must be a DERInteger");; - var rBa = sig.slice(cursor + 2, cursor + 2 + sig[cursor + 1]); - - cursor += 2 + sig[cursor + 1]; - if (sig[cursor] != 0x02) - throw new Error("Second element in signature must be a DERInteger"); - var sBa = sig.slice(cursor + 2, cursor + 2 + sig[cursor + 1]); - - cursor += 2 + sig[cursor + 1]; - - //if (cursor != sig.length) - // throw new Error("Extra bytes in signature"); - - var r = BigInteger.fromByteArrayUnsigned(rBa); - var s = BigInteger.fromByteArrayUnsigned(sBa); - - return { - r: r, - s: s - }; - }, - - parseSigCompact: function(sig) { - if (sig.length !== 65) { - throw "Signature has the wrong length"; - } - - // Signature is prefixed with a type byte storing three bits of - // information. - var i = sig[0] - 27; - if (i < 0 || i > 7) { - throw "Invalid signature type"; - } - - var n = ecparams.getN(); - var r = BigInteger.fromByteArrayUnsigned(sig.slice(1, 33)).mod(n); - var s = BigInteger.fromByteArrayUnsigned(sig.slice(33, 65)).mod(n); - - return { - r: r, - s: s, - i: i - }; - }, - - /** - * Recover a public key from a signature. - * - * See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public - * Key Recovery Operation". - * - * http://www.secg.org/download/aid-780/sec1-v2.pdf - */ - recoverPubKey: function(r, s, hash, i) { - // The recovery parameter i has two bits. - i = i & 3; - - // The less significant bit specifies whether the y coordinate - // of the compressed point is even or not. - var isYEven = i & 1; - - // The more significant bit specifies whether we should use the - // first or second candidate key. - var isSecondKey = i >> 1; - - var n = ecparams.getN(); - var G = ecparams.getG(); - var curve = ecparams.getCurve(); - var p = curve.getQ(); - var a = curve.getA().toBigInteger(); - var b = curve.getB().toBigInteger(); - - // We precalculate (p + 1) / 4 where p is if the field order - if (!P_OVER_FOUR) { - P_OVER_FOUR = p.add(BigInteger.ONE).divide(BigInteger.valueOf(4)); - } - - // 1.1 Compute x - var x = isSecondKey ? r.add(n) : r; - - // 1.3 Convert x to point - var alpha = x.multiply(x).multiply(x).add(a.multiply(x)).add(b).mod(p); - var beta = alpha.modPow(P_OVER_FOUR, p); - - var xorOdd = beta.isEven() ? (i % 2) : ((i + 1) % 2); - // If beta is even, but y isn't or vice versa, then convert it, - // otherwise we're done and y == beta. - var y = (beta.isEven() ? !isYEven : isYEven) ? beta : p.subtract(beta); - - // 1.4 Check that nR is at infinity - var R = new EllipticCurve.PointFp(curve, - curve.fromBigInteger(x), - curve.fromBigInteger(y)); - R.validate(); - - // 1.5 Compute e from M - var e = BigInteger.fromByteArrayUnsigned(hash); - var eNeg = BigInteger.ZERO.subtract(e).mod(n); - - // 1.6 Compute Q = r^-1 (sR - eG) - var rInv = r.modInverse(n); - var Q = implShamirsTrick(R, s, G, eNeg).multiply(rInv); - - Q.validate(); - if (!ECDSA.verifyRaw(e, r, s, Q)) { - throw "Pubkey recovery unsuccessful"; - } - - var pubKey = new Bitcoin.ECKey(); - pubKey.pub = Q; - return pubKey; - }, - - /** - * Calculate pubkey extraction parameter. - * - * When extracting a pubkey from a signature, we have to - * distinguish four different cases. Rather than putting this - * burden on the verifier, Bitcoin includes a 2-bit value with the - * signature. - * - * This function simply tries all four cases and returns the value - * that resulted in a successful pubkey recovery. - */ - calcPubkeyRecoveryParam: function(address, r, s, hash) { - for (var i = 0; i < 4; i++) { - try { - var pubkey = Bitcoin.ECDSA.recoverPubKey(r, s, hash, i); - if (pubkey.getBitcoinAddress().toString() == address) { - return i; - } - } catch (e) {} - } - throw "Unable to find valid recovery factor"; - } - }; - - return ECDSA; - })(); - Bitcoin.KeyPool = (function() { - var KeyPool = function() { - this.keyArray = []; - - this.push = function(item) { - if (item == null || item.priv == null) return; - var doAdd = true; - // prevent duplicates from being added to the array - for (var index in this.keyArray) { - var currentItem = this.keyArray[index]; - if (currentItem != null && currentItem.priv != null && item.getBitcoinAddress() == currentItem.getBitcoinAddress()) { - doAdd = false; - break; - } - } - if (doAdd) this.keyArray.push(item); - }; - - this.reset = function() { - this.keyArray = []; - }; - - this.getArray = function() { - // copy array - return this.keyArray.slice(0); - }; - - this.setArray = function(ka) { - this.keyArray = ka; - }; - - this.length = function() { - return this.keyArray.length; - }; - - this.toString = function() { - var keyPoolString = "# = " + this.length() + "\n"; - var pool = this.getArray(); - for (var index in pool) { - var item = pool[index]; - if (Bitcoin.Util.hasMethods(item, 'getBitcoinAddress', 'toString')) { - if (item != null) { - keyPoolString += "\"" + item.getBitcoinAddress() + "\"" + ", \"" + item.toString("wif") + "\"\n"; - } - } - } - - return keyPoolString; - }; - - return this; - }; - - return new KeyPool(); - })(); - - Bitcoin.Bip38Key = (function() { - var Bip38 = function(address, encryptedKey) { - this.address = address; - this.priv = encryptedKey; - }; - - Bip38.prototype.getBitcoinAddress = function() { - return this.address; - }; - - Bip38.prototype.toString = function() { - return this.priv; - }; - - return Bip38; - })(); - - //https://raw.github.com/pointbiz/bitcoinjs-lib/9b2f94a028a7bc9bed94e0722563e9ff1d8e8db8/src/eckey.js - Bitcoin.ECKey = (function() { - var ECDSA = Bitcoin.ECDSA; - var KeyPool = Bitcoin.KeyPool; - var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); - - var ECKey = function(input) { - if (!input) { - // Generate new key - var n = ecparams.getN(); - this.priv = ECDSA.getBigRandom(n); - } else if (input instanceof BigInteger) { - // Input is a private key value - this.priv = input; - } else if (Bitcoin.Util.isArray(input)) { - // Prepend zero byte to prevent interpretation as negative integer - this.priv = BigInteger.fromByteArrayUnsigned(input); - } else if ("string" == typeof input) { - var bytes = null; - try { - - // This part is edited for FLO. FLO WIF are always compressed WIF (length of 52). - if ((/^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{52}$/.test(input))) { - bytes = ECKey.decodeCompressedWalletImportFormat(input); - this.compressed = true; - } else if (ECKey.isHexFormat(input)) { - bytes = Crypto.util.hexToBytes(input); - } - - - /* - if (ECKey.isWalletImportFormat(input)) { - bytes = ECKey.decodeWalletImportFormat(input); - } else if (ECKey.isCompressedWalletImportFormat(input)) { - bytes = ECKey.decodeCompressedWalletImportFormat(input); - this.compressed = true; - } else if (ECKey.isMiniFormat(input)) { - bytes = Crypto.SHA256(input, { asBytes: true }); - } else if (ECKey.isHexFormat(input)) { - bytes = Crypto.util.hexToBytes(input); - } else if (ECKey.isBase64Format(input)) { - bytes = Crypto.util.base64ToBytes(input); - } - */ - } catch (exc1) { - this.setError(exc1); - } - - if (ECKey.isBase6Format(input)) { - this.priv = new BigInteger(input, 6); - } else if (bytes == null || bytes.length != 32) { - this.priv = null; - } else { - // Prepend zero byte to prevent interpretation as negative integer - this.priv = BigInteger.fromByteArrayUnsigned(bytes); - } - } - - this.compressed = (this.compressed == undefined) ? !!ECKey.compressByDefault : this.compressed; - try { - // check not zero - if (this.priv != null && BigInteger.ZERO.compareTo(this.priv) == 0) this.setError("Error: BigInteger equal to zero."); - // valid range [0x1, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140]) - var hexKeyRangeLimit = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140"; - var rangeLimitBytes = Crypto.util.hexToBytes(hexKeyRangeLimit); - var limitBigInt = BigInteger.fromByteArrayUnsigned(rangeLimitBytes); - if (this.priv != null && limitBigInt.compareTo(this.priv) < 0) this.setError("Error: BigInteger outside of curve range.") - - if (this.priv != null) { - KeyPool.push(this); - } - } catch (exc2) { - this.setError(exc2); - } - }; - - if (GLOBAL.cryptocoin == "FLO") - ECKey.privateKeyPrefix = 0xA3; //(Bitcoin mainnet 0x80 testnet 0xEF) (FLO mainnet 0xA3 163 D) - else if (GLOBAL.cryptocoin == "FLO_TEST") - ECKey.privateKeyPrefix = 0xEF; //FLO testnet - - /** - * Whether public keys should be returned compressed by default. - */ - ECKey.compressByDefault = false; - - /** - * Set whether the public key should be returned compressed or not. - */ - ECKey.prototype.setError = function(err) { - this.error = err; - this.priv = null; - return this; - }; - - /** - * Set whether the public key should be returned compressed or not. - */ - ECKey.prototype.setCompressed = function(v) { - this.compressed = !!v; - if (this.pubPoint) this.pubPoint.compressed = this.compressed; - return this; - }; - - /* - * Return public key as a byte array in DER encoding - */ - ECKey.prototype.getPub = function() { - if (this.compressed) { - if (this.pubComp) return this.pubComp; - return this.pubComp = this.getPubPoint().getEncoded(1); - } else { - if (this.pubUncomp) return this.pubUncomp; - return this.pubUncomp = this.getPubPoint().getEncoded(0); - } - }; - - /** - * Return public point as ECPoint object. - */ - ECKey.prototype.getPubPoint = function() { - if (!this.pubPoint) { - this.pubPoint = ecparams.getG().multiply(this.priv); - this.pubPoint.compressed = this.compressed; - } - return this.pubPoint; - }; - - ECKey.prototype.getPubKeyHex = function() { - if (this.compressed) { - if (this.pubKeyHexComp) return this.pubKeyHexComp; - return this.pubKeyHexComp = Crypto.util.bytesToHex(this.getPub()).toString().toUpperCase(); - } else { - if (this.pubKeyHexUncomp) return this.pubKeyHexUncomp; - return this.pubKeyHexUncomp = Crypto.util.bytesToHex(this.getPub()).toString().toUpperCase(); - } - }; - - /** - * Get the pubKeyHash for this key. - * - * This is calculated as RIPE160(SHA256([encoded pubkey])) and returned as - * a byte array. - */ - ECKey.prototype.getPubKeyHash = function() { - if (this.compressed) { - if (this.pubKeyHashComp) return this.pubKeyHashComp; - return this.pubKeyHashComp = Bitcoin.Util.sha256ripe160(this.getPub()); - } else { - if (this.pubKeyHashUncomp) return this.pubKeyHashUncomp; - return this.pubKeyHashUncomp = Bitcoin.Util.sha256ripe160(this.getPub()); - } - }; - - ECKey.prototype.getBitcoinAddress = function() { - var hash = this.getPubKeyHash(); - var addr = new Bitcoin.Address(hash); - return addr.toString(); - }; - - /* - * Takes a public point as a hex string or byte array - */ - ECKey.prototype.setPub = function(pub) { - // byte array - if (Bitcoin.Util.isArray(pub)) { - pub = Crypto.util.bytesToHex(pub).toString().toUpperCase(); - } - var ecPoint = ecparams.getCurve().decodePointHex(pub); - this.setCompressed(ecPoint.compressed); - this.pubPoint = ecPoint; - return this; - }; - - // Sipa Private Key Wallet Import Format - ECKey.prototype.getBitcoinWalletImportFormat = function() { - var bytes = this.getBitcoinPrivateKeyByteArray(); - if (bytes == null) return ""; - bytes.unshift(ECKey.privateKeyPrefix); // prepend 0x80 byte - if (this.compressed) bytes.push(0x01); // append 0x01 byte for compressed format - var checksum = Crypto.SHA256(Crypto.SHA256(bytes, { - asBytes: true - }), { - asBytes: true - }); - bytes = bytes.concat(checksum.slice(0, 4)); - var privWif = Bitcoin.Base58.encode(bytes); - return privWif; - }; - - // Private Key Hex Format - ECKey.prototype.getBitcoinHexFormat = function() { - return Crypto.util.bytesToHex(this.getBitcoinPrivateKeyByteArray()).toString().toUpperCase(); - }; - - // Private Key Base64 Format - ECKey.prototype.getBitcoinBase64Format = function() { - return Crypto.util.bytesToBase64(this.getBitcoinPrivateKeyByteArray()); - }; - - ECKey.prototype.getBitcoinPrivateKeyByteArray = function() { - if (this.priv == null) return null; - // Get a copy of private key as a byte array - var bytes = this.priv.toByteArrayUnsigned(); - // zero pad if private key is less than 32 bytes - while (bytes.length < 32) bytes.unshift(0x00); - return bytes; - }; - - ECKey.prototype.toString = function(format) { - format = format || ""; - if (format.toString().toLowerCase() == "base64" || format.toString().toLowerCase() == "b64") { - return this.getBitcoinBase64Format(); - } - // Wallet Import Format - else if (format.toString().toLowerCase() == "wif") { - return this.getBitcoinWalletImportFormat(); - } else { - return this.getBitcoinHexFormat(); - } - }; - - ECKey.prototype.sign = function(hash) { - return ECDSA.sign(hash, this.priv); - }; - - ECKey.prototype.verify = function(hash, sig) { - return ECDSA.verify(hash, sig, this.getPub()); - }; - - /** - * Parse a wallet import format private key contained in a string. - */ - ECKey.decodeWalletImportFormat = function(privStr) { - var bytes = Bitcoin.Base58.decode(privStr); - var hash = bytes.slice(0, 33); - var checksum = Crypto.SHA256(Crypto.SHA256(hash, { - asBytes: true - }), { - asBytes: true - }); - if (checksum[0] != bytes[33] || - checksum[1] != bytes[34] || - checksum[2] != bytes[35] || - checksum[3] != bytes[36]) { - throw "Checksum validation failed!"; - - } - var version = hash.shift(); - /* - if (version != ECKey.privateKeyPrefix) { - throw "Version " + version + " not supported!"; - } - */ - return hash; - }; - - /** - * Parse a compressed wallet import format private key contained in a string. - */ - ECKey.decodeCompressedWalletImportFormat = function(privStr) { - var bytes = Bitcoin.Base58.decode(privStr); - var hash = bytes.slice(0, 34); - var checksum = Crypto.SHA256(Crypto.SHA256(hash, { - asBytes: true - }), { - asBytes: true - }); - if (checksum[0] != bytes[34] || - checksum[1] != bytes[35] || - checksum[2] != bytes[36] || - checksum[3] != bytes[37]) { - throw "Checksum validation failed!"; - } - var version = hash.shift(); - /* - if (version != ECKey.privateKeyPrefix) { - throw "Version " + version + " not supported!"; - } - */ - hash.pop(); - return hash; - }; - - // 64 characters [0-9A-F] - ECKey.isHexFormat = function(key) { - key = key.toString(); - return /^[A-Fa-f0-9]{64}$/.test(key); - }; - - // 51 characters base58, always starts with a '5' - ECKey.isWalletImportFormat = function(key) { - key = key.toString(); - return (ECKey.privateKeyPrefix == 0x80) ? - (/^5[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{50}$/.test(key)) : - (/^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{50}$/.test(key)); - }; - - // 52 characters base58 - ECKey.isCompressedWalletImportFormat = function(key) { - key = key.toString(); - return (ECKey.privateKeyPrefix == 0x80) ? - (/^[LK][123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(key)) : - (/^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(key)); - }; - - // 44 characters - ECKey.isBase64Format = function(key) { - key = key.toString(); - return (/^[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789=+\/]{44}$/.test(key)); - }; - - // 99 characters, 1=1, if using dice convert 6 to 0 - ECKey.isBase6Format = function(key) { - key = key.toString(); - return (/^[012345]{99}$/.test(key)); - }; - - // 22, 26 or 30 characters, always starts with an 'S' - ECKey.isMiniFormat = function(key) { - key = key.toString(); - var validChars22 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21}$/.test(key); - var validChars26 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{25}$/.test(key); - var validChars30 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{29}$/.test(key); - var testBytes = Crypto.SHA256(key + "?", { - asBytes: true - }); - - return ((testBytes[0] === 0x00 || testBytes[0] === 0x01) && (validChars22 || validChars26 || validChars30)); - }; - - return ECKey; - })(); - //https://raw.github.com/bitcoinjs/bitcoinjs-lib/09e8c6e184d6501a0c2c59d73ca64db5c0d3eb95/src/util.js - // Bitcoin utility functions - Bitcoin.Util = { - /** - * Cross-browser compatibility version of Array.isArray. - */ - isArray: Array.isArray || function(o) { - return Object.prototype.toString.call(o) === '[object Array]'; - }, - /** - * Create an array of a certain length filled with a specific value. - */ - makeFilledArray: function(len, val) { - var array = []; - var i = 0; - while (i < len) { - array[i++] = val; - } - return array; - }, - /** - * Turn an integer into a "var_int". - * - * "var_int" is a variable length integer used by Bitcoin's binary format. - * - * Returns a byte array. - */ - numToVarInt: function(i) { - if (i < 0xfd) { - // unsigned char - return [i]; - } else if (i <= 1 << 16) { - // unsigned short (LE) - return [0xfd, i >>> 8, i & 255]; - } else if (i <= 1 << 32) { - // unsigned int (LE) - return [0xfe].concat(Crypto.util.wordsToBytes([i])); - } else { - // unsigned long long (LE) - return [0xff].concat(Crypto.util.wordsToBytes([i >>> 32, i])); - } - }, - /** - * Parse a Bitcoin value byte array, returning a BigInteger. - */ - valueToBigInt: function(valueBuffer) { - if (valueBuffer instanceof BigInteger) return valueBuffer; - - // Prepend zero byte to prevent interpretation as negative integer - return BigInteger.fromByteArrayUnsigned(valueBuffer); - }, - /** - * Format a Bitcoin value as a string. - * - * Takes a BigInteger or byte-array and returns that amount of Bitcoins in a - * nice standard formatting. - * - * Examples: - * 12.3555 - * 0.1234 - * 900.99998888 - * 34.00 - */ - formatValue: function(valueBuffer) { - var value = this.valueToBigInt(valueBuffer).toString(); - var integerPart = value.length > 8 ? value.substr(0, value.length - 8) : '0'; - var decimalPart = value.length > 8 ? value.substr(value.length - 8) : value; - while (decimalPart.length < 8) decimalPart = "0" + decimalPart; - decimalPart = decimalPart.replace(/0*$/, ''); - while (decimalPart.length < 2) decimalPart += "0"; - return integerPart + "." + decimalPart; - }, - /** - * Parse a floating point string as a Bitcoin value. - * - * Keep in mind that parsing user input is messy. You should always display - * the parsed value back to the user to make sure we understood his input - * correctly. - */ - parseValue: function(valueString) { - // TODO: Detect other number formats (e.g. comma as decimal separator) - var valueComp = valueString.split('.'); - var integralPart = valueComp[0]; - var fractionalPart = valueComp[1] || "0"; - while (fractionalPart.length < 8) fractionalPart += "0"; - fractionalPart = fractionalPart.replace(/^0+/g, ''); - var value = BigInteger.valueOf(parseInt(integralPart)); - value = value.multiply(BigInteger.valueOf(100000000)); - value = value.add(BigInteger.valueOf(parseInt(fractionalPart))); - return value; - }, - /** - * Calculate RIPEMD160(SHA256(data)). - * - * Takes an arbitrary byte array as inputs and returns the hash as a byte - * array. - */ - sha256ripe160: function(data) { - return ripemd160(Crypto.SHA256(data, { - asBytes: true - }), { - asBytes: true - }); - }, - // double sha256 - dsha256: function(data) { - return Crypto.SHA256(Crypto.SHA256(data, { - asBytes: true - }), { - asBytes: true - }); - }, - // duck typing method - hasMethods: function(obj /*, method list as strings */ ) { - var i = 1, - methodName; - while ((methodName = arguments[i++])) { - if (typeof obj[methodName] != 'function') { - return false; - } - } - return true; - } - }; - })(); - - //ellipticCurveEncryption.js - (function() { - (function(ellipticCurveType) { - - //Defining Elliptic Encryption Object - var ellipticEncryption = GLOBAL.ellipticCurveEncryption = function() {}; - - ellipticEncryption.rng = new SecureRandom(); - - ellipticEncryption.getCurveParameters = function(curveName) { - - //Default is secp256k1 - curveName = typeof curveName !== 'undefined' ? curveName : "secp256k1"; - - var c = EllipticCurve.getSECCurveByName(curveName); - var curveDetails = { - Q: "", - A: "", - B: "", - GX: "", - GY: "", - N: "" - }; - - curveDetails.Q = c.getCurve().getQ().toString(); - curveDetails.A = c.getCurve().getA().toBigInteger().toString(); - curveDetails.B = c.getCurve().getB().toBigInteger().toString(); - curveDetails.GX = c.getG().getX().toBigInteger().toString(); - curveDetails.GY = c.getG().getY().toBigInteger().toString(); - curveDetails.N = c.getN().toString(); - - return curveDetails; - - } - - ellipticEncryption.selectedCurve = ellipticEncryption.getCurveParameters(ellipticCurveType); - - ellipticEncryption.get_curve = function() { - return new EllipticCurve.CurveFp(new BigInteger(this.selectedCurve.Q), - new BigInteger(this.selectedCurve.A), - new BigInteger(this.selectedCurve.B)); - } - - ellipticEncryption.get_G = function(curve) { - return new EllipticCurve.PointFp(curve, - curve.fromBigInteger(new BigInteger(this.selectedCurve.GX)), - curve.fromBigInteger(new BigInteger(this.selectedCurve.GY))); - } - - ellipticEncryption.pick_rand = function() { - var n = new BigInteger(this.selectedCurve.N); - var n1 = n.subtract(BigInteger.ONE); - var r = new BigInteger(n.bitLength(), this.rng); - return r.mod(n1).add(BigInteger.ONE); - } - - ellipticEncryption.senderRandom = function() { - var r = this.pick_rand(); - return r.toString(); - }; - - ellipticEncryption.receiverRandom = function() { - - //This is receivers private key. For now we will use random. CHANGE IT LATER - var r = this.pick_rand(); - return r.toString(); - } - - ellipticEncryption.senderPublicString = function(senderPrivateKey) { - - var senderKeyECData = {}; - - var curve = this.get_curve(); - var G = this.get_G(curve); - var a = new BigInteger(senderPrivateKey); - var P = G.multiply(a); - senderKeyECData.XValuePublicString = P.getX().toBigInteger().toString(); - senderKeyECData.YValuePublicString = P.getY().toBigInteger().toString(); - - return senderKeyECData; - } - - //In real life ellipticEncryption.receiverPublicString is the public key of the receiver. - //you don't have to run receiverRandom and the bottom function - ellipticEncryption.receiverPublicString = function(receiverPublicKey) { - - var receiverKeyECData = {}; - - var curve = this.get_curve(); - var G = this.get_G(curve); - var a = new BigInteger(receiverPublicKey); - var P = G.multiply(a); - receiverKeyECData.XValuePublicString = P.getX().toBigInteger().toString(); - receiverKeyECData.YValuePublicString = P.getY().toBigInteger().toString(); - - return receiverKeyECData; - } - - ellipticEncryption.senderSharedKeyDerivation = function(receiverPublicStringXValue, - receiverPublicStringYValue, senderPrivateKey) { - - var senderDerivedKey = {}; - var curve = this.get_curve(); - var P = new EllipticCurve.PointFp(curve, - curve.fromBigInteger(new BigInteger(receiverPublicStringXValue)), - curve.fromBigInteger(new BigInteger(receiverPublicStringYValue))); - var a = new BigInteger(senderPrivateKey); - var S = P.multiply(a); - - senderDerivedKey.XValue = S.getX().toBigInteger().toString(); - senderDerivedKey.YValue = S.getY().toBigInteger().toString(); - - return senderDerivedKey; - } - - ellipticEncryption.receiverSharedKeyDerivation = function(senderPublicStringXValue, - senderPublicStringYValue, receiverPrivateKey) { - - var receiverDerivedKey = {}; - var curve = this.get_curve(); - var P = new EllipticCurve.PointFp(curve, - curve.fromBigInteger(new BigInteger(senderPublicStringXValue)), - curve.fromBigInteger(new BigInteger(senderPublicStringYValue))); - var a = new BigInteger(receiverPrivateKey); - var S = P.multiply(a); - - receiverDerivedKey.XValue = S.getX().toBigInteger().toString(); - receiverDerivedKey.YValue = S.getY().toBigInteger().toString(); - - return receiverDerivedKey; - } - - })("secp256k1"); - })(); - - //sha512.js - (function() { - /* - A JavaScript implementation of the SHA family of hashes, as defined in FIPS - PUB 180-2 as well as the corresponding HMAC implementation as defined in - FIPS PUB 198a - - Copyright Brian Turek 2008-2012 - Distributed under the BSD License - See http://caligatio.github.com/jsSHA/ for more information - - Several functions taken from Paul Johnson - */ - function n(a) { - throw a; - } - var q = null; - - function s(a, b) { - this.a = a; - this.b = b - } - - function u(a, b) { - var d = [], - h = (1 << b) - 1, - f = a.length * b, - g; - for (g = 0; g < f; g += b) d[g >>> 5] |= (a.charCodeAt(g / b) & h) << 32 - b - g % 32; - return { - value: d, - binLen: f - } - } - - function x(a) { - var b = [], - d = a.length, - h, f; - 0 !== d % 2 && n("String of HEX type must be in byte increments"); - for (h = 0; h < d; h += 2) f = parseInt(a.substr(h, 2), 16), isNaN(f) && n("String of HEX type contains invalid characters"), b[h >>> 3] |= f << 24 - 4 * (h % 8); - return { - value: b, - binLen: 4 * d - } - } - - function B(a) { - var b = [], - d = 0, - h, f, g, k, m; - 1 === a.search(/^[a-zA-Z0-9=+\/]+$/) && n("Invalid character in base-64 string"); - h = a.indexOf("="); - a = a.replace(/\=/g, ""); - 1 !== h && h < a.length && n("Invalid '=' found in base-64 string"); - for (f = 0; f < a.length; f += 4) { - m = a.substr(f, 4); - for (g = k = 0; g < m.length; g += 1) h = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(m[g]), k |= h << 18 - 6 * g; - for (g = 0; g < m.length - 1; g += 1) b[d >> 2] |= (k >>> 16 - 8 * g & 255) << 24 - 8 * (d % 4), d += 1 - } - return { - value: b, - binLen: 8 * d - } - } - - function E(a, b) { - var d = "", - h = 4 * a.length, - f, g; - for (f = 0; f < h; f += 1) g = a[f >>> 2] >>> 8 * (3 - f % 4), d += "0123456789abcdef".charAt(g >>> 4 & 15) + "0123456789abcdef".charAt(g & 15); - return b.outputUpper ? d.toUpperCase() : d - } - - function F(a, b) { - var d = "", - h = 4 * a.length, - f, g, k; - for (f = 0; f < h; f += 3) { - k = (a[f >>> 2] >>> 8 * (3 - f % 4) & 255) << 16 | (a[f + 1 >>> 2] >>> 8 * (3 - (f + 1) % 4) & 255) << 8 | a[f + 2 >>> 2] >>> 8 * (3 - (f + 2) % 4) & 255; - for (g = 0; 4 > g; g += 1) d = 8 * f + 6 * g <= 32 * a.length ? d + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(k >>> 6 * (3 - g) & 63) : d + b.b64Pad - } - return d - } - - function G(a) { - var b = { - outputUpper: !1, - b64Pad: "=" - }; - try { - a.hasOwnProperty("outputUpper") && (b.outputUpper = a.outputUpper), a.hasOwnProperty("b64Pad") && (b.b64Pad = a.b64Pad) - } catch (d) {} - "boolean" !== typeof b.outputUpper && n("Invalid outputUpper formatting option"); - "string" !== typeof b.b64Pad && n("Invalid b64Pad formatting option"); - return b - } - - function H(a, b) { - var d = q, - d = new s(a.a, a.b); - return d = 32 >= b ? new s(d.a >>> b | d.b << 32 - b & 4294967295, d.b >>> b | d.a << 32 - b & 4294967295) : new s(d.b >>> b - 32 | d.a << 64 - b & 4294967295, d.a >>> b - 32 | d.b << 64 - b & 4294967295) - } - - function I(a, b) { - var d = q; - return d = 32 >= b ? new s(a.a >>> b, a.b >>> b | a.a << 32 - b & 4294967295) : new s(0, a.a >>> b - 32) - } - - function J(a, b, d) { - return new s(a.a & b.a ^ ~a.a & d.a, a.b & b.b ^ ~a.b & d.b) - } - - function U(a, b, d) { - return new s(a.a & b.a ^ a.a & d.a ^ b.a & d.a, a.b & b.b ^ a.b & d.b ^ b.b & d.b) - } - - function V(a) { - var b = H(a, 28), - d = H(a, 34); - a = H(a, 39); - return new s(b.a ^ d.a ^ a.a, b.b ^ d.b ^ a.b) - } - - function W(a) { - var b = H(a, 14), - d = H(a, 18); - a = H(a, 41); - return new s(b.a ^ d.a ^ a.a, b.b ^ d.b ^ a.b) - } - - function X(a) { - var b = H(a, 1), - d = H(a, 8); - a = I(a, 7); - return new s(b.a ^ d.a ^ a.a, b.b ^ d.b ^ a.b) - } - - function Y(a) { - var b = H(a, 19), - d = H(a, 61); - a = I(a, 6); - return new s(b.a ^ d.a ^ a.a, b.b ^ d.b ^ a.b) - } - - function Z(a, b) { - var d, h, f; - d = (a.b & 65535) + (b.b & 65535); - h = (a.b >>> 16) + (b.b >>> 16) + (d >>> 16); - f = (h & 65535) << 16 | d & 65535; - d = (a.a & 65535) + (b.a & 65535) + (h >>> 16); - h = (a.a >>> 16) + (b.a >>> 16) + (d >>> 16); - return new s((h & 65535) << 16 | d & 65535, f) - } - - function aa(a, b, d, h) { - var f, g, k; - f = (a.b & 65535) + (b.b & 65535) + (d.b & 65535) + (h.b & 65535); - g = (a.b >>> 16) + (b.b >>> 16) + (d.b >>> 16) + (h.b >>> 16) + (f >>> 16); - k = (g & 65535) << 16 | f & 65535; - f = (a.a & 65535) + (b.a & 65535) + (d.a & 65535) + (h.a & 65535) + (g >>> 16); - g = (a.a >>> 16) + (b.a >>> 16) + (d.a >>> 16) + (h.a >>> 16) + (f >>> 16); - return new s((g & 65535) << 16 | f & 65535, k) - } - - function ba(a, b, d, h, f) { - var g, k, m; - g = (a.b & 65535) + (b.b & 65535) + (d.b & 65535) + (h.b & 65535) + (f.b & 65535); - k = (a.b >>> 16) + (b.b >>> 16) + (d.b >>> 16) + (h.b >>> 16) + (f.b >>> 16) + (g >>> 16); - m = (k & 65535) << 16 | g & 65535; - g = (a.a & 65535) + (b.a & 65535) + (d.a & 65535) + (h.a & 65535) + (f.a & 65535) + (k >>> 16); - k = (a.a >>> 16) + (b.a >>> 16) + (d.a >>> 16) + (h.a >>> 16) + (f.a >>> 16) + (g >>> 16); - return new s((k & 65535) << 16 | g & 65535, m) - } - - function $(a, b, d) { - var h, f, g, k, m, j, A, C, K, e, L, v, l, M, t, p, y, z, r, N, O, P, Q, R, c, S, w = [], - T, D; - "SHA-384" === d || "SHA-512" === d ? (L = 80, h = (b + 128 >>> 10 << 5) + 31, M = 32, t = 2, c = s, p = Z, y = aa, z = ba, r = X, N = Y, O = V, P = W, R = U, Q = J, S = [new c(1116352408, 3609767458), new c(1899447441, 602891725), new c(3049323471, 3964484399), new c(3921009573, 2173295548), new c(961987163, 4081628472), new c(1508970993, 3053834265), new c(2453635748, 2937671579), new c(2870763221, 3664609560), new c(3624381080, 2734883394), new c(310598401, 1164996542), new c(607225278, 1323610764), - new c(1426881987, 3590304994), new c(1925078388, 4068182383), new c(2162078206, 991336113), new c(2614888103, 633803317), new c(3248222580, 3479774868), new c(3835390401, 2666613458), new c(4022224774, 944711139), new c(264347078, 2341262773), new c(604807628, 2007800933), new c(770255983, 1495990901), new c(1249150122, 1856431235), new c(1555081692, 3175218132), new c(1996064986, 2198950837), new c(2554220882, 3999719339), new c(2821834349, 766784016), new c(2952996808, 2566594879), new c(3210313671, 3203337956), new c(3336571891, - 1034457026), new c(3584528711, 2466948901), new c(113926993, 3758326383), new c(338241895, 168717936), new c(666307205, 1188179964), new c(773529912, 1546045734), new c(1294757372, 1522805485), new c(1396182291, 2643833823), new c(1695183700, 2343527390), new c(1986661051, 1014477480), new c(2177026350, 1206759142), new c(2456956037, 344077627), new c(2730485921, 1290863460), new c(2820302411, 3158454273), new c(3259730800, 3505952657), new c(3345764771, 106217008), new c(3516065817, 3606008344), new c(3600352804, 1432725776), new c(4094571909, - 1467031594), new c(275423344, 851169720), new c(430227734, 3100823752), new c(506948616, 1363258195), new c(659060556, 3750685593), new c(883997877, 3785050280), new c(958139571, 3318307427), new c(1322822218, 3812723403), new c(1537002063, 2003034995), new c(1747873779, 3602036899), new c(1955562222, 1575990012), new c(2024104815, 1125592928), new c(2227730452, 2716904306), new c(2361852424, 442776044), new c(2428436474, 593698344), new c(2756734187, 3733110249), new c(3204031479, 2999351573), new c(3329325298, 3815920427), new c(3391569614, - 3928383900), new c(3515267271, 566280711), new c(3940187606, 3454069534), new c(4118630271, 4000239992), new c(116418474, 1914138554), new c(174292421, 2731055270), new c(289380356, 3203993006), new c(460393269, 320620315), new c(685471733, 587496836), new c(852142971, 1086792851), new c(1017036298, 365543100), new c(1126000580, 2618297676), new c(1288033470, 3409855158), new c(1501505948, 4234509866), new c(1607167915, 987167468), new c(1816402316, 1246189591) - ], e = "SHA-384" === d ? [new c(3418070365, 3238371032), new c(1654270250, 914150663), - new c(2438529370, 812702999), new c(355462360, 4144912697), new c(1731405415, 4290775857), new c(41048885895, 1750603025), new c(3675008525, 1694076839), new c(1203062813, 3204075428) - ] : [new c(1779033703, 4089235720), new c(3144134277, 2227873595), new c(1013904242, 4271175723), new c(2773480762, 1595750129), new c(1359893119, 2917565137), new c(2600822924, 725511199), new c(528734635, 4215389547), new c(1541459225, 327033209)]) : n("Unexpected error in SHA-2 implementation"); - a[b >>> 5] |= 128 << 24 - b % 32; - a[h] = b; - T = a.length; - for (v = 0; v < - T; v += M) { - b = e[0]; - h = e[1]; - f = e[2]; - g = e[3]; - k = e[4]; - m = e[5]; - j = e[6]; - A = e[7]; - for (l = 0; l < L; l += 1) w[l] = 16 > l ? new c(a[l * t + v], a[l * t + v + 1]) : y(N(w[l - 2]), w[l - 7], r(w[l - 15]), w[l - 16]), C = z(A, P(k), Q(k, m, j), S[l], w[l]), K = p(O(b), R(b, h, f)), A = j, j = m, m = k, k = p(g, C), g = f, f = h, h = b, b = p(C, K); - e[0] = p(b, e[0]); - e[1] = p(h, e[1]); - e[2] = p(f, e[2]); - e[3] = p(g, e[3]); - e[4] = p(k, e[4]); - e[5] = p(m, e[5]); - e[6] = p(j, e[6]); - e[7] = p(A, e[7]) - } - "SHA-384" === d ? D = [e[0].a, e[0].b, e[1].a, e[1].b, e[2].a, e[2].b, e[3].a, e[3].b, e[4].a, e[4].b, e[5].a, e[5].b] : "SHA-512" === d ? D = [e[0].a, e[0].b, - e[1].a, e[1].b, e[2].a, e[2].b, e[3].a, e[3].b, e[4].a, e[4].b, e[5].a, e[5].b, e[6].a, e[6].b, e[7].a, e[7].b - ] : n("Unexpected error in SHA-2 implementation"); - return D - } - GLOBAL.jsSHA = function(a, b, d) { - var h = q, - f = q, - g = 0, - k = [0], - m = 0, - j = q, - m = "undefined" !== typeof d ? d : 8; - 8 === m || 16 === m || n("charSize must be 8 or 16"); - "HEX" === b ? (0 !== a.length % 2 && n("srcString of HEX type must be in byte increments"), j = x(a), g = j.binLen, k = j.value) : "ASCII" === b || "TEXT" === b ? (j = u(a, m), g = j.binLen, k = j.value) : "B64" === b ? (j = B(a), g = j.binLen, k = j.value) : n("inputFormat must be HEX, TEXT, ASCII, or B64"); - this.getHash = function(a, b, d) { - var e = q, - m = k.slice(), - j = ""; - switch (b) { - case "HEX": - e = E; - break; - case "B64": - e = F; - break; - default: - n("format must be HEX or B64") - } - "SHA-384" === - a ? (q === h && (h = $(m, g, a)), j = e(h, G(d))) : "SHA-512" === a ? (q === f && (f = $(m, g, a)), j = e(f, G(d))) : n("Chosen SHA variant is not supported"); - return j - }; - this.getHMAC = function(a, b, d, e, f) { - var h, l, j, t, p, y = [], - z = [], - r = q; - switch (e) { - case "HEX": - h = E; - break; - case "B64": - h = F; - break; - default: - n("outputFormat must be HEX or B64") - } - "SHA-384" === d ? (j = 128, p = 384) : "SHA-512" === d ? (j = 128, p = 512) : n("Chosen SHA variant is not supported"); - "HEX" === b ? (r = x(a), t = r.binLen, l = r.value) : "ASCII" === b || "TEXT" === b ? (r = u(a, m), t = r.binLen, l = r.value) : "B64" === b ? (r = B(a), - t = r.binLen, l = r.value) : n("inputFormat must be HEX, TEXT, ASCII, or B64"); - a = 8 * j; - b = j / 4 - 1; - j < t / 8 ? (l = $(l, t, d), l[b] &= 4294967040) : j > t / 8 && (l[b] &= 4294967040); - for (j = 0; j <= b; j += 1) y[j] = l[j] ^ 909522486, z[j] = l[j] ^ 1549556828; - d = $(z.concat($(y.concat(k), a + g, d)), a + p, d); - return h(d, G(f)) - } - }; - })(); - - //coin.js - (function() { - /* - Coinjs 0.01 beta by OutCast3k{at}gmail.com - A bitcoin framework. - http://github.com/OutCast3k/coinjs or http://coinb.in/coinjs - */ - var coinjs = GLOBAL.coinjs = function() {}; - - /* public vars */ - coinjs.pub = 0x00; - coinjs.priv = 0x80; - coinjs.multisig = 0x05; - coinjs.hdkey = { - 'prv': 0x0488ade4, - 'pub': 0x0488b21e - }; - coinjs.bech32 = { - 'charset': 'qpzry9x8gf2tvdw0s3jn54khce6mua7l', - 'version': 0, - 'hrp': 'bc' - }; - - coinjs.compressed = false; - - /* other vars */ - coinjs.developer = '33tht1bKDgZVxb39MnZsWa8oxHXHvUYE4G'; //bitcoin - - /* bit(coinb.in) api vars - coinjs.hostname = ((document.location.hostname.split(".")[(document.location.hostname.split(".")).length - 1]) == 'onion') ? 'coinbin3ravkwb24f7rmxx6w3snkjw45jhs5lxbh3yfeg3vpt6janwqd.onion' : 'coinb.in'; - coinjs.host = ('https:' == document.location.protocol ? 'https://' : 'http://') + coinjs.hostname + '/api/'; - coinjs.uid = '1'; - coinjs.key = '12345678901234567890123456789012'; - */ - - /* start of address functions */ - - /* generate a private and public keypair, with address and WIF address */ - coinjs.newKeys = function(input) { - var privkey = (input) ? Crypto.SHA256(input) : this.newPrivkey(); - var pubkey = this.newPubkey(privkey); - return { - 'privkey': privkey, - 'pubkey': pubkey, - 'address': this.pubkey2address(pubkey), - 'wif': this.privkey2wif(privkey), - 'compressed': this.compressed - }; - } - - /* generate a new random private key */ - coinjs.newPrivkey = function() { - var x = GLOBAL.location; - x += (GLOBAL.screen.height * GLOBAL.screen.width * GLOBAL.screen.colorDepth); - x += coinjs.random(64); - x += (GLOBAL.screen.availHeight * GLOBAL.screen.availWidth * GLOBAL.screen.pixelDepth); - x += navigator.language; - x += GLOBAL.history.length; - x += coinjs.random(64); - x += navigator.userAgent; - x += 'coinb.in'; - x += (Crypto.util.randomBytes(64)).join(""); - x += x.length; - var dateObj = new Date(); - x += dateObj.getTimezoneOffset(); - x += coinjs.random(64); - x += (document.getElementById("entropybucket")) ? document.getElementById("entropybucket").innerHTML : ''; - x += x + '' + x; - var r = x; - for (let i = 0; i < (x).length / 25; i++) { - r = Crypto.SHA256(r.concat(x)); - } - var checkrBigInt = new BigInteger(r); - var orderBigInt = new BigInteger("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); - while (checkrBigInt.compareTo(orderBigInt) >= 0 || checkrBigInt.equals(BigInteger.ZERO) || checkrBigInt.equals(BigInteger.ONE)) { - r = Crypto.SHA256(r.concat(x)); - checkrBigInt = new BigInteger(r); - } - return r; - } - - /* generate a public key from a private key */ - coinjs.newPubkey = function(hash) { - var privateKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(hash)); - var curve = EllipticCurve.getSECCurveByName("secp256k1"); - - var curvePt = curve.getG().multiply(privateKeyBigInt); - var x = curvePt.getX().toBigInteger(); - var y = curvePt.getY().toBigInteger(); - - var publicKeyBytes = EllipticCurve.integerToBytes(x, 32); - publicKeyBytes = publicKeyBytes.concat(EllipticCurve.integerToBytes(y, 32)); - publicKeyBytes.unshift(0x04); - - if (coinjs.compressed == true) { - var publicKeyBytesCompressed = EllipticCurve.integerToBytes(x, 32) - if (y.isEven()) { - publicKeyBytesCompressed.unshift(0x02) - } else { - publicKeyBytesCompressed.unshift(0x03) - } - return Crypto.util.bytesToHex(publicKeyBytesCompressed); - } else { - return Crypto.util.bytesToHex(publicKeyBytes); - } - } - - /* provide a public key and return address */ - coinjs.pubkey2address = function(h, byte) { - var r = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(h), { - asBytes: true - })); - r.unshift(byte || coinjs.pub); - var hash = Crypto.SHA256(Crypto.SHA256(r, { - asBytes: true - }), { - asBytes: true - }); - var checksum = hash.slice(0, 4); - return coinjs.base58encode(r.concat(checksum)); - } - - /* provide a scripthash and return address */ - coinjs.scripthash2address = function(h) { - var x = Crypto.util.hexToBytes(h); - x.unshift(coinjs.pub); - var r = x; - r = Crypto.SHA256(Crypto.SHA256(r, { - asBytes: true - }), { - asBytes: true - }); - var checksum = r.slice(0, 4); - return coinjs.base58encode(x.concat(checksum)); - } - - /* new multisig address, provide the pubkeys AND required signatures to release the funds */ - coinjs.pubkeys2MultisigAddress = function(pubkeys, required) { - var s = coinjs.script(); - s.writeOp(81 + (required * 1) - 1); //OP_1 - for (var i = 0; i < pubkeys.length; ++i) { - s.writeBytes(Crypto.util.hexToBytes(pubkeys[i])); - } - s.writeOp(81 + pubkeys.length - 1); //OP_1 - s.writeOp(174); //OP_CHECKMULTISIG - var x = ripemd160(Crypto.SHA256(s.buffer, { - asBytes: true - }), { - asBytes: true - }); - x.unshift(coinjs.multisig); - var r = x; - r = Crypto.SHA256(Crypto.SHA256(r, { - asBytes: true - }), { - asBytes: true - }); - var checksum = r.slice(0, 4); - var redeemScript = Crypto.util.bytesToHex(s.buffer); - var address = coinjs.base58encode(x.concat(checksum)); - - if (s.buffer.length > 520) { // too large - address = 'invalid'; - redeemScript = 'invalid'; - } - - return { - 'address': address, - 'redeemScript': redeemScript, - 'size': s.buffer.length - }; - } - - /* new time locked address, provide the pubkey and time necessary to unlock the funds. - when time is greater than 500000000, it should be a unix timestamp (seconds since epoch), - otherwise it should be the block height required before this transaction can be released. - - may throw a string on failure! - */ - coinjs.simpleHodlAddress = function(pubkey, checklocktimeverify) { - - if (checklocktimeverify < 0) { - throw "Parameter for OP_CHECKLOCKTIMEVERIFY is negative."; - } - - var s = coinjs.script(); - if (checklocktimeverify <= 16 && checklocktimeverify >= 1) { - s.writeOp(0x50 + checklocktimeverify); //OP_1 to OP_16 for minimal encoding - } else { - s.writeBytes(coinjs.numToScriptNumBytes(checklocktimeverify)); - } - s.writeOp(177); //OP_CHECKLOCKTIMEVERIFY - s.writeOp(117); //OP_DROP - s.writeBytes(Crypto.util.hexToBytes(pubkey)); - s.writeOp(172); //OP_CHECKSIG - - var x = ripemd160(Crypto.SHA256(s.buffer, { - asBytes: true - }), { - asBytes: true - }); - x.unshift(coinjs.multisig); - var r = x; - r = Crypto.SHA256(Crypto.SHA256(r, { - asBytes: true - }), { - asBytes: true - }); - var checksum = r.slice(0, 4); - var redeemScript = Crypto.util.bytesToHex(s.buffer); - var address = coinjs.base58encode(x.concat(checksum)); - - return { - 'address': address, - 'redeemScript': redeemScript - }; - } - - /* create a new segwit address */ - coinjs.segwitAddress = function(pubkey) { - var keyhash = [0x00, 0x14].concat(ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubkey), { - asBytes: true - }), { - asBytes: true - })); - var x = ripemd160(Crypto.SHA256(keyhash, { - asBytes: true - }), { - asBytes: true - }); - x.unshift(coinjs.multisig); - var r = x; - r = Crypto.SHA256(Crypto.SHA256(r, { - asBytes: true - }), { - asBytes: true - }); - var checksum = r.slice(0, 4); - var address = coinjs.base58encode(x.concat(checksum)); - - return { - 'address': address, - 'type': 'segwit', - 'redeemscript': Crypto.util.bytesToHex(keyhash) - }; - } - - /* create a new segwit bech32 encoded address */ - coinjs.bech32Address = function(pubkey) { - var program = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubkey), { - asBytes: true - }), { - asBytes: true - }); - var address = coinjs.bech32_encode(coinjs.bech32.hrp, [coinjs.bech32.version].concat(coinjs.bech32_convert(program, 8, 5, true))); - return { - 'address': address, - 'type': 'bech32', - 'redeemscript': Crypto.util.bytesToHex(program) - }; - } - - /* extract the redeemscript from a bech32 address */ - coinjs.bech32redeemscript = function(address) { - var r = false; - var decode = coinjs.bech32_decode(address); - if (decode) { - decode.data.shift(); - return Crypto.util.bytesToHex(coinjs.bech32_convert(decode.data, 5, 8, false)); - } - return r; - } - - /* provide a privkey and return an WIF */ - coinjs.privkey2wif = function(h) { - var r = Crypto.util.hexToBytes(h); - - if (coinjs.compressed == true) { - r.push(0x01); - } - - r.unshift(coinjs.priv); - var hash = Crypto.SHA256(Crypto.SHA256(r, { - asBytes: true - }), { - asBytes: true - }); - var checksum = hash.slice(0, 4); - - return coinjs.base58encode(r.concat(checksum)); - } - - /* convert a wif key back to a private key */ - coinjs.wif2privkey = function(wif) { - var compressed = false; - var decode = coinjs.base58decode(wif); - var key = decode.slice(0, decode.length - 4); - key = key.slice(1, key.length); - if (key.length >= 33 && key[key.length - 1] == 0x01) { - key = key.slice(0, key.length - 1); - compressed = true; - } - return { - 'privkey': Crypto.util.bytesToHex(key), - 'compressed': compressed - }; - } - - /* convert a wif to a pubkey */ - coinjs.wif2pubkey = function(wif) { - var compressed = coinjs.compressed; - var r = coinjs.wif2privkey(wif); - coinjs.compressed = r['compressed']; - var pubkey = coinjs.newPubkey(r['privkey']); - coinjs.compressed = compressed; - return { - 'pubkey': pubkey, - 'compressed': r['compressed'] - }; - } - - /* convert a wif to a address */ - coinjs.wif2address = function(wif) { - var r = coinjs.wif2pubkey(wif); - return { - 'address': coinjs.pubkey2address(r['pubkey']), - 'compressed': r['compressed'] - }; - } - - /* decode or validate an address and return the hash */ - coinjs.addressDecode = function(addr) { - try { - var bytes = coinjs.base58decode(addr); - var front = bytes.slice(0, bytes.length - 4); - var back = bytes.slice(bytes.length - 4); - var checksum = Crypto.SHA256(Crypto.SHA256(front, { - asBytes: true - }), { - asBytes: true - }).slice(0, 4); - if (checksum + "" == back + "") { - - var o = {}; - o.bytes = front.slice(1); - o.version = front[0]; - - if (o.version == coinjs.pub) { // standard address - o.type = 'standard'; - - } else if (o.version == coinjs.multisig) { // multisig address - o.type = 'multisig'; - - } else if (o.version == coinjs.priv) { // wifkey - o.type = 'wifkey'; - - } else if (o.version == 42) { // stealth address - o.type = 'stealth'; - - o.option = front[1]; - if (o.option != 0) { - alert("Stealth Address option other than 0 is currently not supported!"); - return false; - }; - - o.scankey = Crypto.util.bytesToHex(front.slice(2, 35)); - o.n = front[35]; - - if (o.n > 1) { - alert("Stealth Multisig is currently not supported!"); - return false; - }; - - o.spendkey = Crypto.util.bytesToHex(front.slice(36, 69)); - o.m = front[69]; - o.prefixlen = front[70]; - - if (o.prefixlen > 0) { - alert("Stealth Address Prefixes are currently not supported!"); - return false; - }; - o.prefix = front.slice(71); - - } else { // everything else - o.type = 'other'; // address is still valid but unknown version - } - - return o; - } else { - throw "Invalid checksum"; - } - } catch (e) { - let bech32rs = coinjs.bech32redeemscript(addr); - if (bech32rs) { - return { - 'type': 'bech32', - 'redeemscript': bech32rs - }; - } else { - return false; - } - } - } - - /* retreive the balance from a given address */ - coinjs.addressBalance = function(address, callback) { - coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=bal&address=' + address + '&r=' + securedMathRandom(), callback, "GET"); - } - - /* decompress an compressed public key */ - coinjs.pubkeydecompress = function(pubkey) { - if ((typeof(pubkey) == 'string') && pubkey.match(/^[a-f0-9]+$/i)) { - var curve = EllipticCurve.getSECCurveByName("secp256k1"); - try { - var pt = curve.curve.decodePointHex(pubkey); - var x = pt.getX().toBigInteger(); - var y = pt.getY().toBigInteger(); - - var publicKeyBytes = EllipticCurve.integerToBytes(x, 32); - publicKeyBytes = publicKeyBytes.concat(EllipticCurve.integerToBytes(y, 32)); - publicKeyBytes.unshift(0x04); - return Crypto.util.bytesToHex(publicKeyBytes); - } catch (e) { - // console.log(e); - return false; - } - } - return false; - } - - coinjs.bech32_polymod = function(values) { - var chk = 1; - var BECH32_GENERATOR = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; - for (var p = 0; p < values.length; ++p) { - var top = chk >> 25; - chk = (chk & 0x1ffffff) << 5 ^ values[p]; - for (var i = 0; i < 5; ++i) { - if ((top >> i) & 1) { - chk ^= BECH32_GENERATOR[i]; - } - } - } - return chk; - } - - coinjs.bech32_hrpExpand = function(hrp) { - var ret = []; - var p; - for (p = 0; p < hrp.length; ++p) { - ret.push(hrp.charCodeAt(p) >> 5); - } - ret.push(0); - for (p = 0; p < hrp.length; ++p) { - ret.push(hrp.charCodeAt(p) & 31); - } - return ret; - } - - coinjs.bech32_verifyChecksum = function(hrp, data) { - return coinjs.bech32_polymod(coinjs.bech32_hrpExpand(hrp).concat(data)) === 1; - } - - coinjs.bech32_createChecksum = function(hrp, data) { - var values = coinjs.bech32_hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]); - var mod = coinjs.bech32_polymod(values) ^ 1; - var ret = []; - for (var p = 0; p < 6; ++p) { - ret.push((mod >> 5 * (5 - p)) & 31); - } - return ret; - } - - coinjs.bech32_encode = function(hrp, data) { - var combined = data.concat(coinjs.bech32_createChecksum(hrp, data)); - var ret = hrp + '1'; - for (var p = 0; p < combined.length; ++p) { - ret += coinjs.bech32.charset.charAt(combined[p]); - } - return ret; - } - - coinjs.bech32_decode = function(bechString) { - var p; - var has_lower = false; - var has_upper = false; - for (p = 0; p < bechString.length; ++p) { - if (bechString.charCodeAt(p) < 33 || bechString.charCodeAt(p) > 126) { - return null; - } - if (bechString.charCodeAt(p) >= 97 && bechString.charCodeAt(p) <= 122) { - has_lower = true; - } - if (bechString.charCodeAt(p) >= 65 && bechString.charCodeAt(p) <= 90) { - has_upper = true; - } - } - if (has_lower && has_upper) { - return null; - } - bechString = bechString.toLowerCase(); - var pos = bechString.lastIndexOf('1'); - if (pos < 1 || pos + 7 > bechString.length || bechString.length > 90) { - return null; - } - var hrp = bechString.substring(0, pos); - var data = []; - for (p = pos + 1; p < bechString.length; ++p) { - var d = coinjs.bech32.charset.indexOf(bechString.charAt(p)); - if (d === -1) { - return null; - } - data.push(d); - } - if (!coinjs.bech32_verifyChecksum(hrp, data)) { - return null; - } - return { - hrp: hrp, - data: data.slice(0, data.length - 6) - }; - } - - coinjs.bech32_convert = function(data, inBits, outBits, pad) { - var value = 0; - var bits = 0; - var maxV = (1 << outBits) - 1; - - var result = []; - for (var i = 0; i < data.length; ++i) { - value = (value << inBits) | data[i]; - bits += inBits; - - while (bits >= outBits) { - bits -= outBits; - result.push((value >> bits) & maxV); - } - } - - if (pad) { - if (bits > 0) { - result.push((value << (outBits - bits)) & maxV); - } - } else { - if (bits >= inBits) throw new Error('Excess padding'); - if ((value << (outBits - bits)) & maxV) throw new Error('Non-zero padding'); - } - - return result; - } - - coinjs.testdeterministicK = function() { - // https://github.com/bitpay/bitcore/blob/9a5193d8e94b0bd5b8e7f00038e7c0b935405a03/test/crypto/ecdsa.js - // Line 21 and 22 specify digest hash and privkey for the first 2 test vectors. - // Line 96-117 tells expected result. - - var tx = coinjs.transaction(); - - var test_vectors = [{ - 'message': 'test data', - 'privkey': 'fee0a1f7afebf9d2a5a80c0c98a31c709681cce195cbcd06342b517970c0be1e', - 'k_bad00': 'fcce1de7a9bcd6b2d3defade6afa1913fb9229e3b7ddf4749b55c4848b2a196e', - 'k_bad01': '727fbcb59eb48b1d7d46f95a04991fc512eb9dbf9105628e3aec87428df28fd8', - 'k_bad15': '398f0e2c9f79728f7b3d84d447ac3a86d8b2083c8f234a0ffa9c4043d68bd258' - }, - { - 'message': 'Everything should be made as simple as possible, but not simpler.', - 'privkey': '0000000000000000000000000000000000000000000000000000000000000001', - 'k_bad00': 'ec633bd56a5774a0940cb97e27a9e4e51dc94af737596a0c5cbb3d30332d92a5', - 'k_bad01': 'df55b6d1b5c48184622b0ead41a0e02bfa5ac3ebdb4c34701454e80aabf36f56', - 'k_bad15': 'def007a9a3c2f7c769c75da9d47f2af84075af95cadd1407393dc1e26086ef87' - }, - { - 'message': 'Satoshi Nakamoto', - 'privkey': '0000000000000000000000000000000000000000000000000000000000000002', - 'k_bad00': 'd3edc1b8224e953f6ee05c8bbf7ae228f461030e47caf97cde91430b4607405e', - 'k_bad01': 'f86d8e43c09a6a83953f0ab6d0af59fb7446b4660119902e9967067596b58374', - 'k_bad15': '241d1f57d6cfd2f73b1ada7907b199951f95ef5ad362b13aed84009656e0254a' - }, - { - 'message': 'Diffie Hellman', - 'privkey': '7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f', - 'k_bad00': 'c378a41cb17dce12340788dd3503635f54f894c306d52f6e9bc4b8f18d27afcc', - 'k_bad01': '90756c96fef41152ac9abe08819c4e95f16da2af472880192c69a2b7bac29114', - 'k_bad15': '7b3f53300ab0ccd0f698f4d67db87c44cf3e9e513d9df61137256652b2e94e7c' - }, - { - 'message': 'Japan', - 'privkey': '8080808080808080808080808080808080808080808080808080808080808080', - 'k_bad00': 'f471e61b51d2d8db78f3dae19d973616f57cdc54caaa81c269394b8c34edcf59', - 'k_bad01': '6819d85b9730acc876fdf59e162bf309e9f63dd35550edf20869d23c2f3e6d17', - 'k_bad15': 'd8e8bae3ee330a198d1f5e00ad7c5f9ed7c24c357c0a004322abca5d9cd17847' - }, - { - 'message': 'Bitcoin', - 'privkey': 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140', - 'k_bad00': '36c848ffb2cbecc5422c33a994955b807665317c1ce2a0f59c689321aaa631cc', - 'k_bad01': '4ed8de1ec952a4f5b3bd79d1ff96446bcd45cabb00fc6ca127183e14671bcb85', - 'k_bad15': '56b6f47babc1662c011d3b1f93aa51a6e9b5f6512e9f2e16821a238d450a31f8' - }, - { - 'message': 'i2FLPP8WEus5WPjpoHwheXOMSobUJVaZM1JPMQZq', - 'privkey': 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140', - 'k_bad00': '6e9b434fcc6bbb081a0463c094356b47d62d7efae7da9c518ed7bac23f4e2ed6', - 'k_bad01': 'ae5323ae338d6117ce8520a43b92eacd2ea1312ae514d53d8e34010154c593bb', - 'k_bad15': '3eaa1b61d1b8ab2f1ca71219c399f2b8b3defa624719f1e96fe3957628c2c4ea' - }, - { - 'message': 'lEE55EJNP7aLrMtjkeJKKux4Yg0E8E1SAJnWTCEh', - 'privkey': '3881e5286abc580bb6139fe8e83d7c8271c6fe5e5c2d640c1f0ed0e1ee37edc9', - 'k_bad00': '5b606665a16da29cc1c5411d744ab554640479dd8abd3c04ff23bd6b302e7034', - 'k_bad01': 'f8b25263152c042807c992eacd2ac2cc5790d1e9957c394f77ea368e3d9923bd', - 'k_bad15': 'ea624578f7e7964ac1d84adb5b5087dd14f0ee78b49072aa19051cc15dab6f33' - }, - { - 'message': '2SaVPvhxkAPrayIVKcsoQO5DKA8Uv5X/esZFlf+y', - 'privkey': '7259dff07922de7f9c4c5720d68c9745e230b32508c497dd24cb95ef18856631', - 'k_bad00': '3ab6c19ab5d3aea6aa0c6da37516b1d6e28e3985019b3adb388714e8f536686b', - 'k_bad01': '19af21b05004b0ce9cdca82458a371a9d2cf0dc35a813108c557b551c08eb52e', - 'k_bad15': '117a32665fca1b7137a91c4739ac5719fec0cf2e146f40f8e7c21b45a07ebc6a' - }, - { - 'message': '00A0OwO2THi7j5Z/jp0FmN6nn7N/DQd6eBnCS+/b', - 'privkey': '0d6ea45d62b334777d6995052965c795a4f8506044b4fd7dc59c15656a28f7aa', - 'k_bad00': '79487de0c8799158294d94c0eb92ee4b567e4dc7ca18addc86e49d31ce1d2db6', - 'k_bad01': '9561d2401164a48a8f600882753b3105ebdd35e2358f4f808c4f549c91490009', - 'k_bad15': 'b0d273634129ff4dbdf0df317d4062a1dbc58818f88878ffdb4ec511c77976c0' - } - ]; - - var result_txt = '\n----------------------\nResults\n----------------------\n\n'; - - for (i = 0; i < test_vectors.length; i++) { - var hash = Crypto.SHA256(test_vectors[i]['message'].split('').map(function(c) { - return c.charCodeAt(0); - }), { - asBytes: true - }); - var wif = coinjs.privkey2wif(test_vectors[i]['privkey']); - - var KBigInt = tx.deterministicK(wif, hash); - var KBigInt0 = tx.deterministicK(wif, hash, 0); - var KBigInt1 = tx.deterministicK(wif, hash, 1); - var KBigInt15 = tx.deterministicK(wif, hash, 15); - - var K = Crypto.util.bytesToHex(KBigInt.toByteArrayUnsigned()); - var K0 = Crypto.util.bytesToHex(KBigInt0.toByteArrayUnsigned()); - var K1 = Crypto.util.bytesToHex(KBigInt1.toByteArrayUnsigned()); - var K15 = Crypto.util.bytesToHex(KBigInt15.toByteArrayUnsigned()); - - if (K != test_vectors[i]['k_bad00']) { - result_txt += 'Failed Test #' + (i + 1) + '\n K = ' + K + '\nExpected = ' + test_vectors[i]['k_bad00'] + '\n\n'; - } else if (K0 != test_vectors[i]['k_bad00']) { - result_txt += 'Failed Test #' + (i + 1) + '\n K0 = ' + K0 + '\nExpected = ' + test_vectors[i]['k_bad00'] + '\n\n'; - } else if (K1 != test_vectors[i]['k_bad01']) { - result_txt += 'Failed Test #' + (i + 1) + '\n K1 = ' + K1 + '\nExpected = ' + test_vectors[i]['k_bad01'] + '\n\n'; - } else if (K15 != test_vectors[i]['k_bad15']) { - result_txt += 'Failed Test #' + (i + 1) + '\n K15 = ' + K15 + '\nExpected = ' + test_vectors[i]['k_bad15'] + '\n\n'; - }; - }; - - if (result_txt.length < 60) { - result_txt = 'All Tests OK!'; - }; - - return result_txt; - }; - - /* start of hd functions, thanks bip32.org */ - coinjs.hd = function(data) { - - var r = {}; - - /* some hd value parsing */ - r.parse = function() { - - var bytes = []; - - // some quick validation - if (typeof(data) == 'string') { - var decoded = coinjs.base58decode(data); - if (decoded.length == 82) { - var checksum = decoded.slice(78, 82); - var hash = Crypto.SHA256(Crypto.SHA256(decoded.slice(0, 78), { - asBytes: true - }), { - asBytes: true - }); - if (checksum[0] == hash[0] && checksum[1] == hash[1] && checksum[2] == hash[2] && checksum[3] == hash[3]) { - bytes = decoded.slice(0, 78); - } - } - } - - // actual parsing code - if (bytes && bytes.length > 0) { - r.version = coinjs.uint(bytes.slice(0, 4), 4); - r.depth = coinjs.uint(bytes.slice(4, 5), 1); - r.parent_fingerprint = bytes.slice(5, 9); - r.child_index = coinjs.uint(bytes.slice(9, 13), 4); - r.chain_code = bytes.slice(13, 45); - r.key_bytes = bytes.slice(45, 78); - - var c = coinjs.compressed; // get current default - coinjs.compressed = true; - - if (r.key_bytes[0] == 0x00) { - r.type = 'private'; - var privkey = (r.key_bytes).slice(1, 33); - var privkeyHex = Crypto.util.bytesToHex(privkey); - var pubkey = coinjs.newPubkey(privkeyHex); - - r.keys = { - 'privkey': privkeyHex, - 'pubkey': pubkey, - 'address': coinjs.pubkey2address(pubkey), - 'wif': coinjs.privkey2wif(privkeyHex) - }; - - } else if (r.key_bytes[0] == 0x02 || r.key_bytes[0] == 0x03) { - r.type = 'public'; - var pubkeyHex = Crypto.util.bytesToHex(r.key_bytes); - - r.keys = { - 'pubkey': pubkeyHex, - 'address': coinjs.pubkey2address(pubkeyHex) - }; - } else { - r.type = 'invalid'; - } - - r.keys_extended = r.extend(); - - coinjs.compressed = c; // reset to default - } - - return r; - } - - // extend prv/pub key - r.extend = function() { - var hd = coinjs.hd(); - return hd.make({ - 'depth': (this.depth * 1) + 1, - 'parent_fingerprint': this.parent_fingerprint, - 'child_index': this.child_index, - 'chain_code': this.chain_code, - 'privkey': this.keys.privkey, - 'pubkey': this.keys.pubkey - }); - } - - // derive from path - r.derive_path = function(path) { - - if (path == 'm' || path == 'M' || path == 'm\'' || path == 'M\'') return this; - - var p = path.split('/'); - var hdp = coinjs.clone(this); // clone hd path - - for (var i in p) { - - if (((i == 0) && c != 'm') || i == 'remove') { - continue; - } - - var c = p[i]; - - var use_private = (c.length > 1) && (c[c.length - 1] == '\''); - var child_index = parseInt(use_private ? c.slice(0, c.length - 1) : c) & 0x7fffffff; - if (use_private) - child_index += 0x80000000; - - hdp = hdp.derive(child_index); - var key = ((hdp.keys_extended.privkey) && hdp.keys_extended.privkey != '') ? hdp.keys_extended.privkey : hdp.keys_extended.pubkey; - hdp = coinjs.hd(key); - } - return hdp; - } - - // derive key from index - r.derive = function(i) { - - i = (i) ? i : 0; - var blob = (Crypto.util.hexToBytes(this.keys.pubkey)).concat(coinjs.numToBytes(i, 4).reverse()); - - var j = new jsSHA(Crypto.util.bytesToHex(blob), 'HEX'); - var hash = j.getHMAC(Crypto.util.bytesToHex(r.chain_code), "HEX", "SHA-512", "HEX"); - - var il = new BigInteger(hash.slice(0, 64), 16); - var ir = Crypto.util.hexToBytes(hash.slice(64, 128)); - - var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); - var curve = ecparams.getCurve(); - - var k, key, pubkey, o; - - o = coinjs.clone(this); - o.chain_code = ir; - o.child_index = i; - - if (this.type == 'private') { - // derive key pair from from a xprv key - k = il.add(new BigInteger([0].concat(Crypto.util.hexToBytes(this.keys.privkey)))).mod(ecparams.getN()); - key = Crypto.util.bytesToHex(k.toByteArrayUnsigned()); - - pubkey = coinjs.newPubkey(key); - - o.keys = { - 'privkey': key, - 'pubkey': pubkey, - 'wif': coinjs.privkey2wif(key), - 'address': coinjs.pubkey2address(pubkey) - }; - - } else if (this.type == 'public') { - // derive xpub key from an xpub key - q = ecparams.curve.decodePointHex(this.keys.pubkey); - var curvePt = ecparams.getG().multiply(il).add(q); - - var x = curvePt.getX().toBigInteger(); - var y = curvePt.getY().toBigInteger(); - - var publicKeyBytesCompressed = EllipticCurve.integerToBytes(x, 32) - if (y.isEven()) { - publicKeyBytesCompressed.unshift(0x02) - } else { - publicKeyBytesCompressed.unshift(0x03) - } - pubkey = Crypto.util.bytesToHex(publicKeyBytesCompressed); - - o.keys = { - 'pubkey': pubkey, - 'address': coinjs.pubkey2address(pubkey) - } - } else { - // fail - } - - o.parent_fingerprint = (ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(r.keys.pubkey), { - asBytes: true - }), { - asBytes: true - })).slice(0, 4); - o.keys_extended = o.extend(); - return o; - } - - // make a master hd xprv/xpub - r.master = function(pass) { - var seed = (pass) ? Crypto.SHA256(pass) : coinjs.newPrivkey(); - var hasher = new jsSHA(seed, 'HEX'); - var I = hasher.getHMAC("Bitcoin seed", "TEXT", "SHA-512", "HEX"); - - var privkey = Crypto.util.hexToBytes(I.slice(0, 64)); - var chain = Crypto.util.hexToBytes(I.slice(64, 128)); - - var hd = coinjs.hd(); - return hd.make({ - 'depth': 0, - 'parent_fingerprint': [0, 0, 0, 0], - 'child_index': 0, - 'chain_code': chain, - 'privkey': I.slice(0, 64), - 'pubkey': coinjs.newPubkey(I.slice(0, 64)) - }); - } - - // encode data to a base58 string - r.make = function(data) { // { (int) depth, (array) parent_fingerprint, (int) child_index, (byte array) chain_code, (hex str) privkey, (hex str) pubkey} - var k = []; - - //depth - k.push(data.depth * 1); - - //parent fingerprint - k = k.concat(data.parent_fingerprint); - - //child index - k = k.concat((coinjs.numToBytes(data.child_index, 4)).reverse()); - - //Chain code - k = k.concat(data.chain_code); - - var o = {}; // results - - //encode xprv key - if (data.privkey) { - var prv = (coinjs.numToBytes(coinjs.hdkey.prv, 4)).reverse(); - prv = prv.concat(k); - prv.push(0x00); - prv = prv.concat(Crypto.util.hexToBytes(data.privkey)); - var hash = Crypto.SHA256(Crypto.SHA256(prv, { - asBytes: true - }), { - asBytes: true - }); - var checksum = hash.slice(0, 4); - var ret = prv.concat(checksum); - o.privkey = coinjs.base58encode(ret); - } - - //encode xpub key - if (data.pubkey) { - var pub = (coinjs.numToBytes(coinjs.hdkey.pub, 4)).reverse(); - pub = pub.concat(k); - pub = pub.concat(Crypto.util.hexToBytes(data.pubkey)); - var hash = Crypto.SHA256(Crypto.SHA256(pub, { - asBytes: true - }), { - asBytes: true - }); - var checksum = hash.slice(0, 4); - var ret = pub.concat(checksum); - o.pubkey = coinjs.base58encode(ret); - } - return o; - } - - return r.parse(); - } - - - /* start of script functions */ - coinjs.script = function(data) { - var r = {}; - - if (!data) { - r.buffer = []; - } else if ("string" == typeof data) { - r.buffer = Crypto.util.hexToBytes(data); - } else if (coinjs.isArray(data)) { - r.buffer = data; - } else if (data instanceof coinjs.script) { - r.buffer = data.buffer; - } else { - r.buffer = data; - } - - /* parse buffer array */ - r.parse = function() { - - var self = this; - r.chunks = []; - var i = 0; - - function readChunk(n) { - self.chunks.push(self.buffer.slice(i, i + n)); - i += n; - }; - - while (i < this.buffer.length) { - var opcode = this.buffer[i++]; - if (opcode >= 0xF0) { - opcode = (opcode << 8) | this.buffer[i++]; - } - - var len; - if (opcode > 0 && opcode < 76) { //OP_PUSHDATA1 - readChunk(opcode); - } else if (opcode == 76) { //OP_PUSHDATA1 - len = this.buffer[i++]; - readChunk(len); - } else if (opcode == 77) { //OP_PUSHDATA2 - len = (this.buffer[i++] << 8) | this.buffer[i++]; - readChunk(len); - } else if (opcode == 78) { //OP_PUSHDATA4 - len = (this.buffer[i++] << 24) | (this.buffer[i++] << 16) | (this.buffer[i++] << 8) | this.buffer[i++]; - readChunk(len); - } else { - this.chunks.push(opcode); - } - - if (i < 0x00) { - break; - } - } - - return true; - }; - - /* decode the redeemscript of a multisignature transaction */ - r.decodeRedeemScript = function(script) { - var r = false; - try { - var s = coinjs.script(Crypto.util.hexToBytes(script)); - if ((s.chunks.length >= 3) && s.chunks[s.chunks.length - 1] == 174) { //OP_CHECKMULTISIG - r = {}; - r.signaturesRequired = s.chunks[0] - 80; - var pubkeys = []; - for (var i = 1; i < s.chunks.length - 2; i++) { - pubkeys.push(Crypto.util.bytesToHex(s.chunks[i])); - } - r.pubkeys = pubkeys; - var multi = coinjs.pubkeys2MultisigAddress(pubkeys, r.signaturesRequired); - r.address = multi['address']; - r.type = 'multisig__'; // using __ for now to differentiat from the other object .type == "multisig" - var rs = Crypto.util.bytesToHex(s.buffer); - r.redeemscript = rs; - - } else if ((s.chunks.length == 2) && (s.buffer[0] == 0 && s.buffer[1] == 20)) { // SEGWIT - r = {}; - r.type = "segwit__"; - var rs = Crypto.util.bytesToHex(s.buffer); - r.address = coinjs.pubkey2address(rs, coinjs.multisig); - r.redeemscript = rs; - - } else if (s.chunks.length == 5 && s.chunks[1] == 177 && s.chunks[2] == 117 && s.chunks[4] == 172) { - // ^ OP_CHECKLOCKTIMEVERIFY OP_DROP OP_CHECKSIG ^ - r = {} - r.pubkey = Crypto.util.bytesToHex(s.chunks[3]); - r.checklocktimeverify = coinjs.bytesToNum(s.chunks[0].slice()); - r.address = coinjs.simpleHodlAddress(r.pubkey, r.checklocktimeverify).address; - var rs = Crypto.util.bytesToHex(s.buffer); - r.redeemscript = rs; - r.type = "hodl__"; - } - } catch (e) { - // console.log(e); - r = false; - } - return r; - } - - /* create output script to spend */ - r.spendToScript = function(address) { - var addr = coinjs.addressDecode(address); - var s = coinjs.script(); - if (addr.type == "bech32") { - s.writeOp(0); - s.writeBytes(Crypto.util.hexToBytes(addr.redeemscript)); - } else if (addr.version == coinjs.multisig) { // multisig address - s.writeOp(169); //OP_HASH160 - s.writeBytes(addr.bytes); - s.writeOp(135); //OP_EQUAL - } else { // regular address - s.writeOp(118); //OP_DUP - s.writeOp(169); //OP_HASH160 - s.writeBytes(addr.bytes); - s.writeOp(136); //OP_EQUALVERIFY - s.writeOp(172); //OP_CHECKSIG - } - return s; - } - - /* geneate a (script) pubkey hash of the address - used for when signing */ - r.pubkeyHash = function(address) { - var addr = coinjs.addressDecode(address); - var s = coinjs.script(); - s.writeOp(118); //OP_DUP - s.writeOp(169); //OP_HASH160 - s.writeBytes(addr.bytes); - s.writeOp(136); //OP_EQUALVERIFY - s.writeOp(172); //OP_CHECKSIG - return s; - } - - /* write to buffer */ - r.writeOp = function(op) { - this.buffer.push(op); - this.chunks.push(op); - return true; - } - - /* write bytes to buffer */ - r.writeBytes = function(data) { - if (data.length < 76) { //OP_PUSHDATA1 - this.buffer.push(data.length); - } else if (data.length <= 0xff) { - this.buffer.push(76); //OP_PUSHDATA1 - this.buffer.push(data.length); - } else if (data.length <= 0xffff) { - this.buffer.push(77); //OP_PUSHDATA2 - this.buffer.push(data.length & 0xff); - this.buffer.push((data.length >>> 8) & 0xff); - } else { - this.buffer.push(78); //OP_PUSHDATA4 - this.buffer.push(data.length & 0xff); - this.buffer.push((data.length >>> 8) & 0xff); - this.buffer.push((data.length >>> 16) & 0xff); - this.buffer.push((data.length >>> 24) & 0xff); - } - this.buffer = this.buffer.concat(data); - this.chunks.push(data); - return true; - } - - r.parse(); - return r; - } - - /* start of transaction functions */ - - /* create a new transaction object */ - coinjs.transaction = function() { - - var r = {}; - r.version = 1; - r.lock_time = 0; - r.ins = []; - r.outs = []; - r.witness = false; - r.timestamp = null; - r.block = null; - - /* add an input to a transaction */ - r.addinput = function(txid, index, script, sequence) { - var o = {}; - o.outpoint = { - 'hash': txid, - 'index': index - }; - o.script = coinjs.script(script || []); - o.sequence = sequence || ((r.lock_time == 0) ? 4294967295 : 0); - return this.ins.push(o); - } - - /* add an output to a transaction */ - r.addoutput = function(address, value) { - var o = {}; - o.value = new BigInteger('' + Math.round((value * 1) * 1e8), 10); - var s = coinjs.script(); - o.script = s.spendToScript(address); - - return this.outs.push(o); - } - - /* add two outputs for stealth addresses to a transaction */ - r.addstealth = function(stealth, value) { - var ephemeralKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(coinjs.newPrivkey())); - var curve = EllipticCurve.getSECCurveByName("secp256k1"); - - var p = EllipticCurve.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"); - var a = BigInteger.ZERO; - var b = EllipticCurve.fromHex("7"); - var calccurve = new EllipticCurve.CurveFp(p, a, b); - - var ephemeralPt = curve.getG().multiply(ephemeralKeyBigInt); - var scanPt = calccurve.decodePointHex(stealth.scankey); - var sharedPt = scanPt.multiply(ephemeralKeyBigInt); - var stealthindexKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.SHA256(sharedPt.getEncoded(true), { - asBytes: true - })); - - var stealthindexPt = curve.getG().multiply(stealthindexKeyBigInt); - var spendPt = calccurve.decodePointHex(stealth.spendkey); - var addressPt = spendPt.add(stealthindexPt); - - var sendaddress = coinjs.pubkey2address(Crypto.util.bytesToHex(addressPt.getEncoded(true))); - - - var OPRETBytes = [6].concat(Crypto.util.randomBytes(4)).concat(ephemeralPt.getEncoded(true)); // ephemkey data - var q = coinjs.script(); - q.writeOp(106); // OP_RETURN - q.writeBytes(OPRETBytes); - v = {}; - v.value = 0; - v.script = q; - - this.outs.push(v); - - var o = {}; - o.value = new BigInteger('' + Math.round((value * 1) * 1e8), 10); - var s = coinjs.script(); - o.script = s.spendToScript(sendaddress); - - return this.outs.push(o); - } - - /* add data to a transaction */ - r.adddata = function(data) { - var r = false; - if (((data.match(/^[a-f0-9]+$/gi)) && data.length < 160) && (data.length % 2) == 0) { - var s = coinjs.script(); - s.writeOp(106); // OP_RETURN - s.writeBytes(Crypto.util.hexToBytes(data)); - o = {}; - o.value = 0; - o.script = s; - return this.outs.push(o); - } - return r; - } - - /* list unspent transactions */ - r.listUnspent = function(address, callback) { - coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=unspent&address=' + address + '&r=' + securedMathRandom(), callback, "GET"); - } - - /* list transaction data */ - r.getTransaction = function(txid, callback) { - coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=bitcoin&request=gettransaction&txid=' + txid + '&r=' + securedMathRandom(), callback, "GET"); - } - - /* add unspent to transaction */ - r.addUnspent = function(address, callback, script, segwit, sequence) { - var self = this; - this.listUnspent(address, function(data) { - var s = coinjs.script(); - var value = 0; - var total = 0; - var x = {}; - - if (GLOBAL.DOMParser) { - parser = new DOMParser(); - xmlDoc = parser.parseFromString(data, "text/xml"); - } else { - xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); - xmlDoc.async = false; - xmlDoc.loadXML(data); - } - - var unspent = xmlDoc.getElementsByTagName("unspent")[0]; - - if (unspent) { - for (i = 1; i <= unspent.childElementCount; i++) { - var u = xmlDoc.getElementsByTagName("unspent_" + i)[0] - var txhash = (u.getElementsByTagName("tx_hash")[0].childNodes[0].nodeValue).match(/.{1,2}/g).reverse().join("") + ''; - var n = u.getElementsByTagName("tx_output_n")[0].childNodes[0].nodeValue; - var scr = script || u.getElementsByTagName("script")[0].childNodes[0].nodeValue; - - if (segwit) { - /* this is a small hack to include the value with the redeemscript to make the signing procedure smoother. - It is not standard and removed during the signing procedure. */ - - s = coinjs.script(); - s.writeBytes(Crypto.util.hexToBytes(script)); - s.writeOp(0); - s.writeBytes(coinjs.numToBytes(u.getElementsByTagName("value")[0].childNodes[0].nodeValue * 1, 8)); - scr = Crypto.util.bytesToHex(s.buffer); - } - - var seq = sequence || false; - self.addinput(txhash, n, scr, seq); - value += u.getElementsByTagName("value")[0].childNodes[0].nodeValue * 1; - total++; - } - } - - x.result = xmlDoc.getElementsByTagName("result")[0].childNodes[0].nodeValue; - x.unspent = unspent; - x.value = value; - x.total = total; - x.response = xmlDoc.getElementsByTagName("response")[0].childNodes[0].nodeValue; - - return callback(x); - }); - } - - /* add unspent and sign */ - r.addUnspentAndSign = function(wif, callback) { - var self = this; - var address = coinjs.wif2address(wif); - self.addUnspent(address['address'], function(data) { - self.sign(wif); - return callback(data); - }); - } - - /* broadcast a transaction */ - r.broadcast = function(callback, txhex) { - var tx = txhex || this.serialize(); - coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=bitcoin&request=sendrawtransaction', callback, "POST", ["rawtx=" + tx]); - } - - /* generate the transaction hash to sign from a transaction input */ - r.transactionHash = function(index, sigHashType) { - - var clone = coinjs.clone(this); - var shType = sigHashType || 1; - - /* black out all other ins, except this one */ - for (var i = 0; i < clone.ins.length; i++) { - if (index != i) { - clone.ins[i].script = coinjs.script(); - } - } - - var extract = this.extractScriptKey(index); - clone.ins[index].script = coinjs.script(extract['script']); - - if ((clone.ins) && clone.ins[index]) { - - /* SIGHASH : For more info on sig hashs see https://en.bitcoin.it/wiki/OP_CHECKSIG - and https://bitcoin.org/en/developer-guide#signature-hash-type */ - - if (shType == 1) { - //SIGHASH_ALL 0x01 - - } else if (shType == 2) { - //SIGHASH_NONE 0x02 - clone.outs = []; - for (var i = 0; i < clone.ins.length; i++) { - if (index != i) { - clone.ins[i].sequence = 0; - } - } - - } else if (shType == 3) { - - //SIGHASH_SINGLE 0x03 - clone.outs.length = index + 1; - - for (var i = 0; i < index; i++) { - clone.outs[i].value = -1; - clone.outs[i].script.buffer = []; - } - - for (var i = 0; i < clone.ins.length; i++) { - if (index != i) { - clone.ins[i].sequence = 0; - } - } - - } else if (shType >= 128) { - //SIGHASH_ANYONECANPAY 0x80 - clone.ins = [clone.ins[index]]; - - if (shType == 129) { - // SIGHASH_ALL + SIGHASH_ANYONECANPAY - - } else if (shType == 130) { - // SIGHASH_NONE + SIGHASH_ANYONECANPAY - clone.outs = []; - - } else if (shType == 131) { - // SIGHASH_SINGLE + SIGHASH_ANYONECANPAY - clone.outs.length = index + 1; - for (var i = 0; i < index; i++) { - clone.outs[i].value = -1; - clone.outs[i].script.buffer = []; - } - } - } - - var buffer = Crypto.util.hexToBytes(clone.serialize()); - buffer = buffer.concat(coinjs.numToBytes(parseInt(shType), 4)); - var hash = Crypto.SHA256(buffer, { - asBytes: true - }); - var r = Crypto.util.bytesToHex(Crypto.SHA256(hash, { - asBytes: true - })); - return r; - } else { - return false; - } - } - - /* generate a segwit transaction hash to sign from a transaction input */ - r.transactionHashSegWitV0 = function(index, sigHashType) { - /* - Notice: coinb.in by default, deals with segwit transactions in a non-standard way. - Segwit transactions require that input values are included in the transaction hash. - To save wasting resources and potentially slowing down this service, we include the amount with the - redeem script to generate the transaction hash and remove it after its signed. - */ - - // start redeem script check - var extract = this.extractScriptKey(index); - if (extract['type'] != 'segwit') { - return { - 'result': 0, - 'fail': 'redeemscript', - 'response': 'redeemscript missing or not valid for segwit' - }; - } - - if (extract['value'] == -1) { - return { - 'result': 0, - 'fail': 'value', - 'response': 'unable to generate a valid segwit hash without a value' - }; - } - - var scriptcode = Crypto.util.hexToBytes(extract['script']); - - // end of redeem script check - - /* P2WPKH */ - if (scriptcode.length == 20) { - scriptcode = [0x00, 0x14].concat(scriptcode); - } - - if (scriptcode.length == 22) { - scriptcode = scriptcode.slice(1); - scriptcode.unshift(25, 118, 169); - scriptcode.push(136, 172); - } - - var value = coinjs.numToBytes(extract['value'], 8); - - // start - - var zero = coinjs.numToBytes(0, 32); - var version = coinjs.numToBytes(parseInt(this.version), 4); - - var bufferTmp = []; - if (!(sigHashType >= 80)) { // not sighash anyonecanpay - for (var i = 0; i < this.ins.length; i++) { - bufferTmp = bufferTmp.concat(Crypto.util.hexToBytes(this.ins[i].outpoint.hash).reverse()); - bufferTmp = bufferTmp.concat(coinjs.numToBytes(this.ins[i].outpoint.index, 4)); - } - } - var hashPrevouts = bufferTmp.length >= 1 ? Crypto.SHA256(Crypto.SHA256(bufferTmp, { - asBytes: true - }), { - asBytes: true - }) : zero; - - var bufferTmp = []; - if (!(sigHashType >= 80) && sigHashType != 2 && sigHashType != 3) { // not sighash anyonecanpay & single & none - for (var i = 0; i < this.ins.length; i++) { - bufferTmp = bufferTmp.concat(coinjs.numToBytes(this.ins[i].sequence, 4)); - } - } - var hashSequence = bufferTmp.length >= 1 ? Crypto.SHA256(Crypto.SHA256(bufferTmp, { - asBytes: true - }), { - asBytes: true - }) : zero; - - var outpoint = Crypto.util.hexToBytes(this.ins[index].outpoint.hash).reverse(); - outpoint = outpoint.concat(coinjs.numToBytes(this.ins[index].outpoint.index, 4)); - - var nsequence = coinjs.numToBytes(this.ins[index].sequence, 4); - var hashOutputs = zero; - var bufferTmp = []; - if (sigHashType != 2 && sigHashType != 3) { // not sighash single & none - for (var i = 0; i < this.outs.length; i++) { - bufferTmp = bufferTmp.concat(coinjs.numToBytes(this.outs[i].value, 8)); - bufferTmp = bufferTmp.concat(coinjs.numToVarInt(this.outs[i].script.buffer.length)); - bufferTmp = bufferTmp.concat(this.outs[i].script.buffer); - } - hashOutputs = Crypto.SHA256(Crypto.SHA256(bufferTmp, { - asBytes: true - }), { - asBytes: true - }); - - } else if ((sigHashType == 2) && index < this.outs.length) { // is sighash single - bufferTmp = bufferTmp.concat(coinjs.numToBytes(this.outs[index].value, 8)); - bufferTmp = bufferTmp.concat(coinjs.numToVarInt(this.outs[i].script.buffer.length)); - bufferTmp = bufferTmp.concat(this.outs[index].script.buffer); - hashOutputs = Crypto.SHA256(Crypto.SHA256(bufferTmp, { - asBytes: true - }), { - asBytes: true - }); - } - - var locktime = coinjs.numToBytes(this.lock_time, 4); - var sighash = coinjs.numToBytes(sigHashType, 4); - - var buffer = []; - buffer = buffer.concat(version); - buffer = buffer.concat(hashPrevouts); - buffer = buffer.concat(hashSequence); - buffer = buffer.concat(outpoint); - buffer = buffer.concat(scriptcode); - buffer = buffer.concat(value); - buffer = buffer.concat(nsequence); - buffer = buffer.concat(hashOutputs); - buffer = buffer.concat(locktime); - buffer = buffer.concat(sighash); - - var hash = Crypto.SHA256(buffer, { - asBytes: true - }); - return { - 'result': 1, - 'hash': Crypto.util.bytesToHex(Crypto.SHA256(hash, { - asBytes: true - })), - 'response': 'hash generated' - }; - } - - /* extract the scriptSig, used in the transactionHash() function */ - r.extractScriptKey = function(index) { - if (this.ins[index]) { - if ((this.ins[index].script.chunks.length == 5) && this.ins[index].script.chunks[4] == 172 && coinjs.isArray(this.ins[index].script.chunks[2])) { //OP_CHECKSIG - // regular scriptPubkey (not signed) - return { - 'type': 'scriptpubkey', - 'signed': 'false', - 'signatures': 0, - 'script': Crypto.util.bytesToHex(this.ins[index].script.buffer) - }; - } else if ((this.ins[index].script.chunks.length == 2) && this.ins[index].script.chunks[0][0] == 48 && this.ins[index].script.chunks[1].length == 5 && this.ins[index].script.chunks[1][1] == 177) { //OP_CHECKLOCKTIMEVERIFY - // hodl script (signed) - return { - 'type': 'hodl', - 'signed': 'true', - 'signatures': 1, - 'script': Crypto.util.bytesToHex(this.ins[index].script.buffer) - }; - } else if ((this.ins[index].script.chunks.length == 2) && this.ins[index].script.chunks[0][0] == 48) { - // regular scriptPubkey (probably signed) - return { - 'type': 'scriptpubkey', - 'signed': 'true', - 'signatures': 1, - 'script': Crypto.util.bytesToHex(this.ins[index].script.buffer) - }; - } else if (this.ins[index].script.chunks.length == 5 && this.ins[index].script.chunks[1] == 177) { //OP_CHECKLOCKTIMEVERIFY - // hodl script (not signed) - return { - 'type': 'hodl', - 'signed': 'false', - 'signatures': 0, - 'script': Crypto.util.bytesToHex(this.ins[index].script.buffer) - }; - } else if ((this.ins[index].script.chunks.length <= 3 && this.ins[index].script.chunks.length > 0) && ((this.ins[index].script.chunks[0].length == 22 && this.ins[index].script.chunks[0][0] == 0) || (this.ins[index].script.chunks[0].length == 20 && this.ins[index].script.chunks[1] == 0))) { - var signed = ((this.witness[index]) && this.witness[index].length == 2) ? 'true' : 'false'; - var sigs = (signed == 'true') ? 1 : 0; - var value = -1; // no value found - if ((this.ins[index].script.chunks[2]) && this.ins[index].script.chunks[2].length == 8) { - value = coinjs.bytesToNum(this.ins[index].script.chunks[2]); // value found encoded in transaction (THIS IS NON STANDARD) - } - return { - 'type': 'segwit', - 'signed': signed, - 'signatures': sigs, - 'script': Crypto.util.bytesToHex(this.ins[index].script.chunks[0]), - 'value': value - }; - } else if (this.ins[index].script.chunks[0] == 0 && this.ins[index].script.chunks[this.ins[index].script.chunks.length - 1][this.ins[index].script.chunks[this.ins[index].script.chunks.length - 1].length - 1] == 174) { // OP_CHECKMULTISIG - // multisig script, with signature(s) included - var sigcount = 0; - for (let i = 1; i < this.ins[index].script.chunks.length - 1; i++) { - if (this.ins[index].script.chunks[i] != 0) { - sigcount++; - } - } - - return { - 'type': 'multisig', - 'signed': 'true', - 'signatures': sigcount, - 'script': Crypto.util.bytesToHex(this.ins[index].script.chunks[this.ins[index].script.chunks.length - 1]) - }; - } else if (this.ins[index].script.chunks[0] >= 80 && this.ins[index].script.chunks[this.ins[index].script.chunks.length - 1] == 174) { // OP_CHECKMULTISIG - // multisig script, without signature! - return { - 'type': 'multisig', - 'signed': 'false', - 'signatures': 0, - 'script': Crypto.util.bytesToHex(this.ins[index].script.buffer) - }; - } else if (this.ins[index].script.chunks.length == 0) { - // empty - //bech32 witness check - var signed = ((this.witness[index]) && this.witness[index].length == 2) ? 'true' : 'false'; - var sigs = (signed == 'true') ? 1 : 0; - return { - 'type': 'empty', - 'signed': signed, - 'signatures': sigs, - 'script': '' - }; - } else { - // something else - return { - 'type': 'unknown', - 'signed': 'false', - 'signatures': 0, - 'script': Crypto.util.bytesToHex(this.ins[index].script.buffer) - }; - } - } else { - return false; - } - } - - /* generate a signature from a transaction hash */ - r.transactionSig = function(index, wif, sigHashType, txhash) { - - function serializeSig(r, s) { - var rBa = r.toByteArraySigned(); - var sBa = s.toByteArraySigned(); - - var sequence = []; - sequence.push(0x02); // INTEGER - sequence.push(rBa.length); - sequence = sequence.concat(rBa); - - sequence.push(0x02); // INTEGER - sequence.push(sBa.length); - sequence = sequence.concat(sBa); - - sequence.unshift(sequence.length); - sequence.unshift(0x30); // SEQUENCE - - return sequence; - } - - var shType = sigHashType || 1; - var hash = txhash || Crypto.util.hexToBytes(this.transactionHash(index, shType)); - - if (hash) { - var curve = EllipticCurve.getSECCurveByName("secp256k1"); - var key = coinjs.wif2privkey(wif); - var priv = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(key['privkey'])); - var n = curve.getN(); - var e = BigInteger.fromByteArrayUnsigned(hash); - var badrs = 0 - do { - var k = this.deterministicK(wif, hash, badrs); - var G = curve.getG(); - var Q = G.multiply(k); - var r = Q.getX().toBigInteger().mod(n); - var s = k.modInverse(n).multiply(e.add(priv.multiply(r))).mod(n); - badrs++ - } while (r.compareTo(BigInteger.ZERO) <= 0 || s.compareTo(BigInteger.ZERO) <= 0); - - // Force lower s values per BIP62 - var halfn = n.shiftRight(1); - if (s.compareTo(halfn) > 0) { - s = n.subtract(s); - }; - - var sig = serializeSig(r, s); - sig.push(parseInt(shType, 10)); - - return Crypto.util.bytesToHex(sig); - } else { - return false; - } - } - - // https://tools.ietf.org/html/rfc6979#section-3.2 - r.deterministicK = function(wif, hash, badrs) { - // if r or s were invalid when this function was used in signing, - // we do not want to actually compute r, s here for efficiency, so, - // we can increment badrs. explained at end of RFC 6979 section 3.2 - - // wif is b58check encoded wif privkey. - // hash is byte array of transaction digest. - // badrs is used only if the k resulted in bad r or s. - - // some necessary things out of the way for clarity. - badrs = badrs || 0; - var key = coinjs.wif2privkey(wif); - var x = Crypto.util.hexToBytes(key['privkey']) - var curve = EllipticCurve.getSECCurveByName("secp256k1"); - var N = curve.getN(); - - // Step: a - // hash is a byteArray of the message digest. so h1 == hash in our case - - // Step: b - var v = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; - - // Step: c - var k = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - - // Step: d - k = Crypto.HMAC(Crypto.SHA256, v.concat([0]).concat(x).concat(hash), k, { - asBytes: true - }); - - // Step: e - v = Crypto.HMAC(Crypto.SHA256, v, k, { - asBytes: true - }); - - // Step: f - k = Crypto.HMAC(Crypto.SHA256, v.concat([1]).concat(x).concat(hash), k, { - asBytes: true - }); - - // Step: g - v = Crypto.HMAC(Crypto.SHA256, v, k, { - asBytes: true - }); - - // Step: h1 - var T = []; - - // Step: h2 (since we know tlen = qlen, just copy v to T.) - v = Crypto.HMAC(Crypto.SHA256, v, k, { - asBytes: true - }); - T = v; - - // Step: h3 - var KBigInt = BigInteger.fromByteArrayUnsigned(T); - - // loop if KBigInt is not in the range of [1, N-1] or if badrs needs incrementing. - var i = 0 - while (KBigInt.compareTo(N) >= 0 || KBigInt.compareTo(BigInteger.ZERO) <= 0 || i < badrs) { - k = Crypto.HMAC(Crypto.SHA256, v.concat([0]), k, { - asBytes: true - }); - v = Crypto.HMAC(Crypto.SHA256, v, k, { - asBytes: true - }); - v = Crypto.HMAC(Crypto.SHA256, v, k, { - asBytes: true - }); - T = v; - KBigInt = BigInteger.fromByteArrayUnsigned(T); - i++ - }; - - return KBigInt; - }; - - /* sign a "standard" input */ - r.signinput = function(index, wif, sigHashType) { - var key = coinjs.wif2pubkey(wif); - var shType = sigHashType || 1; - var signature = this.transactionSig(index, wif, shType); - var s = coinjs.script(); - s.writeBytes(Crypto.util.hexToBytes(signature)); - s.writeBytes(Crypto.util.hexToBytes(key['pubkey'])); - this.ins[index].script = s; - return true; - } - - /* signs a time locked / hodl input */ - r.signhodl = function(index, wif, sigHashType) { - var shType = sigHashType || 1; - var signature = this.transactionSig(index, wif, shType); - var redeemScript = this.ins[index].script.buffer - var s = coinjs.script(); - s.writeBytes(Crypto.util.hexToBytes(signature)); - s.writeBytes(redeemScript); - this.ins[index].script = s; - return true; - } - - /* sign a multisig input */ - r.signmultisig = function(index, wif, sigHashType) { - - function scriptListPubkey(redeemScript) { - var r = {}; - for (var i = 1; i < redeemScript.chunks.length - 2; i++) { - r[i] = Crypto.util.hexToBytes(coinjs.pubkeydecompress(Crypto.util.bytesToHex(redeemScript.chunks[i]))); - } - return r; - } - - function scriptListSigs(scriptSig) { - var r = {}; - var c = 0; - if (scriptSig.chunks[0] == 0 && scriptSig.chunks[scriptSig.chunks.length - 1][scriptSig.chunks[scriptSig.chunks.length - 1].length - 1] == 174) { - for (var i = 1; i < scriptSig.chunks.length - 1; i++) { - if (scriptSig.chunks[i] != 0) { - c++; - r[c] = scriptSig.chunks[i]; - } - } - } - return r; - } - - var redeemScript = (this.ins[index].script.chunks[this.ins[index].script.chunks.length - 1] == 174) ? this.ins[index].script.buffer : this.ins[index].script.chunks[this.ins[index].script.chunks.length - 1]; - - var pubkeyList = scriptListPubkey(coinjs.script(redeemScript)); - var sigsList = scriptListSigs(this.ins[index].script); - - var shType = sigHashType || 1; - var sighash = Crypto.util.hexToBytes(this.transactionHash(index, shType)); - var signature = Crypto.util.hexToBytes(this.transactionSig(index, wif, shType)); - - sigsList[coinjs.countObject(sigsList) + 1] = signature; - - var s = coinjs.script(); - - s.writeOp(0); - - for (let x in pubkeyList) { - for (let y in sigsList) { - this.ins[index].script.buffer = redeemScript; - sighash = Crypto.util.hexToBytes(this.transactionHash(index, sigsList[y].slice(-1)[0] * 1)); - if (coinjs.verifySignature(sighash, sigsList[y], pubkeyList[x])) { - s.writeBytes(sigsList[y]); - } - } - } - - s.writeBytes(redeemScript); - this.ins[index].script = s; - return true; - } - - /* sign segwit input */ - r.signsegwit = function(index, wif, sigHashType) { - var shType = sigHashType || 1; - - var wif2 = coinjs.wif2pubkey(wif); - var segwit = coinjs.segwitAddress(wif2['pubkey']); - var bech32 = coinjs.bech32Address(wif2['pubkey']); - - if ((segwit['redeemscript'] == Crypto.util.bytesToHex(this.ins[index].script.chunks[0])) || (bech32['redeemscript'] == Crypto.util.bytesToHex(this.ins[index].script.chunks[0]))) { - var txhash = this.transactionHashSegWitV0(index, shType); - - if (txhash.result == 1) { - - var segwitHash = Crypto.util.hexToBytes(txhash.hash); - var signature = this.transactionSig(index, wif, shType, segwitHash); - - // remove any non standard data we store, i.e. input value - var script = coinjs.script(); - script.writeBytes(this.ins[index].script.chunks[0]); - this.ins[index].script = script; - - if (!coinjs.isArray(this.witness)) { - this.witness = new Array(this.ins.length); - this.witness.fill([]); - } - - this.witness[index] = ([signature, wif2['pubkey']]); - - // bech32, empty redeemscript - if (bech32['redeemscript'] == Crypto.util.bytesToHex(this.ins[index].script.chunks[0])) { - this.ins[index].script = coinjs.script(); - } - - /* attempt to reorder witness data as best as we can. - data can't be easily validated at this stage as - we dont have access to the inputs value and - making a web call will be too slow. */ - - /* - var witness_order = []; - var witness_used = []; - for (var i = 0; i < this.ins.length; i++) { - for (var y = 0; y < this.witness.length; y++) { - if (!witness_used.includes(y)) { - var sw = coinjs.segwitAddress(this.witness[y][1]); - var b32 = coinjs.bech32Address(this.witness[y][1]); - var rs = ''; - - if (this.ins[i].script.chunks.length >= 1) { - rs = Crypto.util.bytesToHex(this.ins[i].script.chunks[0]); - } else if (this.ins[i].script.chunks.length == 0) { - rs = b32['redeemscript']; - } - - if ((sw['redeemscript'] == rs) || (b32['redeemscript'] == rs)) { - witness_order.push(this.witness[y]); - witness_used.push(y); - - // bech32, empty redeemscript - if (b32['redeemscript'] == rs) { - this.ins[index].script = coinjs.script(); - } - break; - } - } - } - } - - this.witness = witness_order; - */ - } - } - return true; - } - - /* sign inputs */ - r.sign = function(wif, sigHashType) { - var shType = sigHashType || 1; - for (var i = 0; i < this.ins.length; i++) { - var d = this.extractScriptKey(i); - - var w2a = coinjs.wif2address(wif); - var script = coinjs.script(); - var pubkeyHash = script.pubkeyHash(w2a['address']); - - if (((d['type'] == 'scriptpubkey' && d['script'] == Crypto.util.bytesToHex(pubkeyHash.buffer)) || d['type'] == 'empty') && d['signed'] == "false") { - this.signinput(i, wif, shType); - - } else if (d['type'] == 'hodl' && d['signed'] == "false") { - this.signhodl(i, wif, shType); - - } else if (d['type'] == 'multisig') { - this.signmultisig(i, wif, shType); - - } else if (d['type'] == 'segwit') { - this.signsegwit(i, wif, shType); - - } else { - // could not sign - } - } - return this.serialize(); - } - - /* serialize a transaction */ - r.serialize = function() { - var buffer = []; - buffer = buffer.concat(coinjs.numToBytes(parseInt(this.version), 4)); - - if (coinjs.isArray(this.witness)) { - buffer = buffer.concat([0x00, 0x01]); - } - - buffer = buffer.concat(coinjs.numToVarInt(this.ins.length)); - for (var i = 0; i < this.ins.length; i++) { - var txin = this.ins[i]; - buffer = buffer.concat(Crypto.util.hexToBytes(txin.outpoint.hash).reverse()); - buffer = buffer.concat(coinjs.numToBytes(parseInt(txin.outpoint.index), 4)); - var scriptBytes = txin.script.buffer; - buffer = buffer.concat(coinjs.numToVarInt(scriptBytes.length)); - buffer = buffer.concat(scriptBytes); - buffer = buffer.concat(coinjs.numToBytes(parseInt(txin.sequence), 4)); - } - buffer = buffer.concat(coinjs.numToVarInt(this.outs.length)); - - for (var i = 0; i < this.outs.length; i++) { - var txout = this.outs[i]; - buffer = buffer.concat(coinjs.numToBytes(txout.value, 8)); - var scriptBytes = txout.script.buffer; - buffer = buffer.concat(coinjs.numToVarInt(scriptBytes.length)); - buffer = buffer.concat(scriptBytes); - } - - if ((coinjs.isArray(this.witness)) && this.witness.length >= 1) { - for (var i = 0; i < this.witness.length; i++) { - buffer = buffer.concat(coinjs.numToVarInt(this.witness[i].length)); - for (var x = 0; x < this.witness[i].length; x++) { - buffer = buffer.concat(coinjs.numToVarInt(Crypto.util.hexToBytes(this.witness[i][x]).length)); - buffer = buffer.concat(Crypto.util.hexToBytes(this.witness[i][x])); - } - } - } - - buffer = buffer.concat(coinjs.numToBytes(parseInt(this.lock_time), 4)); - return Crypto.util.bytesToHex(buffer); - } - - /* deserialize a transaction */ - r.deserialize = function(buffer) { - if (typeof buffer == "string") { - buffer = Crypto.util.hexToBytes(buffer) - } - - var pos = 0; - var witness = false; - - var readAsInt = function(bytes) { - if (bytes == 0) return 0; - pos++; - return buffer[pos - 1] + readAsInt(bytes - 1) * 256; - } - - var readVarInt = function() { - pos++; - if (buffer[pos - 1] < 253) { - return buffer[pos - 1]; - } - return readAsInt(buffer[pos - 1] - 251); - } - - var readBytes = function(bytes) { - pos += bytes; - return buffer.slice(pos - bytes, pos); - } - - var readVarString = function() { - var size = readVarInt(); - return readBytes(size); - } - - var obj = new coinjs.transaction(); - obj.version = readAsInt(4); - - if (buffer[pos] == 0x00 && buffer[pos + 1] == 0x01) { - // segwit transaction - witness = true; - obj.witness = []; - pos += 2; - } - - var ins = readVarInt(); - for (var i = 0; i < ins; i++) { - obj.ins.push({ - outpoint: { - hash: Crypto.util.bytesToHex(readBytes(32).reverse()), - index: readAsInt(4) - }, - script: coinjs.script(readVarString()), - sequence: readAsInt(4) - }); - } - - var outs = readVarInt(); - for (var i = 0; i < outs; i++) { - obj.outs.push({ - value: coinjs.bytesToNum(readBytes(8)), - script: coinjs.script(readVarString()) - }); - } - - if (witness == true) { - for (i = 0; i < ins; ++i) { - var count = readVarInt(); - var vector = []; - if (!coinjs.isArray(obj.witness[i])) { - obj.witness[i] = []; - } - for (var y = 0; y < count; y++) { - var slice = readVarInt(); - pos += slice; - obj.witness[i].push(Crypto.util.bytesToHex(buffer.slice(pos - slice, pos))); - } - } - } - - obj.lock_time = readAsInt(4); - return obj; - } - - r.size = function() { - return ((this.serialize()).length / 2).toFixed(0); - } - - return r; - } - - /* start of signature vertification functions */ - - coinjs.verifySignature = function(hash, sig, pubkey) { - - function parseSig(sig) { - var cursor; - if (sig[0] != 0x30) - throw new Error("Signature not a valid DERSequence"); - - cursor = 2; - if (sig[cursor] != 0x02) - throw new Error("First element in signature must be a DERInteger");; - - var rBa = sig.slice(cursor + 2, cursor + 2 + sig[cursor + 1]); - - cursor += 2 + sig[cursor + 1]; - if (sig[cursor] != 0x02) - throw new Error("Second element in signature must be a DERInteger"); - - var sBa = sig.slice(cursor + 2, cursor + 2 + sig[cursor + 1]); - - cursor += 2 + sig[cursor + 1]; - - var r = BigInteger.fromByteArrayUnsigned(rBa); - var s = BigInteger.fromByteArrayUnsigned(sBa); - - return { - r: r, - s: s - }; - } - - var r, s; - - if (coinjs.isArray(sig)) { - var obj = parseSig(sig); - r = obj.r; - s = obj.s; - } else if ("object" === typeof sig && sig.r && sig.s) { - r = sig.r; - s = sig.s; - } else { - throw "Invalid value for signature"; - } - - var Q; - if (coinjs.isArray(pubkey)) { - var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); - Q = EllipticCurve.PointFp.decodeFrom(ecparams.getCurve(), pubkey); - } else { - throw "Invalid format for pubkey value, must be byte array"; - } - var e = BigInteger.fromByteArrayUnsigned(hash); - - return coinjs.verifySignatureRaw(e, r, s, Q); - } - - coinjs.verifySignatureRaw = function(e, r, s, Q) { - var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); - var n = ecparams.getN(); - var G = ecparams.getG(); - - if (r.compareTo(BigInteger.ONE) < 0 || r.compareTo(n) >= 0) - return false; - - if (s.compareTo(BigInteger.ONE) < 0 || s.compareTo(n) >= 0) - return false; - - var c = s.modInverse(n); - - var u1 = e.multiply(c).mod(n); - var u2 = r.multiply(c).mod(n); - - var point = G.multiply(u1).add(Q.multiply(u2)); - - var v = point.getX().toBigInteger().mod(n); - - return v.equals(r); - } - - /* start of privates functions */ - - /* base58 encode function */ - coinjs.base58encode = function(buffer) { - var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; - var base = BigInteger.valueOf(58); - - var bi = BigInteger.fromByteArrayUnsigned(buffer); - var chars = []; - - while (bi.compareTo(base) >= 0) { - var mod = bi.mod(base); - chars.unshift(alphabet[mod.intValue()]); - bi = bi.subtract(mod).divide(base); - } - - chars.unshift(alphabet[bi.intValue()]); - for (var i = 0; i < buffer.length; i++) { - if (buffer[i] == 0x00) { - chars.unshift(alphabet[0]); - } else break; - } - return chars.join(''); - } - - /* base58 decode function */ - coinjs.base58decode = function(buffer) { - var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; - var base = BigInteger.valueOf(58); - var validRegex = /^[1-9A-HJ-NP-Za-km-z]+$/; - - var bi = BigInteger.valueOf(0); - var leadingZerosNum = 0; - for (var i = buffer.length - 1; i >= 0; i--) { - var alphaIndex = alphabet.indexOf(buffer[i]); - if (alphaIndex < 0) { - throw "Invalid character"; - } - bi = bi.add(BigInteger.valueOf(alphaIndex).multiply(base.pow(buffer.length - 1 - i))); - - if (buffer[i] == "1") leadingZerosNum++; - else leadingZerosNum = 0; - } - - var bytes = bi.toByteArrayUnsigned(); - while (leadingZerosNum-- > 0) bytes.unshift(0); - return bytes; - } - - /* raw ajax function to avoid needing bigger frame works like jquery, mootools etc */ - coinjs.ajax = function(u, f, m, a) { - var x = false; - try { - x = new ActiveXObject('Msxml2.XMLHTTP') - } catch (e) { - try { - x = new ActiveXObject('Microsoft.XMLHTTP') - } catch (e) { - x = new XMLHttpRequest() - } - } - - if (x == false) { - return false; - } - - x.open(m, u, true); - x.onreadystatechange = function() { - if ((x.readyState == 4) && f) - f(x.responseText); - }; - - if (m == 'POST') { - x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); - } - - x.send(a); - } - - /* clone an object */ - coinjs.clone = function(obj) { - if (obj == null || typeof(obj) != 'object') return obj; - var temp = new obj.constructor(); - - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - temp[key] = coinjs.clone(obj[key]); - } - } - return temp; - } - - coinjs.numToBytes = function(num, bytes) { - if (typeof bytes === "undefined") bytes = 8; - if (bytes == 0) { - return []; - } else if (num == -1) { - return Crypto.util.hexToBytes("ffffffffffffffff"); - } else { - return [num % 256].concat(coinjs.numToBytes(Math.floor(num / 256), bytes - 1)); - } - } - - function scriptNumSize(i) { - return i > 0x7fffffff ? 5 : - i > 0x7fffff ? 4 : - i > 0x7fff ? 3 : - i > 0x7f ? 2 : - i > 0x00 ? 1 : - 0; - } - - coinjs.numToScriptNumBytes = function(_number) { - var value = Math.abs(_number); - var size = scriptNumSize(value); - var result = []; - for (var i = 0; i < size; ++i) { - result.push(0); - } - var negative = _number < 0; - for (i = 0; i < size; ++i) { - result[i] = value & 0xff; - value = Math.floor(value / 256); - } - if (negative) { - result[size - 1] |= 0x80; - } - return result; - } - - coinjs.numToVarInt = function(num) { - if (num < 253) { - return [num]; - } else if (num < 65536) { - return [253].concat(coinjs.numToBytes(num, 2)); - } else if (num < 4294967296) { - return [254].concat(coinjs.numToBytes(num, 4)); - } else { - return [255].concat(coinjs.numToBytes(num, 8)); - } - } - - coinjs.bytesToNum = function(bytes) { - if (bytes.length == 0) return 0; - else return bytes[0] + 256 * coinjs.bytesToNum(bytes.slice(1)); - } - - coinjs.uint = function(f, size) { - if (f.length < size) - throw new Error("not enough data"); - var n = 0; - for (var i = 0; i < size; i++) { - n *= 256; - n += f[i]; - } - return n; - } - - coinjs.isArray = function(o) { - return Object.prototype.toString.call(o) === '[object Array]'; - } - - coinjs.countObject = function(obj) { - var count = 0; - var i; - for (i in obj) { - if (obj.hasOwnProperty(i)) { - count++; - } - } - return count; - } - - coinjs.random = function(length) { - var r = ""; - var l = length || 25; - var chars = "!$%^&*()_+{}:@~?><|\./;'#][=-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; - for (let x = 0; x < l; x++) { - r += chars.charAt(Math.floor(securedMathRandom() * 62)); - } - return r; - } - - })(); - - //secrets.js - (function() { - //Shamir Secret Share by Alexander Stetsyuk - released under MIT License - - var SecretShare = GLOBAL.shamirSecretShare = {}; - var defaults = { - bits: 8, // default number of bits - radix: 16, // work with HEX by default - minBits: 3, - maxBits: 20, // this permits 1,048,575 shares, though going this high is NOT recommended in JS! - - bytesPerChar: 2, - maxBytesPerChar: 6, // Math.pow(256,7) > Math.pow(2,53) - - // Primitive polynomials (in decimal form) for Galois Fields GF(2^n), for 2 <= n <= 30 - // The index of each term in the array corresponds to the n for that polynomial - // i.e. to get the polynomial for n=16, use primitivePolynomials[16] - primitivePolynomials: [null, null, 1, 3, 3, 5, 3, 3, 29, 17, 9, 5, 83, 27, 43, 3, 45, 9, 39, 39, - 9, 5, 3, 33, 27, 9, 71, 39, 9, 5, 83 - ], - - // warning for insecure PRNG - warning: 'WARNING:\nA secure random number generator was not found.\nUsing securedMathRandom(), which is NOT cryptographically strong!' - }; - - // Protected settings object - var config = {}; - - /** @expose **/ - SecretShare.getConfig = function() { - return { - 'bits': config.bits, - 'unsafePRNG': config.unsafePRNG - }; - }; - - function init(bits) { - if (bits && (typeof bits !== 'number' || bits % 1 !== 0 || bits < defaults.minBits || bits > - defaults.maxBits)) { - throw new Error('Number of bits must be an integer between ' + defaults.minBits + ' and ' + - defaults.maxBits + ', inclusive.') - } - - config.radix = defaults.radix; - config.bits = bits || defaults.bits; - config.size = Math.pow(2, config.bits); - config.max = config.size - 1; - - // Construct the exp and log tables for multiplication. - var logs = [], - exps = [], - x = 1, - primitive = defaults.primitivePolynomials[config.bits]; - for (var i = 0; i < config.size; i++) { - exps[i] = x; - logs[x] = i; - x <<= 1; - if (x >= config.size) { - x ^= primitive; - x &= config.max; - } - } - - config.logs = logs; - config.exps = exps; - }; - - /** @expose **/ - SecretShare.init = init; - - function isInited() { - if (!config.bits || !config.size || !config.max || !config.logs || !config.exps || config.logs.length !== - config.size || config.exps.length !== config.size) { - return false; - } - return true; - }; - - // Returns a pseudo-random number generator of the form function(bits){} - // which should output a random string of 1's and 0's of length `bits` - function getRNG() { - var randomBits, crypto; - - function construct(bits, arr, radix, size) { - var str = '', - i = 0, - len = arr.length - 1; - while (i < len || (str.length < bits)) { - str += padLeft(parseInt(arr[i], radix).toString(2), size); - i++; - } - str = str.substr(-bits); - if ((str.match(/0/g) || []).length === str.length) { // all zeros? - return null; - } else { - return str; - } - } - - // node.js crypto.randomBytes() - if (typeof require === 'function') { - return function(bits) { - var bytes = Math.ceil(bits / 8), - str = null; - - while (str === null) { - str = construct(bits, require('crypto').randomBytes(bytes).toString('hex'), 16, 4); - } - return str; - } - } - - // browsers with window.crypto.getRandomValues() - if (GLOBAL['crypto'] && typeof GLOBAL['crypto']['getRandomValues'] === 'function' && typeof GLOBAL['Uint32Array'] === 'function') { - crypto = GLOBAL['crypto']; - return function(bits) { - var elems = Math.ceil(bits / 32), - str = null, - arr = new GLOBAL['Uint32Array'](elems); - - while (str === null) { - crypto['getRandomValues'](arr); - str = construct(bits, arr, 10, 32); - } - - return str; - } - } - - // A totally insecure RNG!!! (except in Safari) - // Will produce a warning every time it is called. - config.unsafePRNG = true; - warn(); - - var bitsPerNum = 32; - var max = Math.pow(2, bitsPerNum) - 1; - return function(bits) { - var elems = Math.ceil(bits / bitsPerNum); - var arr = [], - str = null; - while (str === null) { - for (var i = 0; i < elems; i++) { - arr[i] = Math.floor(securedMathRandom() * max + 1); - } - str = construct(bits, arr, 10, bitsPerNum); - } - return str; - }; - }; - - // Warn about using insecure rng. - // Called when securedMathRandom() is being used. - function warn() { - GLOBAL['console']['warn'](defaults.warning); - if (typeof GLOBAL['alert'] === 'function' && config.alert) { - GLOBAL['alert'](defaults.warning); - } - } - - // Set the PRNG to use. If no RNG function is supplied, pick a default using getRNG() - /** @expose **/ - SecretShare.setRNG = function(rng, alert) { - if (!isInited()) { - this.init(); - } - config.unsafePRNG = false; - rng = rng || getRNG(); - - // test the RNG (5 times) - if (typeof rng !== 'function' || typeof rng(config.bits) !== 'string' || !parseInt(rng(config.bits), - 2) || rng(config.bits).length > config.bits || rng(config.bits).length < config.bits) { - throw new Error( - "Random number generator is invalid. Supply an RNG of the form function(bits){} that returns a string containing 'bits' number of random 1's and 0's." - ) - } else { - config.rng = rng; - } - config.alert = !!alert; - - return !!config.unsafePRNG; - }; - - function isSetRNG() { - return typeof config.rng === 'function'; - }; - - // Generates a random bits-length number string using the PRNG - /** @expose **/ - SecretShare.random = function(bits) { - if (!isSetRNG()) { - this.setRNG(); - } - - if (typeof bits !== 'number' || bits % 1 !== 0 || bits < 2) { - throw new Error('Number of bits must be an integer greater than 1.') - } - - if (config.unsafePRNG) { - warn(); - } - return bin2hex(config.rng(bits)); - } - - // Divides a `secret` number String str expressed in radix `inputRadix` (optional, default 16) - // into `numShares` shares, each expressed in radix `outputRadix` (optional, default to `inputRadix`), - // requiring `threshold` number of shares to reconstruct the secret. - // Optionally, zero-pads the secret to a length that is a multiple of padLength before sharing. - /** @expose **/ - SecretShare.share = function(secret, numShares, threshold, padLength, withoutPrefix) { - if (!isInited()) { - this.init(); - } - if (!isSetRNG()) { - this.setRNG(); - } - - padLength = padLength || 0; - - if (typeof secret !== 'string') { - throw new Error('Secret must be a string.'); - } - if (typeof numShares !== 'number' || numShares % 1 !== 0 || numShares < 2) { - throw new Error('Number of shares must be an integer between 2 and 2^bits-1 (' + config.max + - '), inclusive.') - } - if (numShares > config.max) { - var neededBits = Math.ceil(Math.log(numShares + 1) / Math.LN2); - throw new Error('Number of shares must be an integer between 2 and 2^bits-1 (' + config.max + - '), inclusive. To create ' + numShares + ' shares, use at least ' + neededBits + - ' bits.') - } - if (typeof threshold !== 'number' || threshold % 1 !== 0 || threshold < 2) { - throw new Error('Threshold number of shares must be an integer between 2 and 2^bits-1 (' + - config.max + '), inclusive.'); - } - if (threshold > config.max) { - var neededBits = Math.ceil(Math.log(threshold + 1) / Math.LN2); - throw new Error('Threshold number of shares must be an integer between 2 and 2^bits-1 (' + - config.max + '), inclusive. To use a threshold of ' + threshold + - ', use at least ' + neededBits + ' bits.'); - } - if (typeof padLength !== 'number' || padLength % 1 !== 0) { - throw new Error('Zero-pad length must be an integer greater than 1.'); - } - - if (config.unsafePRNG) { - warn(); - } - - secret = '1' + hex2bin(secret); // append a 1 so that we can preserve the correct number of leading zeros in our secret - secret = split(secret, padLength); - var x = new Array(numShares), - y = new Array(numShares); - for (var i = 0, len = secret.length; i < len; i++) { - var subShares = this._getShares(secret[i], numShares, threshold); - for (var j = 0; j < numShares; j++) { - x[j] = x[j] || subShares[j].x.toString(config.radix); - y[j] = padLeft(subShares[j].y.toString(2)) + (y[j] ? y[j] : ''); - } - } - var padding = config.max.toString(config.radix).length; - if (withoutPrefix) { - for (var i = 0; i < numShares; i++) { - x[i] = bin2hex(y[i]); - } - } else { - for (var i = 0; i < numShares; i++) { - x[i] = config.bits.toString(36).toUpperCase() + padLeft(x[i], padding) + bin2hex(y[i]); - } - } - - return x; - }; - - // This is the basic polynomial generation and evaluation function - // for a `config.bits`-length secret (NOT an arbitrary length) - // Note: no error-checking at this stage! If `secrets` is NOT - // a NUMBER less than 2^bits-1, the output will be incorrect! - /** @expose **/ - SecretShare._getShares = function(secret, numShares, threshold) { - var shares = []; - var coeffs = [secret]; - - for (var i = 1; i < threshold; i++) { - coeffs[i] = parseInt(config.rng(config.bits), 2); - } - for (var i = 1, len = numShares + 1; i < len; i++) { - shares[i - 1] = { - x: i, - y: horner(i, coeffs) - } - } - return shares; - }; - - // Polynomial evaluation at `x` using Horner's Method - // TODO: this can possibly be sped up using other methods - // NOTE: fx=fx * x + coeff[i] -> exp(log(fx) + log(x)) + coeff[i], - // so if fx===0, just set fx to coeff[i] because - // using the exp/log form will result in incorrect value - function horner(x, coeffs) { - var logx = config.logs[x]; - var fx = 0; - for (var i = coeffs.length - 1; i >= 0; i--) { - if (fx === 0) { - fx = coeffs[i]; - continue; - } - fx = config.exps[(logx + config.logs[fx]) % config.max] ^ coeffs[i]; - } - return fx; - }; - - function inArray(arr, val) { - for (var i = 0, len = arr.length; i < len; i++) { - if (arr[i] === val) { - return true; - } - } - return false; - }; - - function processShare(share) { - - var bits = parseInt(share[0], 36); - if (bits && (typeof bits !== 'number' || bits % 1 !== 0 || bits < defaults.minBits || bits > - defaults.maxBits)) { - throw new Error('Number of bits must be an integer between ' + defaults.minBits + ' and ' + - defaults.maxBits + ', inclusive.') - } - - var max = Math.pow(2, bits) - 1; - var idLength = max.toString(config.radix).length; - - var id = parseInt(share.substr(1, idLength), config.radix); - if (typeof id !== 'number' || id % 1 !== 0 || id < 1 || id > max) { - throw new Error('Share id must be an integer between 1 and ' + config.max + ', inclusive.'); - } - share = share.substr(idLength + 1); - if (!share.length) { - throw new Error('Invalid share: zero-length share.') - } - return { - 'bits': bits, - 'id': id, - 'value': share - }; - }; - - /** @expose **/ - SecretShare._processShare = processShare; - - // Protected method that evaluates the Lagrange interpolation - // polynomial at x=`at` for individual config.bits-length - // segments of each share in the `shares` Array. - // Each share is expressed in base `inputRadix`. The output - // is expressed in base `outputRadix' - function combine(at, shares) { - var setBits, share, x = [], - y = [], - result = '', - idx; - - for (var i = 0, len = shares.length; i < len; i++) { - share = processShare(shares[i]); - if (typeof setBits === 'undefined') { - setBits = share['bits']; - } else if (share['bits'] !== setBits) { - throw new Error('Mismatched shares: Different bit settings.') - } - - if (config.bits !== setBits) { - init(setBits); - } - - if (inArray(x, share['id'])) { // repeated x value? - continue; - } - - idx = x.push(share['id']) - 1; - share = split(hex2bin(share['value'])); - for (var j = 0, len2 = share.length; j < len2; j++) { - y[j] = y[j] || []; - y[j][idx] = share[j]; - } - } - - for (var i = 0, len = y.length; i < len; i++) { - result = padLeft(lagrange(at, x, y[i]).toString(2)) + result; - } - - if (at === 0) { // reconstructing the secret - var idx = result.indexOf('1'); //find the first 1 - return bin2hex(result.slice(idx + 1)); - } else { // generating a new share - return bin2hex(result); - } - }; - - // Combine `shares` Array into the original secret - /** @expose **/ - SecretShare.combine = function(shares) { - return combine(0, shares); - }; - - // Generate a new share with id `id` (a number between 1 and 2^bits-1) - // `id` can be a Number or a String in the default radix (16) - /** @expose **/ - SecretShare.newShare = function(id, shares) { - if (typeof id === 'string') { - id = parseInt(id, config.radix); - } - - var share = processShare(shares[0]); - var max = Math.pow(2, share['bits']) - 1; - - if (typeof id !== 'number' || id % 1 !== 0 || id < 1 || id > max) { - throw new Error('Share id must be an integer between 1 and ' + config.max + ', inclusive.'); - } - - var padding = max.toString(config.radix).length; - return config.bits.toString(36).toUpperCase() + padLeft(id.toString(config.radix), padding) + - combine(id, shares); - }; - - // Evaluate the Lagrange interpolation polynomial at x = `at` - // using x and y Arrays that are of the same length, with - // corresponding elements constituting points on the polynomial. - function lagrange(at, x, y) { - var sum = 0, - product, - i, j; - - for (var i = 0, len = x.length; i < len; i++) { - if (!y[i]) { - continue; - } - - product = config.logs[y[i]]; - for (var j = 0; j < len; j++) { - if (i === j) { - continue; - } - if (at === x[j]) { // happens when computing a share that is in the list of shares used to compute it - product = -1; // fix for a zero product term, after which the sum should be sum^0 = sum, not sum^1 - break; - } - product = (product + config.logs[at ^ x[j]] - config.logs[x[i] ^ x[j]] + config.max /* to make sure it's not negative */ ) % - config.max; - } - - sum = product === -1 ? sum : sum ^ config.exps[product]; // though exps[-1]= undefined and undefined ^ anything = anything in chrome, this behavior may not hold everywhere, so do the check - } - return sum; - }; - - /** @expose **/ - SecretShare._lagrange = lagrange; - - // Splits a number string `bits`-length segments, after first - // optionally zero-padding it to a length that is a multiple of `padLength. - // Returns array of integers (each less than 2^bits-1), with each element - // representing a `bits`-length segment of the input string from right to left, - // i.e. parts[0] represents the right-most `bits`-length segment of the input string. - function split(str, padLength) { - if (padLength) { - str = padLeft(str, padLength) - } - var parts = []; - for (var i = str.length; i > config.bits; i -= config.bits) { - parts.push(parseInt(str.slice(i - config.bits, i), 2)); - } - parts.push(parseInt(str.slice(0, i), 2)); - return parts; - }; - - // Pads a string `str` with zeros on the left so that its length is a multiple of `bits` - function padLeft(str, bits) { - bits = bits || config.bits - var missing = str.length % bits; - return (missing ? new Array(bits - missing + 1).join('0') : '') + str; - }; - - function hex2bin(str) { - var bin = '', - num; - for (var i = str.length - 1; i >= 0; i--) { - num = parseInt(str[i], 16) - if (isNaN(num)) { - throw new Error('Invalid hex character.') - } - bin = padLeft(num.toString(2), 4) + bin; - } - return bin; - } - - function bin2hex(str) { - var hex = '', - num; - str = padLeft(str, 4); - for (var i = str.length; i >= 4; i -= 4) { - num = parseInt(str.slice(i - 4, i), 2); - if (isNaN(num)) { - throw new Error('Invalid binary character.') - } - hex = num.toString(16) + hex; - } - return hex; - } - - // Converts a given UTF16 character string to the HEX representation. - // Each character of the input string is represented by - // `bytesPerChar` bytes in the output string. - /** @expose **/ - SecretShare.str2hex = function(str, bytesPerChar) { - if (typeof str !== 'string') { - throw new Error('Input must be a character string.'); - } - bytesPerChar = bytesPerChar || defaults.bytesPerChar; - - if (typeof bytesPerChar !== 'number' || bytesPerChar % 1 !== 0 || bytesPerChar < 1 || - bytesPerChar > defaults.maxBytesPerChar) { - throw new Error('Bytes per character must be an integer between 1 and ' + defaults.maxBytesPerChar + - ', inclusive.') - } - - var hexChars = 2 * bytesPerChar; - var max = Math.pow(16, hexChars) - 1; - var out = '', - num; - for (var i = 0, len = str.length; i < len; i++) { - num = str[i].charCodeAt(); - if (isNaN(num)) { - throw new Error('Invalid character: ' + str[i]); - } else if (num > max) { - var neededBytes = Math.ceil(Math.log(num + 1) / Math.log(256)); - throw new Error('Invalid character code (' + num + - '). Maximum allowable is 256^bytes-1 (' + max + - '). To convert this character, use at least ' + neededBytes + ' bytes.') - } else { - out = padLeft(num.toString(16), hexChars) + out; - } - } - return out; - }; - - // Converts a given HEX number string to a UTF16 character string. - /** @expose **/ - SecretShare.hex2str = function(str, bytesPerChar) { - if (typeof str !== 'string') { - throw new Error('Input must be a hexadecimal string.'); - } - bytesPerChar = bytesPerChar || defaults.bytesPerChar; - - if (typeof bytesPerChar !== 'number' || bytesPerChar % 1 !== 0 || bytesPerChar < 1 || - bytesPerChar > defaults.maxBytesPerChar) { - throw new Error('Bytes per character must be an integer between 1 and ' + defaults.maxBytesPerChar + - ', inclusive.') - } - - var hexChars = 2 * bytesPerChar; - var out = ''; - str = padLeft(str, hexChars); - for (var i = 0, len = str.length; i < len; i += hexChars) { - out = String.fromCharCode(parseInt(str.slice(i, i + hexChars), 16)) + out; - } - return out; - }; - - // by default, initialize without an RNG - SecretShare.init(); - })(); - - //kbucket.js - (function() { - // Kademlia DHT K-bucket implementation as a binary tree. - // by 'Tristan Slominski' under 'MIT License' - GLOBAL.BuildKBucket = function KBucket(options = {}) { - if (!(this instanceof KBucket)) - return new KBucket(options); - this.localNodeId = options.localNodeId || getRandomBytes(new Uint8Array(20)) - this.numberOfNodesPerKBucket = options.numberOfNodesPerKBucket || 20 - this.numberOfNodesToPing = options.numberOfNodesToPing || 3 - this.distance = options.distance || this.distance - this.arbiter = options.arbiter || this.arbiter - this.metadata = Object.assign({}, options.metadata) - - this.createNode = function() { - return { - contacts: [], - dontSplit: false, - left: null, - right: null - } - } - - this.ensureInt8 = function(name, val) { - if (!(val instanceof Uint8Array)) - throw new TypeError(name + ' is not a Uint8Array') - } - - this.arrayEquals = function(array1, array2) { - if (array1 === array2) - return true - if (array1.length !== array2.length) - return false - for (let i = 0, length = array1.length; i < length; ++i) - if (array1[i] !== array2[i]) - return false - return true - } - - this.ensureInt8('option.localNodeId as parameter 1', this.localNodeId) - this.root = this.createNode() - - this.arbiter = function(incumbent, candidate) { - return incumbent.vectorClock > candidate.vectorClock ? incumbent : candidate - } - - this.distance = function(firstId, secondId) { - let distance = 0 - let i = 0 - const min = Math.min(firstId.length, secondId.length) - const max = Math.max(firstId.length, secondId.length) - for (; i < min; ++i) - distance = distance * 256 + (firstId[i] ^ secondId[i]) - for (; i < max; ++i) distance = distance * 256 + 255 - return distance - } - - this.add = function(contact) { - this.ensureInt8('contact.id', (contact || {}).id) - let bitIndex = 0 - let node = this.root - while (node.contacts === null) - node = this._determineNode(node, contact.id, bitIndex++) - const index = this._indexOf(node, contact.id) - if (index >= 0) { - this._update(node, index, contact) - return this - } - if (node.contacts.length < this.numberOfNodesPerKBucket) { - node.contacts.push(contact) - return this - } - if (node.dontSplit) - return this - this._split(node, bitIndex) - return this.add(contact) - } - - this.closest = function(id, n = Infinity) { - this.ensureInt8('id', id) - if ((!Number.isInteger(n) && n !== Infinity) || n <= 0) - throw new TypeError('n is not positive number') - let contacts = [] - for (let nodes = [this.root], bitIndex = 0; nodes.length > 0 && contacts.length < n;) { - const node = nodes.pop() - if (node.contacts === null) { - const detNode = this._determineNode(node, id, bitIndex++) - nodes.push(node.left === detNode ? node.right : node.left) - nodes.push(detNode) - } else - contacts = contacts.concat(node.contacts) - } - return contacts - .map(a => [this.distance(a.id, id), a]) - .sort((a, b) => a[0] - b[0]) - .slice(0, n) - .map(a => a[1]) - } - - this.count = function() { - let count = 0 - for (const nodes = [this.root]; nodes.length > 0;) { - const node = nodes.pop() - if (node.contacts === null) - nodes.push(node.right, node.left) - else - count += node.contacts.length - } - return count - } - - this._determineNode = function(node, id, bitIndex) { - const bytesDescribedByBitIndex = bitIndex >> 3 - const bitIndexWithinByte = bitIndex % 8 - if ((id.length <= bytesDescribedByBitIndex) && (bitIndexWithinByte !== 0)) - return node.left - const byteUnderConsideration = id[bytesDescribedByBitIndex] - if (byteUnderConsideration & (1 << (7 - bitIndexWithinByte))) - return node.right - return node.left - } - - this.get = function(id) { - this.ensureInt8('id', id) - let bitIndex = 0 - let node = this.root - while (node.contacts === null) - node = this._determineNode(node, id, bitIndex++) - const index = this._indexOf(node, id) - return index >= 0 ? node.contacts[index] : null - } - - this._indexOf = function(node, id) { - for (let i = 0; i < node.contacts.length; ++i) - if (this.arrayEquals(node.contacts[i].id, id)) - return i - return -1 - } - - this.remove = function(id) { - this.ensureInt8('the id as parameter 1', id) - let bitIndex = 0 - let node = this.root - while (node.contacts === null) - node = this._determineNode(node, id, bitIndex++) - const index = this._indexOf(node, id) - if (index >= 0) - node.contacts.splice(index, 1)[0] - return this - } - - this._split = function(node, bitIndex) { - node.left = this.createNode() - node.right = this.createNode() - for (const contact of node.contacts) - this._determineNode(node, contact.id, bitIndex).contacts.push(contact) - node.contacts = null - const detNode = this._determineNode(node, this.localNodeId, bitIndex) - const otherNode = node.left === detNode ? node.right : node.left - otherNode.dontSplit = true - } - - this.toArray = function() { - let result = [] - for (const nodes = [this.root]; nodes.length > 0;) { - const node = nodes.pop() - if (node.contacts === null) - nodes.push(node.right, node.left) - else - result = result.concat(node.contacts) - } - return result - } - - this._update = function(node, index, contact) { - if (!this.arrayEquals(node.contacts[index].id, contact.id)) - throw new Error('wrong index for _update') - const incumbent = node.contacts[index] - const selection = this.arbiter(incumbent, contact) - if (selection === incumbent && incumbent !== contact) return - node.contacts.splice(index, 1) - node.contacts.push(selection) - } - } - })(); - -})(typeof global !== "undefined" ? global : window); \ No newline at end of file From fd6e09b157feda0f4d6ff491a25bc85e0e441176 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 19 May 2023 01:05:47 +0530 Subject: [PATCH 288/289] move required stdop files to docs/scripts/ --- LICENCE | 21 - compactIDB.js | 257 ---- btcOperator.js => docs/scripts/btcOperator.js | 0 .../scripts/floBlockchainAPI.js | 0 floCrypto.js => docs/scripts/floCrypto.js | 0 floTokenAPI.js => docs/scripts/floTokenAPI.js | 0 lib.js => docs/scripts/lib.js | 0 floCloudAPI.js | 1055 ----------------- floDapps.js | 845 ------------- index.html | 57 - 10 files changed, 2235 deletions(-) delete mode 100644 LICENCE delete mode 100644 compactIDB.js rename btcOperator.js => docs/scripts/btcOperator.js (100%) rename floBlockchainAPI.js => docs/scripts/floBlockchainAPI.js (100%) rename floCrypto.js => docs/scripts/floCrypto.js (100%) rename floTokenAPI.js => docs/scripts/floTokenAPI.js (100%) rename lib.js => docs/scripts/lib.js (100%) delete mode 100644 floCloudAPI.js delete mode 100644 floDapps.js delete mode 100644 index.html diff --git a/LICENCE b/LICENCE deleted file mode 100644 index d3f4c4c..0000000 --- a/LICENCE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2023 Sai Raj - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/compactIDB.js b/compactIDB.js deleted file mode 100644 index ba843ec..0000000 --- a/compactIDB.js +++ /dev/null @@ -1,257 +0,0 @@ -(function (EXPORTS) { //compactIDB v2.1.2 - /* Compact IndexedDB operations */ - 'use strict'; - const compactIDB = EXPORTS; - - var defaultDB; - - const indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; - const IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction; - const IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange; - - if (!indexedDB) { - console.error("Your browser doesn't support a stable version of IndexedDB."); - return; - } - - compactIDB.setDefaultDB = dbName => defaultDB = dbName; - - Object.defineProperty(compactIDB, 'default', { - get: () => defaultDB, - set: dbName => defaultDB = dbName - }); - - function getDBversion(dbName = defaultDB) { - return new Promise((resolve, reject) => { - openDB(dbName).then(db => { - resolve(db.version) - db.close() - }).catch(error => reject(error)) - }) - } - - function upgradeDB(dbName, createList = null, deleteList = null) { - return new Promise((resolve, reject) => { - getDBversion(dbName).then(version => { - var idb = indexedDB.open(dbName, version + 1); - idb.onerror = (event) => reject("Error in opening IndexedDB"); - idb.onupgradeneeded = (event) => { - let db = event.target.result; - if (createList instanceof Object) { - if (Array.isArray(createList)) { - let tmp = {} - createList.forEach(o => tmp[o] = {}) - createList = tmp - } - for (let o in createList) { - let obs = db.createObjectStore(o, createList[o].options || {}); - if (createList[o].indexes instanceof Object) - for (let i in createList[o].indexes) - obs.createIndex(i, i, createList[o].indexes || {}); - } - } - if (Array.isArray(deleteList)) - deleteList.forEach(o => db.deleteObjectStore(o)); - resolve('Database upgraded') - } - idb.onsuccess = (event) => event.target.result.close(); - }).catch(error => reject(error)) - }) - } - - compactIDB.initDB = function (dbName, objectStores = {}) { - return new Promise((resolve, reject) => { - if (!(objectStores instanceof Object)) - return reject('ObjectStores must be an object or array') - defaultDB = defaultDB || dbName; - var idb = indexedDB.open(dbName); - idb.onerror = (event) => reject("Error in opening IndexedDB"); - idb.onsuccess = (event) => { - var db = event.target.result; - let cList = Object.values(db.objectStoreNames); - var obs = {}, - a_obs = {}, - d_obs = []; - if (!Array.isArray(objectStores)) - var obs = objectStores - else - objectStores.forEach(o => obs[o] = {}) - let nList = Object.keys(obs) - for (let o of nList) - if (!cList.includes(o)) - a_obs[o] = obs[o] - for (let o of cList) - if (!nList.includes(o)) - d_obs.push(o) - if (!Object.keys(a_obs).length && !d_obs.length) - resolve("Initiated IndexedDB"); - else - upgradeDB(dbName, a_obs, d_obs) - .then(result => resolve(result)) - .catch(error => reject(error)) - db.close(); - } - }); - } - - const openDB = compactIDB.openDB = function (dbName = defaultDB) { - return new Promise((resolve, reject) => { - var idb = indexedDB.open(dbName); - idb.onerror = (event) => reject("Error in opening IndexedDB"); - idb.onupgradeneeded = (event) => { - event.target.result.close(); - deleteDB(dbName).then(_ => null).catch(_ => null).finally(_ => reject("Datebase not found")) - } - idb.onsuccess = (event) => resolve(event.target.result); - }); - } - - const deleteDB = compactIDB.deleteDB = function (dbName = defaultDB) { - return new Promise((resolve, reject) => { - var deleteReq = indexedDB.deleteDatabase(dbName);; - deleteReq.onerror = (event) => reject("Error deleting database!"); - deleteReq.onsuccess = (event) => resolve("Database deleted successfully"); - }); - } - - compactIDB.writeData = function (obsName, data, key = false, dbName = defaultDB) { - return new Promise((resolve, reject) => { - openDB(dbName).then(db => { - var obs = db.transaction(obsName, "readwrite").objectStore(obsName); - let writeReq = (key ? obs.put(data, key) : obs.put(data)); - writeReq.onsuccess = (evt) => resolve(`Write data Successful`); - writeReq.onerror = (evt) => reject( - `Write data unsuccessful [${evt.target.error.name}] ${evt.target.error.message}` - ); - db.close(); - }).catch(error => reject(error)); - }); - } - - compactIDB.addData = function (obsName, data, key = false, dbName = defaultDB) { - return new Promise((resolve, reject) => { - openDB(dbName).then(db => { - var obs = db.transaction(obsName, "readwrite").objectStore(obsName); - let addReq = (key ? obs.add(data, key) : obs.add(data)); - addReq.onsuccess = (evt) => resolve(`Add data successful`); - addReq.onerror = (evt) => reject( - `Add data unsuccessful [${evt.target.error.name}] ${evt.target.error.message}` - ); - db.close(); - }).catch(error => reject(error)); - }); - } - - compactIDB.removeData = function (obsName, key, dbName = defaultDB) { - return new Promise((resolve, reject) => { - openDB(dbName).then(db => { - var obs = db.transaction(obsName, "readwrite").objectStore(obsName); - let delReq = obs.delete(key); - delReq.onsuccess = (evt) => resolve(`Removed Data ${key}`); - delReq.onerror = (evt) => reject( - `Remove data unsuccessful [${evt.target.error.name}] ${evt.target.error.message}` - ); - db.close(); - }).catch(error => reject(error)); - }); - } - - compactIDB.clearData = function (obsName, dbName = defaultDB) { - return new Promise((resolve, reject) => { - openDB(dbName).then(db => { - var obs = db.transaction(obsName, "readwrite").objectStore(obsName); - let clearReq = obs.clear(); - clearReq.onsuccess = (evt) => resolve(`Clear data Successful`); - clearReq.onerror = (evt) => reject(`Clear data Unsuccessful`); - db.close(); - }).catch(error => reject(error)); - }); - } - - compactIDB.readData = function (obsName, key, dbName = defaultDB) { - return new Promise((resolve, reject) => { - openDB(dbName).then(db => { - var obs = db.transaction(obsName, "readonly").objectStore(obsName); - let getReq = obs.get(key); - getReq.onsuccess = (evt) => resolve(evt.target.result); - getReq.onerror = (evt) => reject( - `Read data unsuccessful [${evt.target.error.name}] ${evt.target.error.message}` - ); - db.close(); - }).catch(error => reject(error)); - }); - } - - compactIDB.readAllData = function (obsName, dbName = defaultDB) { - return new Promise((resolve, reject) => { - openDB(dbName).then(db => { - var obs = db.transaction(obsName, "readonly").objectStore(obsName); - var tmpResult = {} - let curReq = obs.openCursor(); - curReq.onsuccess = (evt) => { - var cursor = evt.target.result; - if (cursor) { - tmpResult[cursor.primaryKey] = cursor.value; - cursor.continue(); - } else - resolve(tmpResult); - } - curReq.onerror = (evt) => reject( - `Read-All data unsuccessful [${evt.target.error.name}] ${evt.target.error.message}` - ); - db.close(); - }).catch(error => reject(error)); - }); - } - - /* compactIDB.searchData = function (obsName, options = {}, dbName = defaultDB) { - - return new Promise((resolve, reject) => { - openDB(dbName).then(db => { - var obs = db.transaction(obsName, "readonly").objectStore(obsName); - var filteredResult = {} - let keyRange; - if(options.lowerKey!==null && options.upperKey!==null) - keyRange = IDBKeyRange.bound(options.lowerKey, options.upperKey); - else if(options.lowerKey!==null) - keyRange = IDBKeyRange.lowerBound(options.lowerKey); - else if (options.upperKey!==null) - keyRange = IDBKeyRange.upperBound(options.upperBound); - else if (options.atKey) - let curReq = obs.openCursor(keyRange, ) - }).catch(error => reject(error)) - }) - }*/ - - compactIDB.searchData = function (obsName, options = {}, dbName = defaultDB) { - options.lowerKey = options.atKey || options.lowerKey || 0 - options.upperKey = options.atKey || options.upperKey || false - options.patternEval = options.patternEval || ((k, v) => true); - options.limit = options.limit || false; - options.reverse = options.reverse || false; - options.lastOnly = options.lastOnly || false - return new Promise((resolve, reject) => { - openDB(dbName).then(db => { - var obs = db.transaction(obsName, "readonly").objectStore(obsName); - var filteredResult = {} - let curReq = obs.openCursor( - options.upperKey ? IDBKeyRange.bound(options.lowerKey, options.upperKey) : IDBKeyRange.lowerBound(options.lowerKey), - options.lastOnly || options.reverse ? "prev" : "next"); - curReq.onsuccess = (evt) => { - var cursor = evt.target.result; - if (!cursor || (options.limit && options.limit <= Object.keys(filteredResult).length)) - return resolve(filteredResult); //reached end of key list or limit reached - else if (options.patternEval(cursor.primaryKey, cursor.value)) { - filteredResult[cursor.primaryKey] = cursor.value; - options.lastOnly ? resolve(filteredResult) : cursor.continue(); - } else - cursor.continue(); - } - curReq.onerror = (evt) => reject(`Search unsuccessful [${evt.target.error.name}] ${evt.target.error.message}`); - db.close(); - }).catch(error => reject(error)); - }); - } - - -})(window.compactIDB = {}); \ No newline at end of file diff --git a/btcOperator.js b/docs/scripts/btcOperator.js similarity index 100% rename from btcOperator.js rename to docs/scripts/btcOperator.js diff --git a/floBlockchainAPI.js b/docs/scripts/floBlockchainAPI.js similarity index 100% rename from floBlockchainAPI.js rename to docs/scripts/floBlockchainAPI.js diff --git a/floCrypto.js b/docs/scripts/floCrypto.js similarity index 100% rename from floCrypto.js rename to docs/scripts/floCrypto.js diff --git a/floTokenAPI.js b/docs/scripts/floTokenAPI.js similarity index 100% rename from floTokenAPI.js rename to docs/scripts/floTokenAPI.js diff --git a/lib.js b/docs/scripts/lib.js similarity index 100% rename from lib.js rename to docs/scripts/lib.js diff --git a/floCloudAPI.js b/floCloudAPI.js deleted file mode 100644 index c2d2c3f..0000000 --- a/floCloudAPI.js +++ /dev/null @@ -1,1055 +0,0 @@ -(function (EXPORTS) { //floCloudAPI v2.4.3a - /* FLO Cloud operations to send/request application data*/ - 'use strict'; - const floCloudAPI = EXPORTS; - - const DEFAULT = { - blockchainPrefix: 0x23, //Prefix version for FLO blockchain - SNStorageID: floGlobals.SNStorageID || "FNaN9McoBAEFUjkRmNQRYLmBF8SpS7Tgfk", - adminID: floGlobals.adminID, - application: floGlobals.application, - SNStorageName: "SuperNodeStorage", - callback: (d, e) => console.debug(d, e) - }; - - var user_id, user_public, user_private, aes_key; - - function user(id, priv) { - if (!priv || !id) - return user.clear(); - let pub = floCrypto.getPubKeyHex(priv); - if (!pub || !floCrypto.verifyPubKey(pub, id)) - return user.clear(); - let n = floCrypto.randInt(12, 20); - aes_key = floCrypto.randString(n); - user_private = Crypto.AES.encrypt(priv, aes_key); - user_public = pub; - user_id = id; - return user_id; - } - - Object.defineProperties(user, { - id: { - get: () => { - if (!user_id) - throw "User not set"; - return user_id; - } - }, - public: { - get: () => { - if (!user_public) - throw "User not set"; - return user_public; - } - }, - sign: { - value: msg => { - if (!user_private) - throw "User not set"; - return floCrypto.signData(msg, Crypto.AES.decrypt(user_private, aes_key)); - } - }, - clear: { - value: () => user_id = user_public = user_private = aes_key = undefined - } - }) - - Object.defineProperties(floCloudAPI, { - SNStorageID: { - get: () => DEFAULT.SNStorageID - }, - SNStorageName: { - get: () => DEFAULT.SNStorageName - }, - adminID: { - get: () => DEFAULT.adminID - }, - application: { - get: () => DEFAULT.application - }, - user: { - get: () => user - } - }); - - var appObjects, generalData, lastVC; - Object.defineProperties(floGlobals, { - appObjects: { - get: () => appObjects, - set: obj => appObjects = obj - }, - generalData: { - get: () => generalData, - set: data => generalData = data - }, - generalDataset: { - value: (type, options = {}) => generalData[filterKey(type, options)] - }, - lastVC: { - get: () => lastVC, - set: vc => lastVC = vc - } - }); - - var supernodes = {}; //each supnernode must be stored as floID : {uri:,pubKey:} - Object.defineProperty(floCloudAPI, 'nodes', { - get: () => JSON.parse(JSON.stringify(supernodes)) - }); - - var kBucket; - const K_Bucket = floCloudAPI.K_Bucket = function (masterID, nodeList) { - - const decodeID = floID => { - let k = bitjs.Base58.decode(floID); - k.shift(); - k.splice(-4, 4); - let decodedId = Crypto.util.bytesToHex(k); - let nodeIdBigInt = new BigInteger(decodedId, 16); - let nodeIdBytes = nodeIdBigInt.toByteArrayUnsigned(); - let nodeIdNewInt8Array = new Uint8Array(nodeIdBytes); - return nodeIdNewInt8Array; - }; - - const _KB = new BuildKBucket({ - localNodeId: decodeID(masterID) - }); - nodeList.forEach(id => _KB.add({ - id: decodeID(id), - floID: id - })); - - const _CO = nodeList.map(id => [_KB.distance(_KB.localNodeId, decodeID(id)), id]) - .sort((a, b) => a[0] - b[0]) - .map(a => a[1]); - - const self = this; - Object.defineProperty(self, 'tree', { - get: () => _KB - }); - Object.defineProperty(self, 'list', { - get: () => Array.from(_CO) - }); - - self.isNode = floID => _CO.includes(floID); - self.innerNodes = function (id1, id2) { - if (!_CO.includes(id1) || !_CO.includes(id2)) - throw Error('Given nodes are not supernode'); - let iNodes = [] - for (let i = _CO.indexOf(id1) + 1; _CO[i] != id2; i++) { - if (i < _CO.length) - iNodes.push(_CO[i]) - else i = -1 - } - return iNodes - } - self.outterNodes = function (id1, id2) { - if (!_CO.includes(id1) || !_CO.includes(id2)) - throw Error('Given nodes are not supernode'); - let oNodes = [] - for (let i = _CO.indexOf(id2) + 1; _CO[i] != id1; i++) { - if (i < _CO.length) - oNodes.push(_CO[i]) - else i = -1 - } - return oNodes - } - self.prevNode = function (id, N = 1) { - let n = N || _CO.length; - if (!_CO.includes(id)) - throw Error('Given node is not supernode'); - let pNodes = [] - for (let i = 0, j = _CO.indexOf(id) - 1; i < n; j--) { - if (j == _CO.indexOf(id)) - break; - else if (j > -1) - pNodes[i++] = _CO[j] - else j = _CO.length - } - return (N == 1 ? pNodes[0] : pNodes) - } - self.nextNode = function (id, N = 1) { - let n = N || _CO.length; - if (!_CO.includes(id)) - throw Error('Given node is not supernode'); - if (!n) n = _CO.length; - let nNodes = [] - for (let i = 0, j = _CO.indexOf(id) + 1; i < n; j++) { - if (j == _CO.indexOf(id)) - break; - else if (j < _CO.length) - nNodes[i++] = _CO[j] - else j = -1 - } - return (N == 1 ? nNodes[0] : nNodes) - } - self.closestNode = function (id, N = 1) { - let decodedId = decodeID(id); - let n = N || _CO.length; - let cNodes = _KB.closest(decodedId, n) - .map(k => k.floID) - return (N == 1 ? cNodes[0] : cNodes) - } - } - - floCloudAPI.init = function startCloudProcess(nodes) { - return new Promise((resolve, reject) => { - try { - supernodes = nodes; - kBucket = new K_Bucket(DEFAULT.SNStorageID, Object.keys(supernodes)); - resolve('Cloud init successful'); - } catch (error) { - reject(error); - } - }) - } - - Object.defineProperty(floCloudAPI, 'kBucket', { - get: () => kBucket - }); - - const _inactive = new Set(); - - function ws_connect(snID) { - return new Promise((resolve, reject) => { - if (!(snID in supernodes)) - return reject(`${snID} is not a supernode`) - if (_inactive.has(snID)) - return reject(`${snID} is not active`) - var wsConn = new WebSocket("wss://" + supernodes[snID].uri + "/"); - wsConn.onopen = evt => resolve(wsConn); - wsConn.onerror = evt => { - _inactive.add(snID) - reject(`${snID} is unavailable`) - } - }) - } - - function ws_activeConnect(snID, reverse = false) { - return new Promise((resolve, reject) => { - if (_inactive.size === kBucket.list.length) - return reject('Cloud offline'); - if (!(snID in supernodes)) - snID = kBucket.closestNode(proxyID(snID)); - ws_connect(snID) - .then(node => resolve(node)) - .catch(error => { - if (reverse) - var nxtNode = kBucket.prevNode(snID); - else - var nxtNode = kBucket.nextNode(snID); - ws_activeConnect(nxtNode, reverse) - .then(node => resolve(node)) - .catch(error => reject(error)) - }) - }) - } - - function fetch_API(snID, data) { - return new Promise((resolve, reject) => { - if (_inactive.has(snID)) - return reject(`${snID} is not active`); - let fetcher, sn_url = "https://" + supernodes[snID].uri; - if (typeof data === "string") - fetcher = fetch(sn_url + "?" + data); - else if (typeof data === "object" && data.method === "POST") - fetcher = fetch(sn_url, data); - fetcher.then(response => { - if (response.ok || response.status === 400 || response.status === 500) - resolve(response); - else - reject(response); - }).catch(error => reject(error)) - }) - } - - function fetch_ActiveAPI(snID, data, reverse = false) { - return new Promise((resolve, reject) => { - if (_inactive.size === kBucket.list.length) - return reject('Cloud offline'); - if (!(snID in supernodes)) - snID = kBucket.closestNode(proxyID(snID)); - fetch_API(snID, data) - .then(result => resolve(result)) - .catch(error => { - _inactive.add(snID) - if (reverse) - var nxtNode = kBucket.prevNode(snID); - else - var nxtNode = kBucket.nextNode(snID); - fetch_ActiveAPI(nxtNode, data, reverse) - .then(result => resolve(result)) - .catch(error => reject(error)); - }) - }) - } - - function singleRequest(floID, data_obj, method = "POST") { - return new Promise((resolve, reject) => { - let data; - if (method === "POST") - data = { - method: "POST", - body: JSON.stringify(data_obj) - }; - else - data = new URLSearchParams(JSON.parse(JSON.stringify(data_obj))).toString(); - fetch_ActiveAPI(floID, data).then(response => { - if (response.ok) - response.json() - .then(result => resolve(result)) - .catch(error => reject(error)) - else response.text() - .then(result => reject(response.status + ": " + result)) //Error Message from Node - .catch(error => reject(error)) - }).catch(error => reject(error)) - }) - } - - const _liveRequest = {}; - - function liveRequest(floID, request, callback) { - const filterData = typeof request.status !== 'undefined' ? - data => { - if (request.status) - return data; - else { - let filtered = {}; - for (let i in data) - if (request.trackList.includes(i)) - filtered[i] = data[i]; - return filtered; - } - } : - data => { - data = objectifier(data); - let filtered = {}, - proxy = proxyID(request.receiverID), - r = request; - for (let v in data) { - let d = data[v]; - if ((!r.atVectorClock || r.atVectorClock == v) && - (r.atVectorClock || !r.lowerVectorClock || r.lowerVectorClock <= v) && - (r.atVectorClock || !r.upperVectorClock || r.upperVectorClock >= v) && - (!r.afterTime || r.afterTime < d.log_time) && - r.application == d.application && - (proxy == d.receiverID || proxy == d.proxyID) && - (!r.comment || r.comment == d.comment) && - (!r.type || r.type == d.type) && - (!r.senderID || r.senderID.includes(d.senderID))) - filtered[v] = data[v]; - } - return filtered; - }; - - return new Promise((resolve, reject) => { - ws_activeConnect(floID).then(node => { - let randID = floCrypto.randString(5); - node.send(JSON.stringify(request)); - node.onmessage = (evt) => { - let d = null, - e = null; - try { - d = filterData(JSON.parse(evt.data)); - } catch (error) { - e = evt.data - } finally { - callback(d, e) - } - } - _liveRequest[randID] = node; - _liveRequest[randID].request = request; - resolve(randID); - }).catch(error => reject(error)); - }); - } - - Object.defineProperty(floCloudAPI, 'liveRequest', { - get: () => _liveRequest - }); - - Object.defineProperty(floCloudAPI, 'inactive', { - get: () => _inactive - }); - - const util = floCloudAPI.util = {}; - - const encodeMessage = util.encodeMessage = function (message) { - return btoa(unescape(encodeURIComponent(JSON.stringify(message)))) - } - - const decodeMessage = util.decodeMessage = function (message) { - return JSON.parse(decodeURIComponent(escape(atob(message)))) - } - - const filterKey = util.filterKey = function (type, options = {}) { - return type + (options.comment ? ':' + options.comment : '') + - '|' + (options.group || options.receiverID || DEFAULT.adminID) + - '|' + (options.application || DEFAULT.application); - } - - const proxyID = util.proxyID = function (address) { - if (!address) - return; - var bytes; - if (address.length == 33 || address.length == 34) { //legacy encoding - let decode = bitjs.Base58.decode(address); - bytes = decode.slice(0, decode.length - 4); - let checksum = decode.slice(decode.length - 4), - hash = Crypto.SHA256(Crypto.SHA256(bytes, { - asBytes: true - }), { - asBytes: true - }); - hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3] ? - bytes = undefined : bytes.shift(); - } else if (address.length == 42 || address.length == 62) { //bech encoding - if (typeof coinjs !== 'function') - throw "library missing (lib_btc.js)"; - let decode = coinjs.bech32_decode(address); - if (decode) { - bytes = decode.data; - bytes.shift(); - bytes = coinjs.bech32_convert(bytes, 5, 8, false); - if (address.length == 62) //for long bech, aggregate once more to get 160 bit - bytes = coinjs.bech32_convert(bytes, 5, 8, false); - } - } else if (address.length == 66) { //public key hex - bytes = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(address), { - asBytes: true - })); - } - if (!bytes) - throw "Invalid address: " + address; - else { - bytes.unshift(DEFAULT.blockchainPrefix); - let hash = Crypto.SHA256(Crypto.SHA256(bytes, { - asBytes: true - }), { - asBytes: true - }); - return bitjs.Base58.encode(bytes.concat(hash.slice(0, 4))); - } - } - - const lastCommit = {}; - Object.defineProperty(lastCommit, 'get', { - value: objName => JSON.parse(lastCommit[objName]) - }); - Object.defineProperty(lastCommit, 'set', { - value: objName => lastCommit[objName] = JSON.stringify(appObjects[objName]) - }); - - function updateObject(objectName, dataSet) { - try { - console.log(dataSet) - let vcList = Object.keys(dataSet).sort(); - for (let vc of vcList) { - if (vc < lastVC[objectName] || dataSet[vc].type !== objectName) - continue; - switch (dataSet[vc].comment) { - case "RESET": - if (dataSet[vc].message.reset) - appObjects[objectName] = dataSet[vc].message.reset; - break; - case "UPDATE": - if (dataSet[vc].message.diff) - appObjects[objectName] = diff.merge(appObjects[objectName], dataSet[vc].message.diff); - } - lastVC[objectName] = vc; - } - lastCommit.set(objectName); - compactIDB.writeData("appObjects", appObjects[objectName], objectName); - compactIDB.writeData("lastVC", lastVC[objectName], objectName); - } catch (error) { - console.error(error) - } - } - - function storeGeneral(fk, dataSet) { - try { - console.log(dataSet) - if (typeof generalData[fk] !== "object") - generalData[fk] = {} - for (let vc in dataSet) { - generalData[fk][vc] = dataSet[vc]; - if (dataSet[vc].log_time > lastVC[fk]) - lastVC[fk] = dataSet[vc].log_time; - } - compactIDB.writeData("lastVC", lastVC[fk], fk) - compactIDB.writeData("generalData", generalData[fk], fk) - } catch (error) { - console.error(error) - } - } - - function objectifier(data) { - if (!Array.isArray(data)) - data = [data]; - return Object.fromEntries(data.map(d => { - d.message = decodeMessage(d.message); - return [d.vectorClock, d]; - })); - } - - //set status as online for user_id - floCloudAPI.setStatus = function (options = {}) { - return new Promise((resolve, reject) => { - let callback = options.callback instanceof Function ? options.callback : DEFAULT.callback; - var request = { - floID: user.id, - application: options.application || DEFAULT.application, - time: Date.now(), - status: true, - pubKey: user.public - } - let hashcontent = ["time", "application", "floID"].map(d => request[d]).join("|"); - request.sign = user.sign(hashcontent); - liveRequest(options.refID || DEFAULT.adminID, request, callback) - .then(result => resolve(result)) - .catch(error => reject(error)) - }) - } - - //request status of floID(s) in trackList - floCloudAPI.requestStatus = function (trackList, options = {}) { - return new Promise((resolve, reject) => { - if (!Array.isArray(trackList)) - trackList = [trackList]; - let callback = options.callback instanceof Function ? options.callback : DEFAULT.callback; - let request = { - status: false, - application: options.application || DEFAULT.application, - trackList: trackList - } - liveRequest(options.refID || DEFAULT.adminID, request, callback) - .then(result => resolve(result)) - .catch(error => reject(error)) - }) - } - - //send any message to supernode cloud storage - const sendApplicationData = floCloudAPI.sendApplicationData = function (message, type, options = {}) { - return new Promise((resolve, reject) => { - var data = { - senderID: user.id, - receiverID: options.receiverID || DEFAULT.adminID, - pubKey: user.public, - message: encodeMessage(message), - time: Date.now(), - application: options.application || DEFAULT.application, - type: type, - comment: options.comment || "" - } - let hashcontent = ["receiverID", "time", "application", "type", "message", "comment"] - .map(d => data[d]).join("|") - data.sign = user.sign(hashcontent); - singleRequest(data.receiverID, data) - .then(result => resolve(result)) - .catch(error => reject(error)) - }) - } - - //request any data from supernode cloud - const requestApplicationData = floCloudAPI.requestApplicationData = function (type, options = {}) { - return new Promise((resolve, reject) => { - var request = { - receiverID: options.receiverID || DEFAULT.adminID, - senderID: options.senderID || undefined, - application: options.application || DEFAULT.application, - type: type, - comment: options.comment || undefined, - lowerVectorClock: options.lowerVectorClock || undefined, - upperVectorClock: options.upperVectorClock || undefined, - atVectorClock: options.atVectorClock || undefined, - afterTime: options.afterTime || undefined, - mostRecent: options.mostRecent || undefined, - } - - if (options.callback instanceof Function) { - liveRequest(request.receiverID, request, options.callback) - .then(result => resolve(result)) - .catch(error => reject(error)) - } else { - if (options.method === "POST") - request = { - time: Date.now(), - request - }; - singleRequest(request.receiverID, request, options.method || "GET") - .then(data => resolve(data)).catch(error => reject(error)) - } - }) - } - - /*(NEEDS UPDATE) - //delete data from supernode cloud (received only) - floCloudAPI.deleteApplicationData = function(vectorClocks, options = {}) { - return new Promise((resolve, reject) => { - var delreq = { - requestorID: user.id, - pubKey: user.public, - time: Date.now(), - delete: (Array.isArray(vectorClocks) ? vectorClocks : [vectorClocks]), - application: options.application || DEFAULT.application - } - let hashcontent = ["time", "application", "delete"] - .map(d => delreq[d]).join("|") - delreq.sign = user.sign(hashcontent) - singleRequest(delreq.requestorID, delreq).then(result => { - let success = [], - failed = []; - result.forEach(r => r.status === 'fulfilled' ? - success.push(r.value) : failed.push(r.reason)); - resolve({ - success, - failed - }) - }).catch(error => reject(error)) - }) - } - */ - /*(NEEDS UPDATE) - //edit comment of data in supernode cloud (mutable comments only) - floCloudAPI.editApplicationData = function(vectorClock, newComment, oldData, options = {}) { - return new Promise((resolve, reject) => { - let p0 - if (!oldData) { - options.atVectorClock = vectorClock; - options.callback = false; - p0 = requestApplicationData(false, options) - } else - p0 = Promise.resolve({ - vectorClock: { - ...oldData - } - }) - p0.then(d => { - if (d.senderID != user.id) - return reject("Invalid requestorID") - else if (!d.comment.startsWith("EDIT:")) - return reject("Data immutable") - let data = { - requestorID: user.id, - receiverID: d.receiverID, - time: Date.now(), - application: d.application, - edit: { - vectorClock: vectorClock, - comment: newComment - } - } - d.comment = data.edit.comment; - let hashcontent = ["receiverID", "time", "application", "type", "message", - "comment" - ] - .map(x => d[x]).join("|") - data.edit.sign = user.sign(hashcontent) - singleRequest(data.receiverID, data) - .then(result => resolve("Data comment updated")) - .catch(error => reject(error)) - }) - }) - } - */ - - //tag data in supernode cloud (subAdmin access only) - floCloudAPI.tagApplicationData = function (vectorClock, tag, options = {}) { - return new Promise((resolve, reject) => { - if (!floGlobals.subAdmins.includes(user.id)) - return reject("Only subAdmins can tag data") - var request = { - receiverID: options.receiverID || DEFAULT.adminID, - requestorID: user.id, - pubKey: user.public, - time: Date.now(), - vectorClock: vectorClock, - tag: tag, - } - let hashcontent = ["time", "vectorClock", 'tag'].map(d => request[d]).join("|"); - request.sign = user.sign(hashcontent); - singleRequest(request.receiverID, request) - .then(result => resolve(result)) - .catch(error => reject(error)) - }) - } - - //note data in supernode cloud (receiver only or subAdmin allowed if receiver is adminID) - floCloudAPI.noteApplicationData = function (vectorClock, note, options = {}) { - return new Promise((resolve, reject) => { - var request = { - receiverID: options.receiverID || DEFAULT.adminID, - requestorID: user.id, - pubKey: user.public, - time: Date.now(), - vectorClock: vectorClock, - note: note, - } - let hashcontent = ["time", "vectorClock", 'note'].map(d => request[d]).join("|"); - request.sign = user.sign(hashcontent); - singleRequest(request.receiverID, request) - .then(result => resolve(result)) - .catch(error => reject(error)) - }) - } - - //send general data - floCloudAPI.sendGeneralData = function (message, type, options = {}) { - return new Promise((resolve, reject) => { - if (options.encrypt) { - let encryptionKey = options.encrypt === true ? - floGlobals.settings.encryptionKey : options.encrypt - message = floCrypto.encryptData(JSON.stringify(message), encryptionKey) - } - sendApplicationData(message, type, options) - .then(result => resolve(result)) - .catch(error => reject(error)) - }) - } - - //request general data - floCloudAPI.requestGeneralData = function (type, options = {}) { - return new Promise((resolve, reject) => { - var fk = filterKey(type, options) - lastVC[fk] = parseInt(lastVC[fk]) || 0; - options.afterTime = options.afterTime || lastVC[fk]; - if (options.callback instanceof Function) { - let new_options = Object.create(options) - new_options.callback = (d, e) => { - storeGeneral(fk, d); - options.callback(d, e) - } - requestApplicationData(type, new_options) - .then(result => resolve(result)) - .catch(error => reject(error)) - } else { - requestApplicationData(type, options).then(dataSet => { - storeGeneral(fk, objectifier(dataSet)) - resolve(dataSet) - }).catch(error => reject(error)) - } - }) - } - - //request an object data from supernode cloud - floCloudAPI.requestObjectData = function (objectName, options = {}) { - return new Promise((resolve, reject) => { - options.lowerVectorClock = options.lowerVectorClock || lastVC[objectName] + 1; - options.senderID = [false, null].includes(options.senderID) ? null : - options.senderID || floGlobals.subAdmins; - options.mostRecent = true; - options.comment = 'RESET'; - let callback = null; - if (options.callback instanceof Function) { - let old_callback = options.callback; - callback = (d, e) => { - updateObject(objectName, d); - old_callback(d, e); - } - delete options.callback; - } - requestApplicationData(objectName, options).then(dataSet => { - updateObject(objectName, objectifier(dataSet)); - delete options.comment; - options.lowerVectorClock = lastVC[objectName] + 1; - delete options.mostRecent; - if (callback) { - let new_options = Object.create(options); - new_options.callback = callback; - requestApplicationData(objectName, new_options) - .then(result => resolve(result)) - .catch(error => reject(error)) - } else { - requestApplicationData(objectName, options).then(dataSet => { - updateObject(objectName, objectifier(dataSet)) - resolve(appObjects[objectName]) - }).catch(error => reject(error)) - } - }).catch(error => reject(error)) - }) - } - - floCloudAPI.closeRequest = function (requestID) { - return new Promise((resolve, reject) => { - let conn = _liveRequest[requestID] - if (!conn) - return reject('Request not found') - conn.onclose = evt => { - delete _liveRequest[requestID]; - resolve('Request connection closed') - } - conn.close() - }) - } - - //reset or initialize an object and send it to cloud - floCloudAPI.resetObjectData = function (objectName, options = {}) { - return new Promise((resolve, reject) => { - let message = { - reset: appObjects[objectName] - } - options.comment = 'RESET'; - sendApplicationData(message, objectName, options).then(result => { - lastCommit.set(objectName); - resolve(result) - }).catch(error => reject(error)) - }) - } - - //update the diff and send it to cloud - floCloudAPI.updateObjectData = function (objectName, options = {}) { - return new Promise((resolve, reject) => { - let message = { - diff: diff.find(lastCommit.get(objectName), appObjects[ - objectName]) - } - options.comment = 'UPDATE'; - sendApplicationData(message, objectName, options).then(result => { - lastCommit.set(objectName); - resolve(result) - }).catch(error => reject(error)) - }) - } - - /* - Functions: - findDiff(original, updatedObj) returns an object with the added, deleted and updated differences - mergeDiff(original, allDiff) returns a new object from original object merged with all differences (allDiff is returned object of findDiff) - */ - var diff = (function () { - const isDate = d => d instanceof Date; - const isEmpty = o => Object.keys(o).length === 0; - const isObject = o => o != null && typeof o === 'object'; - const properObject = o => isObject(o) && !o.hasOwnProperty ? { - ...o - } : o; - const getLargerArray = (l, r) => l.length > r.length ? l : r; - - const preserve = (diff, left, right) => { - if (!isObject(diff)) return diff; - return Object.keys(diff).reduce((acc, key) => { - const leftArray = left[key]; - const rightArray = right[key]; - if (Array.isArray(leftArray) && Array.isArray(rightArray)) { - const array = [...getLargerArray(leftArray, rightArray)]; - return { - ...acc, - [key]: array.reduce((acc2, item, index) => { - if (diff[key].hasOwnProperty(index)) { - acc2[index] = preserve(diff[key][index], leftArray[index], rightArray[index]); // diff recurse and check for nested arrays - return acc2; - } - delete acc2[index]; // no diff aka empty - return acc2; - }, array) - }; - } - return { - ...acc, - [key]: diff[key] - }; - }, {}); - }; - - const updatedDiff = (lhs, rhs) => { - if (lhs === rhs) return {}; - if (!isObject(lhs) || !isObject(rhs)) return rhs; - const l = properObject(lhs); - const r = properObject(rhs); - if (isDate(l) || isDate(r)) { - if (l.valueOf() == r.valueOf()) return {}; - return r; - } - return Object.keys(r).reduce((acc, key) => { - if (l.hasOwnProperty(key)) { - const difference = updatedDiff(l[key], r[key]); - if (isObject(difference) && isEmpty(difference) && !isDate(difference)) return acc; - return { - ...acc, - [key]: difference - }; - } - return acc; - }, {}); - }; - - - const diff = (lhs, rhs) => { - if (lhs === rhs) return {}; // equal return no diff - if (!isObject(lhs) || !isObject(rhs)) return rhs; // return updated rhs - const l = properObject(lhs); - const r = properObject(rhs); - const deletedValues = Object.keys(l).reduce((acc, key) => { - return r.hasOwnProperty(key) ? acc : { - ...acc, - [key]: null - }; - }, {}); - if (isDate(l) || isDate(r)) { - if (l.valueOf() == r.valueOf()) return {}; - return r; - } - return Object.keys(r).reduce((acc, key) => { - if (!l.hasOwnProperty(key)) return { - ...acc, - [key]: r[key] - }; // return added r key - const difference = diff(l[key], r[key]); - if (isObject(difference) && isEmpty(difference) && !isDate(difference)) return acc; // return no diff - return { - ...acc, - [key]: difference - }; // return updated key - }, deletedValues); - }; - - const addedDiff = (lhs, rhs) => { - if (lhs === rhs || !isObject(lhs) || !isObject(rhs)) return {}; - const l = properObject(lhs); - const r = properObject(rhs); - return Object.keys(r).reduce((acc, key) => { - if (l.hasOwnProperty(key)) { - const difference = addedDiff(l[key], r[key]); - if (isObject(difference) && isEmpty(difference)) return acc; - return { - ...acc, - [key]: difference - }; - } - return { - ...acc, - [key]: r[key] - }; - }, {}); - }; - - const arrayDiff = (lhs, rhs) => { - if (lhs === rhs) return {}; // equal return no diff - if (!isObject(lhs) || !isObject(rhs)) return rhs; // return updated rhs - const l = properObject(lhs); - const r = properObject(rhs); - const deletedValues = Object.keys(l).reduce((acc, key) => { - return r.hasOwnProperty(key) ? acc : { - ...acc, - [key]: null - }; - }, {}); - if (isDate(l) || isDate(r)) { - if (l.valueOf() == r.valueOf()) return {}; - return r; - } - if (Array.isArray(r) && Array.isArray(l)) { - const deletedValues = l.reduce((acc, item, index) => { - return r.hasOwnProperty(index) ? acc.concat(item) : acc.concat(null); - }, []); - return r.reduce((acc, rightItem, index) => { - if (!deletedValues.hasOwnProperty(index)) { - return acc.concat(rightItem); - } - const leftItem = l[index]; - const difference = diff(rightItem, leftItem); - if (isObject(difference) && isEmpty(difference) && !isDate(difference)) { - delete acc[index]; - return acc; // return no diff - } - return acc.slice(0, index).concat(rightItem).concat(acc.slice(index + 1)); // return updated key - }, deletedValues); - } - - return Object.keys(r).reduce((acc, key) => { - if (!l.hasOwnProperty(key)) return { - ...acc, - [key]: r[key] - }; // return added r key - const difference = diff(l[key], r[key]); - if (isObject(difference) && isEmpty(difference) && !isDate(difference)) return acc; // return no diff - return { - ...acc, - [key]: difference - }; // return updated key - }, deletedValues); - }; - - const deletedDiff = (lhs, rhs) => { - if (lhs === rhs || !isObject(lhs) || !isObject(rhs)) return {}; - const l = properObject(lhs); - const r = properObject(rhs); - return Object.keys(l).reduce((acc, key) => { - if (r.hasOwnProperty(key)) { - const difference = deletedDiff(l[key], r[key]); - if (isObject(difference) && isEmpty(difference)) return acc; - return { - ...acc, - [key]: difference - }; - } - return { - ...acc, - [key]: null - }; - }, {}); - }; - - const mergeRecursive = (obj1, obj2, deleteMode = false) => { - for (var p in obj2) { - try { - if (obj2[p].constructor == Object) - obj1[p] = mergeRecursive(obj1[p], obj2[p], deleteMode); - // Property in destination object set; update its value. - else if (Array.isArray(obj2[p])) { - // obj1[p] = []; - if (obj2[p].length < 1) - obj1[p] = obj2[p]; - else - obj1[p] = mergeRecursive(obj1[p], obj2[p], deleteMode); - } else - obj1[p] = deleteMode && obj2[p] === null ? undefined : obj2[p]; - } catch (e) { - // Property in destination object not set; create it and set its value. - obj1[p] = deleteMode && obj2[p] === null ? undefined : obj2[p]; - } - } - return obj1; - } - - const cleanse = (obj) => { - Object.keys(obj).forEach(key => { - var value = obj[key]; - if (typeof value === "object" && value !== null) - obj[key] = cleanse(value); - else if (typeof value === 'undefined') - delete obj[key]; // undefined, remove it - }); - if (Array.isArray(obj)) - obj = obj.filter(v => typeof v !== 'undefined'); - return obj; - } - - - const findDiff = (lhs, rhs) => ({ - added: addedDiff(lhs, rhs), - deleted: deletedDiff(lhs, rhs), - updated: updatedDiff(lhs, rhs), - }); - - /*obj is original object or array, diff is the output of findDiff */ - const mergeDiff = (obj, diff) => { - if (Object.keys(diff.updated).length !== 0) - obj = mergeRecursive(obj, diff.updated) - if (Object.keys(diff.deleted).length !== 0) { - obj = mergeRecursive(obj, diff.deleted, true) - obj = cleanse(obj) - } - if (Object.keys(diff.added).length !== 0) - obj = mergeRecursive(obj, diff.added) - return obj - } - - return { - find: findDiff, - merge: mergeDiff - } - })(); - - -})('object' === typeof module ? module.exports : window.floCloudAPI = {}); \ No newline at end of file diff --git a/floDapps.js b/floDapps.js deleted file mode 100644 index 4d525a2..0000000 --- a/floDapps.js +++ /dev/null @@ -1,845 +0,0 @@ -(function (EXPORTS) { //floDapps v2.4.0 - /* General functions for FLO Dapps*/ - 'use strict'; - const floDapps = EXPORTS; - - const DEFAULT = { - root: "floDapps", - application: floGlobals.application, - adminID: floGlobals.adminID - }; - - Object.defineProperties(floDapps, { - application: { - get: () => DEFAULT.application - }, - adminID: { - get: () => DEFAULT.adminID - }, - root: { - get: () => DEFAULT.root - } - }); - - var user_priv_raw, aes_key, user_priv_wrap; //private variable inside capsule - const raw_user = { - get private() { - if (!user_priv_raw) - throw "User not logged in"; - return Crypto.AES.decrypt(user_priv_raw, aes_key); - } - } - - var user_id, user_public, user_private; - const user = floDapps.user = { - get id() { - if (!user_id) - throw "User not logged in"; - return user_id; - }, - get public() { - if (!user_public) - throw "User not logged in"; - return user_public; - }, - get private() { - if (!user_private) - throw "User not logged in"; - else if (user_private instanceof Function) - return user_private(); - else - return Crypto.AES.decrypt(user_private, aes_key); - }, - sign(message) { - return floCrypto.signData(message, raw_user.private); - }, - decrypt(data) { - return floCrypto.decryptData(data, raw_user.private); - }, - encipher(message) { - return Crypto.AES.encrypt(message, raw_user.private); - }, - decipher(data) { - return Crypto.AES.decrypt(data, raw_user.private); - }, - get db_name() { - return "floDapps#" + floCrypto.toFloID(user.id); - }, - lock() { - user_private = user_priv_wrap; - }, - async unlock() { - if (await user.private === raw_user.private) - user_private = user_priv_raw; - }, - get_contact(id) { - if (!user.contacts) - throw "Contacts not available"; - else if (user.contacts[id]) - return user.contacts[id]; - else { - let id_raw = floCrypto.decodeAddr(id).hex; - for (let i in user.contacts) - if (floCrypto.decodeAddr(i).hex == id_raw) - return user.contacts[i]; - } - }, - get_pubKey(id) { - if (!user.pubKeys) - throw "Contacts not available"; - else if (user.pubKeys[id]) - return user.pubKeys[id]; - else { - let id_raw = floCrypto.decodeAddr(id).hex; - for (let i in user.pubKeys) - if (floCrypto.decodeAddr(i).hex == id_raw) - return user.pubKeys[i]; - } - }, - clear() { - user_id = user_public = user_private = undefined; - user_priv_raw = aes_key = undefined; - delete user.contacts; - delete user.pubKeys; - delete user.messages; - } - }; - - Object.defineProperties(window, { - myFloID: { - get: () => { - try { - return user.id; - } catch { - return; - } - } - }, - myUserID: { - get: () => { - try { - return user.id; - } catch { - return; - } - } - }, - myPubKey: { - get: () => { - try { - return user.public; - } catch { - return; - } - } - }, - myPrivKey: { - get: () => { - try { - return user.private; - } catch { - return; - } - } - } - }); - - var subAdmins, trustedIDs, settings; - Object.defineProperties(floGlobals, { - subAdmins: { - get: () => subAdmins - }, - trustedIDs: { - get: () => trustedIDs - }, - settings: { - get: () => settings - }, - contacts: { - get: () => user.contacts - }, - pubKeys: { - get: () => user.pubKeys - }, - messages: { - get: () => user.messages - } - }) - - function initIndexedDB() { - return new Promise((resolve, reject) => { - var obs_g = { - //general - lastTx: {}, - //supernode (cloud list) - supernodes: { - indexes: { - uri: null, - pubKey: null - } - } - } - var obs_a = { - //login credentials - credentials: {}, - //for Dapps - subAdmins: {}, - trustedIDs: {}, - settings: {}, - appObjects: {}, - generalData: {}, - lastVC: {} - } - //add other given objectStores - initIndexedDB.appObs = initIndexedDB.appObs || {} - for (let o in initIndexedDB.appObs) - if (!(o in obs_a)) - obs_a[o] = initIndexedDB.appObs[o] - Promise.all([ - compactIDB.initDB(DEFAULT.application, obs_a), - compactIDB.initDB(DEFAULT.root, obs_g) - ]).then(result => { - compactIDB.setDefaultDB(DEFAULT.application) - resolve("IndexedDB App Storage Initated Successfully") - }).catch(error => reject(error)); - }) - } - - function initUserDB() { - return new Promise((resolve, reject) => { - var obs = { - contacts: {}, - pubKeys: {}, - messages: {} - } - compactIDB.initDB(user.db_name, obs).then(result => { - resolve("UserDB Initated Successfully") - }).catch(error => reject('Init userDB failed')); - }) - } - - function loadUserDB() { - return new Promise((resolve, reject) => { - var loadData = ["contacts", "pubKeys", "messages"] - var promises = [] - for (var i = 0; i < loadData.length; i++) - promises[i] = compactIDB.readAllData(loadData[i], user.db_name) - Promise.all(promises).then(results => { - for (var i = 0; i < loadData.length; i++) - user[loadData[i]] = results[i] - resolve("Loaded Data from userDB") - }).catch(error => reject('Load userDB failed')) - }) - } - - const startUpOptions = { - cloud: true, - app_config: true, - } - - floDapps.startUpOptions = { - set app_config(val) { - if (val === true || val === false) - startUpOptions.app_config = val; - }, - get app_config() { return startUpOptions.app_config }, - - set cloud(val) { - if (val === true || val === false) - startUpOptions.cloud = val; - }, - get cloud() { return startUpOptions.cloud }, - } - - const startUpFunctions = []; - - startUpFunctions.push(function readSupernodeListFromAPI() { - return new Promise((resolve, reject) => { - if (!startUpOptions.cloud) - return resolve("No cloud for this app"); - compactIDB.readData("lastTx", floCloudAPI.SNStorageID, DEFAULT.root).then(lastTx => { - var query_options = { sentOnly: true, pattern: floCloudAPI.SNStorageName }; - if (typeof lastTx == 'number') //lastTx is tx count (*backward support) - query_options.ignoreOld = lastTx; - else if (typeof lastTx == 'string') //lastTx is txid of last tx - query_options.after = lastTx; - //fetch data from flosight - floBlockchainAPI.readData(floCloudAPI.SNStorageID, query_options).then(result => { - for (var i = result.data.length - 1; i >= 0; i--) { - var content = JSON.parse(result.data[i])[floCloudAPI.SNStorageName]; - for (let sn in content.removeNodes) - compactIDB.removeData("supernodes", sn, DEFAULT.root); - for (let sn in content.newNodes) - compactIDB.writeData("supernodes", content.newNodes[sn], sn, DEFAULT.root); - for (let sn in content.updateNodes) - compactIDB.readData("supernodes", sn, DEFAULT.root).then(r => { - r = r || {} - r.uri = content.updateNodes[sn]; - compactIDB.writeData("supernodes", r, sn, DEFAULT.root); - }); - } - compactIDB.writeData("lastTx", result.lastItem, floCloudAPI.SNStorageID, DEFAULT.root); - compactIDB.readAllData("supernodes", DEFAULT.root).then(nodes => { - floCloudAPI.init(nodes) - .then(result => resolve("Loaded Supernode list\n" + result)) - .catch(error => reject(error)) - }) - }) - }).catch(error => reject(error)) - }) - }); - - startUpFunctions.push(function readAppConfigFromAPI() { - return new Promise((resolve, reject) => { - if (!startUpOptions.app_config) - return resolve("No configs for this app"); - compactIDB.readData("lastTx", `${DEFAULT.application}|${DEFAULT.adminID}`, DEFAULT.root).then(lastTx => { - var query_options = { sentOnly: true, pattern: DEFAULT.application }; - if (typeof lastTx == 'number') //lastTx is tx count (*backward support) - query_options.ignoreOld = lastTx; - else if (typeof lastTx == 'string') //lastTx is txid of last tx - query_options.after = lastTx; - //fetch data from flosight - floBlockchainAPI.readData(DEFAULT.adminID, query_options).then(result => { - for (var i = result.data.length - 1; i >= 0; i--) { - var content = JSON.parse(result.data[i])[DEFAULT.application]; - if (!content || typeof content !== "object") - continue; - if (Array.isArray(content.removeSubAdmin)) - for (var j = 0; j < content.removeSubAdmin.length; j++) - compactIDB.removeData("subAdmins", content.removeSubAdmin[j]); - if (Array.isArray(content.addSubAdmin)) - for (var k = 0; k < content.addSubAdmin.length; k++) - compactIDB.writeData("subAdmins", true, content.addSubAdmin[k]); - if (Array.isArray(content.removeTrustedID)) - for (var j = 0; j < content.removeTrustedID.length; j++) - compactIDB.removeData("trustedIDs", content.removeTrustedID[j]); - if (Array.isArray(content.addTrustedID)) - for (var k = 0; k < content.addTrustedID.length; k++) - compactIDB.writeData("trustedIDs", true, content.addTrustedID[k]); - if (content.settings) - for (let l in content.settings) - compactIDB.writeData("settings", content.settings[l], l) - } - compactIDB.writeData("lastTx", result.lastItem, `${DEFAULT.application}|${DEFAULT.adminID}`, DEFAULT.root); - compactIDB.readAllData("subAdmins").then(result => { - subAdmins = Object.keys(result); - compactIDB.readAllData("trustedIDs").then(result => { - trustedIDs = Object.keys(result); - compactIDB.readAllData("settings").then(result => { - settings = result; - resolve("Read app configuration from blockchain"); - }) - }) - }) - }) - }).catch(error => reject(error)) - }) - }); - - startUpFunctions.push(function loadDataFromAppIDB() { - return new Promise((resolve, reject) => { - if (!startUpOptions.cloud) - return resolve("No cloud for this app"); - var loadData = ["appObjects", "generalData", "lastVC"] - var promises = [] - for (var i = 0; i < loadData.length; i++) - promises[i] = compactIDB.readAllData(loadData[i]) - Promise.all(promises).then(results => { - for (var i = 0; i < loadData.length; i++) - floGlobals[loadData[i]] = results[i] - resolve("Loaded Data from app IDB") - }).catch(error => reject(error)) - }) - }); - - var keyInput = type => new Promise((resolve, reject) => { - let inputVal = prompt(`Enter ${type}: `) - if (inputVal === null) - reject(null) - else - resolve(inputVal) - }); - - function getCredentials() { - - const readSharesFromIDB = indexArr => new Promise((resolve, reject) => { - var promises = [] - for (var i = 0; i < indexArr.length; i++) - promises.push(compactIDB.readData('credentials', indexArr[i])) - Promise.all(promises).then(shares => { - var secret = floCrypto.retrieveShamirSecret(shares) - if (secret) - resolve(secret) - else - reject("Shares are insufficient or incorrect") - }).catch(error => { - clearCredentials(); - location.reload(); - }) - }); - - const writeSharesToIDB = (shares, i = 0, resultIndexes = []) => new Promise(resolve => { - if (i >= shares.length) - return resolve(resultIndexes) - var n = floCrypto.randInt(0, 100000) - compactIDB.addData("credentials", shares[i], n).then(res => { - resultIndexes.push(n) - writeSharesToIDB(shares, i + 1, resultIndexes) - .then(result => resolve(result)) - }).catch(error => { - writeSharesToIDB(shares, i, resultIndexes) - .then(result => resolve(result)) - }) - }); - - const getPrivateKeyCredentials = () => new Promise((resolve, reject) => { - var indexArr = localStorage.getItem(`${DEFAULT.application}#privKey`) - if (indexArr) { - readSharesFromIDB(JSON.parse(indexArr)) - .then(result => resolve(result)) - .catch(error => reject(error)) - } else { - var privKey; - keyInput("PRIVATE_KEY").then(result => { - if (!result) - return reject("Empty Private Key") - var floID = floCrypto.getFloID(result) - if (!floID || !floCrypto.validateFloID(floID)) - return reject("Invalid Private Key") - privKey = result; - }).catch(error => { - console.log(error, "Generating Random Keys") - privKey = floCrypto.generateNewID().privKey - }).finally(_ => { - if (!privKey) - return; - var threshold = floCrypto.randInt(10, 20) - var shares = floCrypto.createShamirsSecretShares(privKey, threshold, threshold) - writeSharesToIDB(shares).then(resultIndexes => { - //store index keys in localStorage - localStorage.setItem(`${DEFAULT.application}#privKey`, JSON.stringify(resultIndexes)) - //also add a dummy privatekey to the IDB - var randomPrivKey = floCrypto.generateNewID().privKey - var randomThreshold = floCrypto.randInt(10, 20) - var randomShares = floCrypto.createShamirsSecretShares(randomPrivKey, randomThreshold, randomThreshold) - writeSharesToIDB(randomShares) - //resolve private Key - resolve(privKey) - }) - }) - } - }); - - const checkIfPinRequired = key => new Promise((resolve, reject) => { - if (key.length == 52) - resolve(key) - else { - keyInput("PIN/Password").then(pwd => { - try { - let privKey = Crypto.AES.decrypt(key, pwd); - resolve(privKey) - } catch (error) { - reject("Access Denied: Incorrect PIN/Password") - } - }).catch(error => reject("Access Denied: PIN/Password required")) - } - }); - - return new Promise((resolve, reject) => { - getPrivateKeyCredentials().then(key => { - checkIfPinRequired(key).then(privKey => { - try { - user_public = floCrypto.getPubKeyHex(privKey); - user_id = floCrypto.getAddress(privKey); - if (startUpOptions.cloud) - floCloudAPI.user(user_id, privKey); //Set user for floCloudAPI - user_priv_wrap = () => checkIfPinRequired(key); - let n = floCrypto.randInt(12, 20); - aes_key = floCrypto.randString(n); - user_priv_raw = Crypto.AES.encrypt(privKey, aes_key); - user_private = user_priv_wrap; - resolve('Login Credentials loaded successful') - } catch (error) { - console.log(error) - reject("Corrupted Private Key") - } - }).catch(error => reject(error)) - }).catch(error => reject(error)) - }) - } - - var startUpLog = (status, log) => status ? console.log(log) : console.error(log); - - const callStartUpFunction = i => new Promise((resolve, reject) => { - startUpFunctions[i]().then(result => { - callStartUpFunction.completed += 1; - startUpLog(true, `${result}\nCompleted ${callStartUpFunction.completed}/${callStartUpFunction.total} Startup functions`) - resolve(true) - }).catch(error => { - callStartUpFunction.failed += 1; - startUpLog(false, `${error}\nFailed ${callStartUpFunction.failed}/${callStartUpFunction.total} Startup functions`) - reject(false) - }) - }); - - var _midFunction; - const midStartUp = () => new Promise((res, rej) => { - if (_midFunction instanceof Function) { - _midFunction() - .then(r => res("Mid startup function completed")) - .catch(e => rej("Mid startup function failed")) - } else - res("No mid startup function") - }); - - const callAndLog = p => new Promise((res, rej) => { - p.then(r => { - startUpLog(true, r) - res(r) - }).catch(e => { - startUpLog(false, e) - rej(e) - }) - }); - - floDapps.launchStartUp = function () { - return new Promise((resolve, reject) => { - initIndexedDB().then(log => { - console.log(log) - callStartUpFunction.total = startUpFunctions.length; - callStartUpFunction.completed = 0; - callStartUpFunction.failed = 0; - let p1 = new Promise((res, rej) => { - Promise.all(startUpFunctions.map((f, i) => callStartUpFunction(i))).then(r => { - callAndLog(midStartUp()) - .then(r => res(true)) - .catch(e => rej(false)) - }) - }); - let p2 = new Promise((res, rej) => { - callAndLog(getCredentials()).then(r => { - callAndLog(initUserDB()).then(r => { - callAndLog(loadUserDB()) - .then(r => res(true)) - .catch(e => rej(false)) - }).catch(e => rej(false)) - }).catch(e => rej(false)) - }) - Promise.all([p1, p2]) - .then(r => resolve('App Startup finished successful')) - .catch(e => reject('App Startup failed')) - }).catch(error => { - startUpLog(false, error); - reject("App database initiation failed") - }) - }) - } - - floDapps.addStartUpFunction = fn => fn instanceof Function && !startUpFunctions.includes(fn) ? startUpFunctions.push(fn) : false; - - floDapps.setMidStartup = fn => fn instanceof Function ? _midFunction = fn : false; - - floDapps.setCustomStartupLogger = fn => fn instanceof Function ? startUpLog = fn : false; - - floDapps.setCustomPrivKeyInput = fn => fn instanceof Function ? keyInput = fn : false; - - floDapps.setAppObjectStores = appObs => initIndexedDB.appObs = appObs; - - floDapps.storeContact = function (floID, name) { - return new Promise((resolve, reject) => { - if (!floCrypto.validateAddr(floID)) - return reject("Invalid floID!") - compactIDB.writeData("contacts", name, floID, user.db_name).then(result => { - user.contacts[floID] = name; - resolve("Contact stored") - }).catch(error => reject(error)) - }); - } - - floDapps.storePubKey = function (floID, pubKey) { - return new Promise((resolve, reject) => { - if (floID in user.pubKeys) - return resolve("pubKey already stored") - if (!floCrypto.validateAddr(floID)) - return reject("Invalid floID!") - if (!floCrypto.verifyPubKey(pubKey, floID)) - return reject("Incorrect pubKey") - compactIDB.writeData("pubKeys", pubKey, floID, user.db_name).then(result => { - user.pubKeys[floID] = pubKey; - resolve("pubKey stored") - }).catch(error => reject(error)) - }); - } - - floDapps.sendMessage = function (floID, message) { - return new Promise((resolve, reject) => { - let options = { - receiverID: floID, - application: DEFAULT.root, - comment: DEFAULT.application - } - if (floID in user.pubKeys) - message = floCrypto.encryptData(JSON.stringify(message), user.pubKeys[floID]) - floCloudAPI.sendApplicationData(message, "Message", options) - .then(result => resolve(result)) - .catch(error => reject(error)) - }) - } - - floDapps.requestInbox = function (callback) { - return new Promise((resolve, reject) => { - let lastVC = Object.keys(user.messages).sort().pop() - let options = { - receiverID: user.id, - application: DEFAULT.root, - lowerVectorClock: lastVC + 1 - } - let privKey = raw_user.private; - options.callback = (d, e) => { - for (let v in d) { - try { - if (d[v].message instanceof Object && "secret" in d[v].message) - d[v].message = floCrypto.decryptData(d[v].message, privKey) - } catch (error) { } - compactIDB.writeData("messages", d[v], v, user.db_name) - user.messages[v] = d[v] - } - if (callback instanceof Function) - callback(d, e) - } - floCloudAPI.requestApplicationData("Message", options) - .then(result => resolve(result)) - .catch(error => reject(error)) - }) - } - - floDapps.manageAppConfig = function (adminPrivKey, addList, rmList, settings) { - return new Promise((resolve, reject) => { - if (!startUpOptions.app_config) - return reject("No configs for this app"); - if (!Array.isArray(addList) || !addList.length) addList = undefined; - if (!Array.isArray(rmList) || !rmList.length) rmList = undefined; - if (!settings || typeof settings !== "object" || !Object.keys(settings).length) settings = undefined; - if (!addList && !rmList && !settings) - return reject("No configuration change") - var floData = { - [DEFAULT.application]: { - addSubAdmin: addList, - removeSubAdmin: rmList, - settings: settings - } - } - var floID = floCrypto.getFloID(adminPrivKey) - if (floID != DEFAULT.adminID) - reject('Access Denied for Admin privilege') - else - floBlockchainAPI.writeData(floID, JSON.stringify(floData), adminPrivKey) - .then(result => resolve(['Updated App Configuration', result])) - .catch(error => reject(error)) - }) - } - - floDapps.manageAppTrustedIDs = function (adminPrivKey, addList, rmList) { - return new Promise((resolve, reject) => { - if (!startUpOptions.app_config) - return reject("No configs for this app"); - if (!Array.isArray(addList) || !addList.length) addList = undefined; - if (!Array.isArray(rmList) || !rmList.length) rmList = undefined; - if (!addList && !rmList) - return reject("No change in list") - var floData = { - [DEFAULT.application]: { - addTrustedID: addList, - removeTrustedID: rmList - } - } - var floID = floCrypto.getFloID(adminPrivKey) - if (floID != DEFAULT.adminID) - reject('Access Denied for Admin privilege') - else - floBlockchainAPI.writeData(floID, JSON.stringify(floData), adminPrivKey) - .then(result => resolve(['Updated App Configuration', result])) - .catch(error => reject(error)) - }) - } - - const clearCredentials = floDapps.clearCredentials = function () { - return new Promise((resolve, reject) => { - compactIDB.clearData('credentials', DEFAULT.application).then(result => { - localStorage.removeItem(`${DEFAULT.application}#privKey`); - user.clear(); - resolve("privKey credentials deleted!") - }).catch(error => reject(error)) - }) - } - - floDapps.deleteUserData = function (credentials = false) { - return new Promise((resolve, reject) => { - let p = [] - p.push(compactIDB.deleteDB(user.db_name)) - if (credentials) - p.push(clearCredentials()) - Promise.all(p) - .then(result => resolve('User database(local) deleted')) - .catch(error => reject(error)) - }) - } - - floDapps.deleteAppData = function () { - return new Promise((resolve, reject) => { - compactIDB.deleteDB(DEFAULT.application).then(result => { - localStorage.removeItem(`${DEFAULT.application}#privKey`) - user.clear(); - compactIDB.removeData('lastTx', `${DEFAULT.application}|${DEFAULT.adminID}`, DEFAULT.root) - .then(result => resolve("App database(local) deleted")) - .catch(error => reject(error)) - }).catch(error => reject(error)) - }) - } - - floDapps.securePrivKey = function (pwd) { - return new Promise(async (resolve, reject) => { - let indexArr = localStorage.getItem(`${DEFAULT.application}#privKey`) - if (!indexArr) - return reject("PrivKey not found"); - indexArr = JSON.parse(indexArr) - let encryptedKey = Crypto.AES.encrypt(await user.private, pwd); - let threshold = indexArr.length; - let shares = floCrypto.createShamirsSecretShares(encryptedKey, threshold, threshold) - let promises = []; - let overwriteFn = (share, index) => - compactIDB.writeData("credentials", share, index, DEFAULT.application); - for (var i = 0; i < threshold; i++) - promises.push(overwriteFn(shares[i], indexArr[i])); - Promise.all(promises) - .then(results => resolve("Private Key Secured")) - .catch(error => reject(error)) - }) - } - - floDapps.verifyPin = function (pin = null) { - const readSharesFromIDB = function (indexArr) { - return new Promise((resolve, reject) => { - var promises = [] - for (var i = 0; i < indexArr.length; i++) - promises.push(compactIDB.readData('credentials', indexArr[i])) - Promise.all(promises).then(shares => { - var secret = floCrypto.retrieveShamirSecret(shares) - console.info(shares, secret) - if (secret) - resolve(secret) - else - reject("Shares are insufficient or incorrect") - }).catch(error => { - clearCredentials(); - location.reload(); - }) - }) - } - return new Promise((resolve, reject) => { - var indexArr = localStorage.getItem(`${DEFAULT.application}#privKey`) - console.info(indexArr) - if (!indexArr) - reject('No login credentials found') - readSharesFromIDB(JSON.parse(indexArr)).then(key => { - if (key.length == 52) { - if (pin === null) - resolve("Private key not secured") - else - reject("Private key not secured") - } else { - if (pin === null) - return reject("PIN/Password required") - try { - let privKey = Crypto.AES.decrypt(key, pin); - resolve("PIN/Password verified") - } catch (error) { - reject("Incorrect PIN/Password") - } - } - }).catch(error => reject(error)) - }) - } - - const getNextGeneralData = floDapps.getNextGeneralData = function (type, vectorClock = null, options = {}) { - var fk = floCloudAPI.util.filterKey(type, options) - vectorClock = vectorClock || getNextGeneralData[fk] || '0'; - var filteredResult = {} - if (floGlobals.generalData[fk]) { - for (let d in floGlobals.generalData[fk]) - if (d > vectorClock) - filteredResult[d] = JSON.parse(JSON.stringify(floGlobals.generalData[fk][d])) - } else if (options.comment) { - let comment = options.comment; - delete options.comment; - let fk = floCloudAPI.util.filterKey(type, options); - for (let d in floGlobals.generalData[fk]) - if (d > vectorClock && floGlobals.generalData[fk][d].comment == comment) - filteredResult[d] = JSON.parse(JSON.stringify(floGlobals.generalData[fk][d])) - } - if (options.decrypt) { - let decryptionKey = (options.decrypt === true) ? raw_user.private : options.decrypt; - if (!Array.isArray(decryptionKey)) - decryptionKey = [decryptionKey]; - for (let f in filteredResult) { - let data = filteredResult[f] - try { - if (data.message instanceof Object && "secret" in data.message) { - for (let key of decryptionKey) { - try { - let tmp = floCrypto.decryptData(data.message, key) - data.message = JSON.parse(tmp) - break; - } catch (error) { } - } - } - } catch (error) { } - } - } - getNextGeneralData[fk] = Object.keys(filteredResult).sort().pop(); - return filteredResult; - } - - const syncData = floDapps.syncData = {}; - - syncData.oldDevice = () => new Promise((resolve, reject) => { - let sync = { - contacts: user.contacts, - pubKeys: user.pubKeys, - messages: user.messages - } - let message = Crypto.AES.encrypt(JSON.stringify(sync), raw_user.private) - let options = { - receiverID: user.id, - application: DEFAULT.root - } - floCloudAPI.sendApplicationData(message, "syncData", options) - .then(result => resolve(result)) - .catch(error => reject(error)) - }); - - syncData.newDevice = () => new Promise((resolve, reject) => { - var options = { - receiverID: user.id, - senderID: user.id, - application: DEFAULT.root, - mostRecent: true, - } - floCloudAPI.requestApplicationData("syncData", options).then(response => { - let vc = Object.keys(response).sort().pop() - let sync = JSON.parse(Crypto.AES.decrypt(response[vc].message, raw_user.private)) - let promises = [] - let store = (key, val, obs) => promises.push(compactIDB.writeData(obs, val, key, user.db_name)); - ["contacts", "pubKeys", "messages"].forEach(c => { - for (let i in sync[c]) { - store(i, sync[c][i], c) - user[c][i] = sync[c][i] - } - }) - Promise.all(promises) - .then(results => resolve("Sync data successful")) - .catch(error => reject(error)) - }).catch(error => reject(error)) - }); -})('object' === typeof module ? module.exports : window.floDapps = {}); \ No newline at end of file diff --git a/index.html b/index.html deleted file mode 100644 index 38e5a0a..0000000 --- a/index.html +++ /dev/null @@ -1,57 +0,0 @@ - - - - - FLO Standard Operators - - - - - - - - - - - - - - - TEST_MODE - (use console) - - - \ No newline at end of file From 42f30a12bbba9769697f3b22b7f1f70a9e29ea69 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Fri, 19 May 2023 01:08:21 +0530 Subject: [PATCH 289/289] Fix for flosight changes --- args/schema.sql | 2 +- docs/scripts/floExchangeAPI.js | 14 ++++++++------ src/main.js | 19 +++++++++++-------- src/services/bobs-fund.js | 31 ++++++++++++++++++------------- src/services/bonds.js | 29 +++++++++++++++++------------ 5 files changed, 55 insertions(+), 40 deletions(-) diff --git a/args/schema.sql b/args/schema.sql index 40cf6e8..16b4d97 100644 --- a/args/schema.sql +++ b/args/schema.sql @@ -2,7 +2,7 @@ CREATE TABLE LastTx( floID CHAR(34) NOT NULL, - num INT, + txid VARCHAR(128), PRIMARY KEY(floID) ); diff --git a/docs/scripts/floExchangeAPI.js b/docs/scripts/floExchangeAPI.js index 44ae667..c737d89 100644 --- a/docs/scripts/floExchangeAPI.js +++ b/docs/scripts/floExchangeAPI.js @@ -1737,13 +1737,15 @@ trusted = new Set(); assets = new Set(); tags = new Set(); - lastTx = 0; + lastTx = undefined; } - floBlockchainAPI.readData(DEFAULT.marketID, { - ignoreOld: lastTx, - sentOnly: true, - pattern: DEFAULT.marketApp - }).then(result => { + + var query_options = { sentOnly: true, pattern: DEFAULT.marketApp }; + if (typeof lastTx == 'string' && /^[0-9a-f]{64}/i.test(lastTx))//lastTx is txid of last tx + query_options.after = lastTx; + else if (!isNaN(lastTx))//lastTx is tx count (*backward support) + query_options.ignoreOld = parseInt(lastTx); + floBlockchainAPI.readData(DEFAULT.marketID, query_options).then(result => { result.data.reverse().forEach(data => { var content = JSON.parse(data)[DEFAULT.marketApp]; //Node List diff --git a/src/main.js b/src/main.js index 15b6186..95b2ad2 100644 --- a/src/main.js +++ b/src/main.js @@ -40,13 +40,16 @@ function refreshData(startup = false) { function refreshDataFromBlockchain() { return new Promise((resolve, reject) => { - DB.query("SELECT num FROM LastTx WHERE floID=?", [floGlobals.adminID]).then(result => { - let lastTx = result.length ? result[0].num : 0; - floBlockchainAPI.readData(floGlobals.adminID, { - ignoreOld: lastTx, - sentOnly: true, - pattern: floGlobals.application - }).then(result => { + DB.query("SELECT txid FROM LastTx WHERE floID=?", [floGlobals.adminID]).then(result => { + var query_options = { sentOnly: true, pattern: floGlobals.application }; + + let lastTx = result.length ? result[0].txid : undefined; + if (typeof lastTx == 'string' && /^[0-9a-f]{64}/i.test(lastTx))//lastTx is txid of last tx + query_options.after = lastTx; + else if (!isNaN(lastTx))//lastTx is tx count (*backward support) + query_options.ignoreOld = parseInt(lastTx); + + floBlockchainAPI.readData(floGlobals.adminID, query_options).then(result => { let promises = [], nodes_change = false, assets_change = false, @@ -96,7 +99,7 @@ function refreshDataFromBlockchain() { promises.push(`UPDATE TagList WHERE tag=? SET ${a}=?`, [t, content.Tag.update[t][a]]); } }); - promises.push(DB.query("INSERT INTO LastTx (floID, num) VALUE (?) ON DUPLICATE KEY UPDATE num=?", [[floGlobals.adminID, result.totalTxs], result.totalTxs])); + promises.push(DB.query("INSERT INTO LastTx (floID, txid) VALUE (?) ON DUPLICATE KEY UPDATE txid=?", [[floGlobals.adminID, result.lastItem], result.lastItem])); //Check if all save process were successful Promise.allSettled(promises).then(results => { //console.debug(results.filter(r => r.status === "rejected")); diff --git a/src/services/bobs-fund.js b/src/services/bobs-fund.js index d4705c9..042100a 100644 --- a/src/services/bobs-fund.js +++ b/src/services/bobs-fund.js @@ -203,16 +203,21 @@ bobsFund.config = { function refreshBlockchainData(nodeList = []) { return new Promise((resolve, reject) => { - DB.query("SELECT num FROM LastTx WHERE floID=?", [bobsFund.config.adminID]).then(result => { - let lastTx = result.length ? result[0].num : 0; - floBlockchainAPI.readData(bobsFund.config.adminID, { - ignoreOld: lastTx, - senders: nodeList.concat(bobsFund.config.adminID), //sentOnly: true, - tx: true, - filter: d => d.startsWith(bobsFund.productStr) - }).then(result => { + DB.query("SELECT txid FROM LastTx WHERE floID=?", [bobsFund.config.adminID]).then(result => { + + var query_options = { + senders: nodeList.concat(bobsFund.config.adminID), + tx: true, filter: d => d.startsWith(bobsFund.productStr) + }; + let lastTx = result.length ? result[0].txid : undefined; + if (typeof lastTx == 'string' && /^[0-9a-f]{64}/i.test(lastTx))//lastTx is txid of last tx + query_options.after = lastTx; + else if (!isNaN(lastTx))//lastTx is tx count (*backward support) + query_options.ignoreOld = parseInt(lastTx); + + floBlockchainAPI.readData(bobsFund.config.adminID, query_options).then(result => { let txQueries = []; - result.data.reverse().forEach(d => { + result.items.reverse().forEach(d => { let fund = bobsFund.parse(d.data); if (d.senders.has(bobsFund.config.adminID) && !/close:/.test(d.data)) { let fund_id = d.data.match(/continue: [a-z0-9]{64}\|/); @@ -221,7 +226,7 @@ function refreshBlockchainData(nodeList = []) { let values = [fund_id, fund.start_date, fund.BTC_base, fund.USD_base, fund.fee, fund.duration]; if (fund.tapoutInterval) values.push(fund.topoutWindow, fund.tapoutInterval.join(',')); - else + else values.push(null, null); txQueries.push(["INSERT INTO BobsFund(fund_id, begin_date, btc_base, usd_base, fee, duration, tapout_window, tapout_interval) VALUE (?) ON DUPLICATE KEY UPDATE fund_id=fund_id", [values]]) } else @@ -240,10 +245,10 @@ function refreshBlockchainData(nodeList = []) { } } }); - txQueries.push(["INSERT INTO LastTx (floID, num) VALUE (?) ON DUPLICATE KEY UPDATE num=?", - [[bobsFund.config.adminID, result.totalTxs], result.totalTxs]]) + txQueries.push(["INSERT INTO LastTx (floID, txid) VALUE (?) ON DUPLICATE KEY UPDATE txid=?", + [[bobsFund.config.adminID, result.lastItem], result.lastItem]]) DB.transaction(txQueries) - .then(_ => resolve(result.totalTxs)) + .then(_ => resolve(result.lastItem)) .catch(error => reject(["Bobs-Fund refresh data failed!", error])); }).catch(error => reject(error)) }).catch(error => reject(error)) diff --git a/src/services/bonds.js b/src/services/bonds.js index 4b43466..3c47ab8 100644 --- a/src/services/bonds.js +++ b/src/services/bonds.js @@ -186,16 +186,21 @@ blockchainBond.config = { function refreshBlockchainData(nodeList = []) { return new Promise((resolve, reject) => { - DB.query("SELECT num FROM LastTx WHERE floID=?", [blockchainBond.config.adminID]).then(result => { - let lastTx = result.length ? result[0].num : 0; - floBlockchainAPI.readData(blockchainBond.config.adminID, { - ignoreOld: lastTx, - senders: nodeList.concat(blockchainBond.config.adminID), //sentOnly: true, - tx: true, - filter: d => d.startsWith(blockchainBond.productStr) - }).then(result => { + DB.query("SELECT txid FROM LastTx WHERE floID=?", [blockchainBond.config.adminID]).then(result => { + + var query_options = { + senders: nodeList.concat(blockchainBond.config.adminID), + tx: true, filter: d => d.startsWith(blockchainBond.productStr) + }; + let lastTx = result.length ? result[0].txid : undefined; + if (typeof lastTx == 'string' && /^[0-9a-f]{64}/i.test(lastTx))//lastTx is txid of last tx + query_options.after = lastTx; + else if (!isNaN(lastTx))//lastTx is tx count (*backward support) + query_options.ignoreOld = parseInt(lastTx); + + floBlockchainAPI.readData(blockchainBond.config.adminID, query_options).then(result => { let txQueries = []; - result.data.reverse().forEach(d => { + result.items.reverse().forEach(d => { let bond = d.senders.has(blockchainBond.config.adminID) ? blockchainBond.parse.main(d.data) : null; if (bond && bond.amount) txQueries.push(["INSERT INTO BlockchainBonds(bond_id, floID, amount_in, begin_date, btc_base, usd_base, gain_cut, min_ipa, max_period, lockin_period) VALUE (?) ON DUPLICATE KEY UPDATE bond_id=bond_id", @@ -207,10 +212,10 @@ function refreshBlockchainData(nodeList = []) { [d.txid, details.amountFinal, details.bondID]]); } }); - txQueries.push(["INSERT INTO LastTx (floID, num) VALUE (?) ON DUPLICATE KEY UPDATE num=?", - [[blockchainBond.config.adminID, result.totalTxs], result.totalTxs]]) + txQueries.push(["INSERT INTO LastTx (floID, txid) VALUE (?) ON DUPLICATE KEY UPDATE txid=?", + [[blockchainBond.config.adminID, result.lastItem], result.lastItem]]) DB.transaction(txQueries) - .then(_ => resolve(result.totalTxs)) + .then(_ => resolve(result.lastItem)) .catch(error => reject(["Blockchain-bonds refresh data failed!", error])); }).catch(error => reject(error)) }).catch(error => reject(error))