rfs.cpp 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #ifdef _WIN32
  14. #define WIN32_LEAN_AND_MEAN
  15. #ifndef _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES
  16. #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
  17. #undef _CRT_SECURE_NO_WARNINGS
  18. #define _CRT_SECURE_NO_WARNINGS 1
  19. #endif
  20. #undef UNICODE
  21. #include <windows.h>
  22. #include <io.h>
  23. #include <winsock2.h>
  24. #include <ws2tcpip.h>
  25. #include <signal.h>
  26. #define getpid ::GetCurrentProcessId
  27. #else
  28. #include <unistd.h>
  29. #include <sys/types.h>
  30. #include <sys/socket.h>
  31. #include <sys/ioctl.h>
  32. #include <netinet/tcp.h>
  33. #include <netinet/in.h>
  34. #include <arpa/inet.h>
  35. #include <stddef.h>
  36. #include <errno.h>
  37. #include <stdarg.h>
  38. #define _strdup strdup
  39. #define closesocket close
  40. #include <sys/stat.h>
  41. #define _O_WRONLY O_WRONLY
  42. #define _open ::open
  43. #define _write ::write
  44. #define _close ::close
  45. #define _S_IREAD S_IRUSR | S_IRGRP | S_IROTH
  46. #define _S_IWRITE S_IWUSR | S_IWGRP | S_IWOTH
  47. #define _S_IEXEC S_IXUSR | S_IXGRP | S_IXOTH
  48. #define _O_CREAT O_CREAT
  49. #define _O_APPEND O_APPEND
  50. #define _vsnprintf vsnprintf
  51. #endif
  52. #include <stdlib.h>
  53. #include <ctype.h>
  54. #include <assert.h>
  55. #include <time.h>
  56. #include <malloc.h>
  57. #include <string.h>
  58. #include <fcntl.h>
  59. #include <sys/stat.h>
  60. #include "rfs.h"
  61. #ifdef _WIN32
  62. #define socklen_t int
  63. #define T_SOCKET SOCKET
  64. #define ETIMEDOUT WSAETIMEDOUT
  65. #define ECONNREFUSED WSAECONNREFUSED
  66. #define BADSOCKERR(err) ((err==WSAEBADF)||(err==WSAENOTSOCK))
  67. #define SEND_FLAGS 0
  68. #define ERRNO() WSAGetLastError()
  69. #define EADDRINUSE WSAEADDRINUSE
  70. #define EINTRCALL WSAEINTR
  71. #define ECONNRESET WSAECONNRESET
  72. #define ECONNABORTED WSAECONNABORTED
  73. #define ENOTCONN WSAENOTCONN
  74. #define EWOULDBLOCK WSAEWOULDBLOCK
  75. #define EINPROGRESS WSAEINPROGRESS
  76. #define ENOTSOCK WSAENOTSOCK
  77. static int strncasecmp (const char *s1, const char *s2, size_t len)
  78. {
  79. int ret = 0;
  80. if (len)
  81. while ((ret = tolower((unsigned char)*s1)-tolower((unsigned char)*s2)) == 0) {
  82. s2++;
  83. if (*s1++ == '\0' || --len == 0)
  84. break;
  85. }
  86. return ret;
  87. }
  88. #else
  89. #define T_SOCKET int
  90. #define SEND_FLAGS (MSG_NOSIGNAL)
  91. #define BADSOCKERR(err) ((err==EBADF)||(err==ENOTSOCK))
  92. #define INVALID_SOCKET -1
  93. #define ERRNO() (errno)
  94. #define EINTRCALL EINTR
  95. static int _memicmp (const void *s1, const void *s2, size_t len)
  96. {
  97. const unsigned char *b1 = (const unsigned char *)s1;
  98. const unsigned char *b2 = (const unsigned char *)s2;
  99. int ret = 0;
  100. while (len&&((ret = tolower(*b1)-tolower(*b2)) == 0)) {
  101. b1++;
  102. b2++;
  103. len--;
  104. }
  105. return ret;
  106. }
  107. #define _stricmp strcasecmp
  108. #endif
  109. #define MAX_BLOCK_SIZE (100*1048576) // 100MB though actually should never be anywhere near
  110. typedef byte RFS_RemoteFileCommandType;
  111. enum {
  112. RFCopenIO,
  113. RFCcloseIO,
  114. RFCread,
  115. RFCwrite,
  116. RFCsize,
  117. RFCexists,
  118. RFCremove,
  119. RFCrename,
  120. RFCgetver,
  121. RFCisfile,
  122. RFCisdirectory,
  123. RFCisreadonly,
  124. RFCsetreadonly,
  125. RFCgettime,
  126. RFCsettime,
  127. RFCcreatedir,
  128. RFCgetdir,
  129. RFCstop, // not supported
  130. RFCexec, // not supported
  131. RFCkill, // not supported
  132. RFCredeploy, // not supported
  133. RFCgetcrc,
  134. #ifdef TBD // The follwing may be implemented depending if required
  135. RFCmove,
  136. RFCsetsize,
  137. RFCextractblobelements,
  138. RFCcopy,
  139. RFCappend,
  140. RFCmonitordir,
  141. RFCsettrace,
  142. RFCgetinfo,
  143. RFCfirewall, // not supported
  144. RFCunlock,
  145. RFCunlockreply,
  146. RFCinvalid,
  147. RFCcopysection,
  148. RFCtreecopy,
  149. RFCtreecopytmp,
  150. RFCsetthrottle,
  151. RFCsetthrottle2,
  152. RFCsetfileperms,
  153. #endif
  154. RFCmax,
  155. RFCnone = 255
  156. };
  157. #define RFSERR_SysError 7999
  158. #define RFSERR_InvalidCommand 8000
  159. #define RFSERR_NullFileIOHandle 8001
  160. #define RFSERR_InvalidFileIOHandle 8002
  161. #define RFSERR_TimeoutFileIOHandle 8003
  162. #define RFSERR_OpenFailed 8004
  163. #define RFSERR_ReadFailed 8005
  164. #define RFSERR_WriteFailed 8006
  165. #define RFSERR_RenameFailed 8007
  166. #define RFSERR_ExistsFailed 8009
  167. #define RFSERR_RemoveFailed 8010
  168. #define RFSERR_CloseFailed 8011
  169. #define RFSERR_IsFileFailed 8012
  170. #define RFSERR_IsDirectoryFailed 8013
  171. #define RFSERR_IsReadOnlyFailed 8014
  172. #define RFSERR_SetReadOnlyFailed 8015
  173. #define RFSERR_GetTimeFailed 8016
  174. #define RFSERR_SetTimeFailed 8017
  175. #define RFSERR_CreateDirFailed 8018
  176. #define RFSERR_GetDirFailed 8019
  177. #define RFSERR_GetCrcFailed 8020
  178. #define RFSERR_MoveFailed 8021
  179. #define RFSERR_ExtractBlobElementsFailed 8022
  180. #define RFSERR_CopyFailed 8023
  181. #define RFSERR_AppendFailed 8024
  182. #define RFSERR_AuthenticateFailed 8025
  183. #define RFSERR_CopySectionFailed 8026
  184. #define RFSERR_TreeCopyFailed 8027
  185. #define RFSERR_SizeFailed 8051
  186. #define RFSERR_GetVerFailed 8052
  187. struct mapCmdToErr_t { RFS_RemoteFileCommandType cmd; int err; } mapCmdToErr[] =
  188. {
  189. { RFCopenIO, RFSERR_OpenFailed },
  190. { RFCcloseIO, RFSERR_CloseFailed },
  191. { RFCread, RFSERR_ReadFailed },
  192. { RFCwrite, RFSERR_WriteFailed },
  193. { RFCsize, RFSERR_SizeFailed },
  194. { RFCexists, RFSERR_ExistsFailed },
  195. { RFCremove, RFSERR_RemoveFailed },
  196. { RFCrename, RFSERR_RenameFailed },
  197. { RFCgetver, RFSERR_GetVerFailed },
  198. { RFCisfile, RFSERR_IsFileFailed },
  199. { RFCisdirectory, RFSERR_IsDirectoryFailed },
  200. { RFCisreadonly, RFSERR_IsReadOnlyFailed },
  201. { RFCsetreadonly, RFSERR_SetReadOnlyFailed },
  202. { RFCgettime, RFSERR_GetTimeFailed },
  203. { RFCsettime, RFSERR_SetTimeFailed },
  204. { RFCcreatedir, RFSERR_CreateDirFailed },
  205. { RFCgetdir, RFSERR_GetDirFailed },
  206. { RFCgetcrc, RFSERR_GetCrcFailed },
  207. { RFCmax, RFSERR_InvalidCommand }
  208. };
  209. struct mapErrs_t { int val; const char *str; } mapErrs[] =
  210. {
  211. { RFSERR_InvalidCommand ,"RFSERR_InvalidCommand"},
  212. { RFSERR_NullFileIOHandle ,"RFSERR_NullFileIOHandle"},
  213. { RFSERR_InvalidFileIOHandle ,"RFSERR_InvalidFileIOHandle"},
  214. { RFSERR_TimeoutFileIOHandle ,"RFSERR_TimeoutFileIOHandle"},
  215. { RFSERR_OpenFailed ,"RFSERR_OpenFailed"},
  216. { RFSERR_ReadFailed ,"RFSERR_ReadFailed"},
  217. { RFSERR_WriteFailed ,"RFSERR_WriteFailed"},
  218. { RFSERR_RenameFailed ,"RFSERR_RenameFailed"},
  219. { RFSERR_ExistsFailed ,"RFSERR_ExistsFailed"},
  220. { RFSERR_RemoveFailed ,"RFSERR_RemoveFailed"},
  221. { RFSERR_CloseFailed ,"RFSERR_CloseFailed"},
  222. { RFSERR_IsFileFailed ,"RFSERR_IsFileFailed"},
  223. { RFSERR_IsDirectoryFailed ,"RFSERR_IsDirectoryFailed"},
  224. { RFSERR_IsReadOnlyFailed ,"RFSERR_IsReadOnlyFailed"},
  225. { RFSERR_SetReadOnlyFailed ,"RFSERR_SetReadOnlyFailed"},
  226. { RFSERR_GetTimeFailed ,"RFSERR_GetTimeFailed"},
  227. { RFSERR_SetTimeFailed ,"RFSERR_SetTimeFailed"},
  228. { RFSERR_CreateDirFailed ,"RFSERR_CreateDirFailed"},
  229. { RFSERR_GetDirFailed ,"RFSERR_GetDirFailed"},
  230. { RFSERR_GetCrcFailed ,"RFSERR_GetCrcFailed"},
  231. { RFSERR_MoveFailed ,"RFSERR_MoveFailed"},
  232. { RFSERR_ExtractBlobElementsFailed ,"RFSERR_ExtractBlobElementsFailed"},
  233. { RFSERR_CopyFailed ,"RFSERR_CopyFailed"},
  234. { RFSERR_AppendFailed ,"RFSERR_AppendFailed"},
  235. { RFSERR_AuthenticateFailed ,"RFSERR_AuthenticateFailed"},
  236. { RFSERR_CopySectionFailed ,"RFSERR_CopySectionFailed"},
  237. { RFSERR_TreeCopyFailed ,"RFSERR_TreeCopyFailed"},
  238. { RFSERR_SizeFailed ,"RFSERR_SizeFailed"},
  239. { RFSERR_GetVerFailed ,"RFSERR_GetVerFailed"},
  240. { 0, NULL }
  241. };
  242. #define RFEnoerror 0U
  243. enum fileBool { foundNo = false, foundYes = true, notFound = 2 };
  244. #ifdef _WIN32
  245. class win_socket_library
  246. {
  247. public:
  248. win_socket_library() { init(); }
  249. bool init()
  250. {
  251. WSADATA wsa;
  252. if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
  253. if (WSAStartup(MAKEWORD(1, 1), &wsa) != 0) {
  254. MessageBoxA(NULL,"Failed to initialize windows sockets","JLib Socket Error",MB_OK);
  255. exit(0);
  256. }
  257. }
  258. return true;
  259. }
  260. ~win_socket_library()
  261. {
  262. WSACleanup();
  263. }
  264. };
  265. #endif
  266. #ifndef _WIN32
  267. static char *_itoa(unsigned long n, char *str, int b, bool sign)
  268. {
  269. char *s = str;
  270. if (sign)
  271. n = -n;
  272. do
  273. {
  274. byte d = n % b;
  275. *(s++) = d+((d<10)?'0':('a'-10));
  276. }
  277. while ((n /= b) > 0);
  278. if (sign)
  279. *(s++) = '-';
  280. *s = '\0';
  281. // reverse
  282. char *s2 = str;
  283. s--;
  284. while (s2<s)
  285. {
  286. char tc = *s2;
  287. *(s2++) = *s;
  288. *(s--) = tc;
  289. }
  290. return str;
  291. }
  292. char *_itoa(int n, char *str, int b)
  293. {
  294. return _itoa(n, str, b, (n<0));
  295. }
  296. char *_ltoa(long n, char *str, int b)
  297. {
  298. return _itoa(n, str, b, (n<0));
  299. }
  300. char *_ultoa(unsigned long n, char *str, int b)
  301. {
  302. return _itoa(n, str, b, false);
  303. }
  304. #endif
  305. void getLogTime(char *res)
  306. {
  307. #ifdef _WIN32
  308. SYSTEMTIME st;
  309. GetLocalTime(&st);
  310. sprintf(res,"%02u/%02u/%04u %02u:%02u:%02u:%03u ", st.wDay,st.wMonth,st.wYear,st.wHour,st.wMinute,st.wSecond,st.wMilliseconds);
  311. #else
  312. time_t st;
  313. time(&st);
  314. struct tm *_tm = localtime(&st);
  315. sprintf(res,"%02u/%02u/%04u %02u:%02u:%02u ", _tm->tm_mday,_tm->tm_mon+1,_tm->tm_year+1900,_tm->tm_hour,_tm->tm_min,_tm->tm_sec);
  316. #endif
  317. }
  318. inline void _cpyrevn(void * _tgt, const void * _src, unsigned len) {
  319. char * tgt = (char *)_tgt; const char * src = (const char *)_src+len;
  320. for (;len;len--) {
  321. *tgt++ = *--src;
  322. }
  323. }
  324. inline void _rev4(char *b) { char t=b[0]; b[0]=b[3]; b[3]=t; t=b[1]; b[1]=b[2]; b[2]=t; }
  325. inline void BECONV(unsigned &v)
  326. {
  327. #if __BYTE_ORDER == __LITTLE_ENDIAN
  328. _rev4((char *)&v);
  329. #else
  330. #endif
  331. }
  332. struct RFS_context
  333. {
  334. unsigned short port;
  335. T_SOCKET listensock;
  336. bool running;
  337. int argc;
  338. const char **argv;
  339. char *logname;
  340. int debug;
  341. RFS_RemoteFileCommandType cmd;
  342. #ifdef _WIN32
  343. win_socket_library *ws32_lib;
  344. static class RFS_WindowsService *RFS_Service;
  345. #else
  346. bool daemon;
  347. #endif
  348. };
  349. void logError(RFS_ServerBase *base, const char *str,int err,unsigned extra=0) // used for comms failures
  350. {
  351. const char *errs;
  352. char es[1024];
  353. #ifdef _WIN32
  354. if (err>1000) {
  355. LPVOID lpMsgBuf=NULL;
  356. FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL,
  357. err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) &lpMsgBuf,0,NULL);
  358. if (lpMsgBuf) {
  359. //wsprintf(buf, "%d: %s", dw, lpMsgBuf);
  360. strncpy(es,(char *)lpMsgBuf,sizeof(es)-1);
  361. LocalFree( lpMsgBuf );
  362. errs = es;
  363. }
  364. else
  365. errs = strerror(err);
  366. }
  367. else
  368. #endif
  369. errs = err?strerror(err):"";
  370. if (!base||!base->logFilename()) {
  371. if (!err&&!extra)
  372. fprintf(stderr,"ERROR: %s\n",str,err,extra,errs);
  373. else if (extra)
  374. fprintf(stderr,"ERROR: %s (%d,%d) %s\n",str,err,extra,errs);
  375. else
  376. fprintf(stderr,"ERROR: %s (%d) %s\n",str,err,errs);
  377. fflush(stderr);
  378. }
  379. else {
  380. if (!err&&!extra)
  381. base->log("ERROR: %s",str,err,extra,errs);
  382. else if (extra)
  383. base->log("ERROR: %s (%d,%d) %s",str,err,extra,errs);
  384. else
  385. base->log("ERROR: %s (%d) %s",str,err,errs);
  386. }
  387. }
  388. static inline byte decode_32c(char c)
  389. {
  390. byte b = (byte)c;
  391. if (b>=97) {
  392. if (b<=122)
  393. return b-97;
  394. }
  395. else if ((b>=50)&&(b<=55))
  396. return b-24;
  397. return 0;
  398. }
  399. class RFS_MemoryBuffer // NB big endian only!
  400. {
  401. byte * buffer;
  402. size_t curLen;
  403. size_t readPos;
  404. size_t maxLen;
  405. public:
  406. inline RFS_MemoryBuffer()
  407. {
  408. curLen = 0;
  409. readPos = 0;
  410. maxLen = 0;
  411. buffer = NULL;
  412. }
  413. inline ~RFS_MemoryBuffer()
  414. {
  415. free(buffer);
  416. }
  417. void swapWith(RFS_MemoryBuffer &other)
  418. {
  419. byte *tb = buffer;
  420. buffer = other.buffer;
  421. other.buffer = tb;
  422. size_t t = curLen;
  423. curLen = other.curLen;
  424. other.curLen = t;
  425. t = readPos;
  426. readPos = other.readPos;
  427. other.readPos = t;
  428. t = maxLen;
  429. curLen = other.maxLen;
  430. other.maxLen = t;
  431. }
  432. inline size_t length() { return curLen; }
  433. inline size_t curPos() { return readPos; }
  434. inline size_t maxLength() { return maxLen; }
  435. inline void setLength(size_t len)
  436. {
  437. assert (len<=maxLen);
  438. curLen = len;
  439. }
  440. inline void *reserve(size_t sz)
  441. {
  442. if (!buffer) {
  443. maxLen = sz+1024;
  444. buffer = (byte *)malloc(maxLen);
  445. }
  446. else if (sz>maxLen-curLen) {
  447. do {
  448. maxLen += maxLen;
  449. } while (sz>maxLen-curLen);
  450. buffer = (byte *)realloc(buffer,maxLen);
  451. }
  452. byte *ret = buffer+curLen;
  453. curLen+=sz;
  454. return ret;
  455. }
  456. inline RFS_MemoryBuffer & appendBigEndian(size_t len, const void * value)
  457. {
  458. #if __BYTE_ORDER == __LITTLE_ENDIAN
  459. _cpyrevn(reserve(len), value, len);
  460. #else
  461. memcpy(reserve(len), value, len);
  462. #endif
  463. return *this;
  464. }
  465. inline RFS_MemoryBuffer & append(rfs_fpos_t value)
  466. {
  467. return appendBigEndian(sizeof(value),&value);
  468. }
  469. RFS_MemoryBuffer & append(unsigned value)
  470. {
  471. return appendBigEndian(sizeof(value),&value);
  472. }
  473. inline RFS_MemoryBuffer & append(int value)
  474. {
  475. return appendBigEndian(sizeof(value),&value);
  476. }
  477. inline RFS_MemoryBuffer & append(short value)
  478. {
  479. return appendBigEndian(sizeof(value),&value);
  480. }
  481. inline RFS_MemoryBuffer & append(byte value)
  482. {
  483. memcpy(reserve(sizeof(value)),&value,sizeof(value));
  484. return *this;
  485. }
  486. inline RFS_MemoryBuffer & append(char value)
  487. {
  488. memcpy(reserve(sizeof(value)),&value,sizeof(value));
  489. return *this;
  490. }
  491. inline RFS_MemoryBuffer & append(bool value)
  492. {
  493. memcpy(reserve(sizeof(value)),&value,1);
  494. return *this;
  495. }
  496. RFS_MemoryBuffer & append(size_t sz,const char *s)
  497. {
  498. memcpy(reserve(sz),s,sz);
  499. return *this;
  500. }
  501. RFS_MemoryBuffer & append(const char *s)
  502. {
  503. if (!s)
  504. return append((byte)0);
  505. return append(strlen(s)+1,s);
  506. }
  507. RFS_MemoryBuffer & readEndian(size_t len, void * value)
  508. {
  509. #if __BYTE_ORDER == __LITTLE_ENDIAN
  510. _cpyrevn(value, buffer + readPos, len);
  511. #else
  512. memcpy(value, buffer + readPos, len);
  513. #endif
  514. readPos += len;
  515. return *this;
  516. }
  517. void read(byte &b)
  518. {
  519. memcpy(&b,buffer+readPos++,1);
  520. }
  521. void read(rfs_fpos_t &i)
  522. {
  523. readEndian(sizeof(i),&i);
  524. }
  525. void read(unsigned &i)
  526. {
  527. readEndian(sizeof(i),&i);
  528. }
  529. void read(int &i)
  530. {
  531. readEndian(sizeof(i),&i);
  532. }
  533. void read(short &i)
  534. {
  535. readEndian(sizeof(i),&i);
  536. }
  537. void read(bool &_b)
  538. {
  539. byte b;
  540. memcpy(&b,buffer+readPos,sizeof(b));
  541. readPos+=sizeof(b);
  542. _b = b!=0;
  543. }
  544. size_t readsize() // NB size sent as 32bit unsigned
  545. {
  546. unsigned ret;
  547. read(ret);
  548. return (size_t)ret;
  549. }
  550. char *readStr()
  551. {
  552. size_t l = strlen((char *)buffer+readPos)+1;
  553. char *ret = (char *)malloc(l);
  554. memcpy(ret,buffer+readPos,l);
  555. readPos+=l;
  556. return ret;
  557. }
  558. const byte *readBlock(size_t sz)
  559. {
  560. assert (sz<=maxLen-readPos);
  561. byte *ret = buffer+readPos;
  562. readPos+=sz;
  563. return ret;
  564. }
  565. inline RFS_MemoryBuffer & reset(size_t pos=0)
  566. {
  567. readPos = pos;
  568. return *this;
  569. }
  570. inline RFS_MemoryBuffer & clear(size_t max=0)
  571. {
  572. curLen = 0;
  573. readPos = 0;
  574. free(buffer);
  575. buffer = NULL;
  576. if (max)
  577. buffer = (byte *)malloc(max);
  578. maxLen = max;
  579. return *this;
  580. }
  581. inline byte *toByteArray()
  582. {
  583. return buffer;
  584. }
  585. byte *detach()
  586. {
  587. byte *ret = buffer;
  588. curLen = 0;
  589. readPos = 0;
  590. maxLen = 0;
  591. buffer = NULL;
  592. return ret;
  593. }
  594. void base32_Decode(const char *bi,RFS_MemoryBuffer &out)
  595. {
  596. while (1) {
  597. byte b[8];
  598. for (unsigned i=0;i<8;i++)
  599. b[i] = decode_32c(*(bi++));
  600. byte o;
  601. o = ((b[0] & 0x1f) << 3) | ((b[1] & 0x1c) >> 2);
  602. if (!o) return;
  603. out.append(o);
  604. o = ((b[1] & 0x03) << 6) | ((b[2] & 0x1f) << 1) | ((b[3] & 0x10) >> 4);
  605. if (!o) return;
  606. out.append(o);
  607. o = ((b[3] & 0x0f) << 4) | ((b[4] & 0x1e) >> 1);
  608. if (!o) return;
  609. out.append(o);
  610. o = ((b[4] & 0x01) << 7) | ((b[5] & 0x1f) << 2) | ((b[6] & 0x18) >> 3);
  611. if (!o) return;
  612. out.append(o);
  613. o = ((b[6] & 0x07) << 5) | (b[7] & 0x1f);
  614. if (!o) return;
  615. out.append(o);
  616. }
  617. }
  618. void appendUtf8(unsigned c)
  619. {
  620. if (c < 0x80)
  621. append((char)c);
  622. else if (c < 0x800)
  623. {
  624. append((char)(0xC0 | c>>6));
  625. append((char)(0x80 | c & 0x3F));
  626. }
  627. else if (c < 0x10000)
  628. {
  629. append((char) (0xE0 | c>>12));
  630. append((char) (0x80 | c>>6 & 0x3F));
  631. append((char) (0x80 | c & 0x3F));
  632. }
  633. else if (c < 0x200000)
  634. {
  635. append((char) (0xF0 | c>>18));
  636. append((char) (0x80 | c>>12 & 0x3F));
  637. append((char) (0x80 | c>>6 & 0x3F));
  638. append((char) (0x80 | c & 0x3F));
  639. }
  640. else if (c < 0x4000000)
  641. {
  642. append((char) (0xF8 | c>>24));
  643. append((char) (0x80 | c>>18 & 0x3F));
  644. append((char) (0x80 | c>>12 & 0x3F));
  645. append((char) (0x80 | c>>6 & 0x3F));
  646. append((char) (0x80 | c & 0x3F));
  647. }
  648. else if (c < 0x80000000)
  649. {
  650. append((char) (0xFC | c>>30));
  651. append((char) (0x80 | c>>24 & 0x3F));
  652. append((char) (0x80 | c>>18 & 0x3F));
  653. append((char) (0x80 | c>>12 & 0x3F));
  654. append((char) (0x80 | c>>6 & 0x3F));
  655. append((char) (0x80 | c & 0x3F));
  656. }
  657. }
  658. void appendXML(const char *x, size_t len)
  659. {
  660. if (!x)
  661. return;
  662. if ((unsigned)-1 == len)
  663. len = strlen(x);
  664. const char *end = x+len;
  665. while (x<end && *x) {
  666. if ('&' == *x) {
  667. switch (*(x+1)) {
  668. case 'a':
  669. case 'A': {
  670. switch (*(x+2)) {
  671. case 'm':
  672. case 'M': {
  673. char c1 = *(x+3);
  674. if (('p' == c1 || 'P' == c1) && ';' == *(x+4)) {
  675. x += 5;
  676. append('&');
  677. continue;
  678. }
  679. break;
  680. }
  681. case 'p':
  682. case 'P': {
  683. char c1 = *(x+3);
  684. char c2 = *(x+4);
  685. if (('o' == c1 || 'O' == c1) && ('s' == c2 || 'S' == c2) && ';' == *(x+5)) {
  686. x += 6;
  687. append('\'');
  688. continue;
  689. }
  690. break;
  691. }
  692. }
  693. break;
  694. }
  695. case 'l':
  696. case 'L': {
  697. char c1 = *(x+2);
  698. if (('t' == c1 || 'T' == c1) && ';' == *(x+3)) {
  699. x += 4;
  700. append('<');
  701. continue;
  702. }
  703. break;
  704. }
  705. case 'g':
  706. case 'G': {
  707. char c1 = *(x+2);
  708. if (('t' == c1 || 'T' == c1) && ';' == *(x+3)) {
  709. x += 4;
  710. append('>');
  711. continue;
  712. }
  713. break;
  714. }
  715. case 'q':
  716. case 'Q': {
  717. char c1 = *(x+2);
  718. char c2 = *(x+3);
  719. char c3 = *(x+4);
  720. if (('u' == c1 || 'U' == c1) && ('o' == c2 || 'O' == c2) && ('t' == c3 || 'T' == c3) && ';' == *(x+5)) {
  721. x += 6;
  722. append('"');
  723. continue;
  724. }
  725. break;
  726. }
  727. case 'n':
  728. case 'N': {
  729. char c1 = *(x+2);
  730. char c2 = *(x+3);
  731. char c3 = *(x+4);
  732. if (('b' == c1 || 'B' == c1) && ('s' == c2 || 'S' == c2) && ('p' == c3 || 'P' == c3) && ';' == *(x+5)) {
  733. x += 6;
  734. appendUtf8(0xa0);
  735. continue;
  736. }
  737. break;
  738. }
  739. default: {
  740. x++;
  741. if (*x == '#') {
  742. x++;
  743. bool hex;
  744. if (*x == 'x' || *x == 'X') { // strictly not sure about X.
  745. hex = true;
  746. x++;
  747. }
  748. else
  749. hex = false;
  750. char *endptr;
  751. unsigned long val = 0;
  752. if (hex)
  753. val = strtoul(x,&endptr,16);
  754. else
  755. val = strtoul(x,&endptr,10);
  756. if (x!=endptr && *endptr == ';')
  757. appendUtf8((unsigned)val);
  758. x = endptr+1;
  759. continue;
  760. }
  761. else {
  762. if ('\0' == *x)
  763. --x;
  764. else {
  765. bool error = false;
  766. append('&');
  767. }
  768. }
  769. break;
  770. }
  771. }
  772. }
  773. append(*(x++));
  774. }
  775. }
  776. const char * readFileName(RFS_MemoryBuffer &out)
  777. {
  778. size_t t = out.length();
  779. char *s = (char *)buffer+readPos;
  780. size_t l = strlen(s);
  781. if ((l>=3)&&((memcmp(s,"/$/",3)==0)||(memcmp(s,"\\$\\",3)==0)))
  782. base32_Decode(s+3,out);
  783. else
  784. out.append(l,s);
  785. out.append((byte)0);
  786. readPos+=l+1;
  787. return (char *)out.toByteArray()+t;
  788. }
  789. };
  790. struct RFS_DateTime
  791. {
  792. RFS_DateTime()
  793. {
  794. year = 0;
  795. month = 0;
  796. day = 0;
  797. hour = 0;
  798. min = 0;
  799. sec = 0;
  800. nanosec = 0;
  801. }
  802. void deserialize(RFS_MemoryBuffer &src)
  803. {
  804. src.read(year);
  805. src.read(month);
  806. src.read(day);
  807. src.read(hour);
  808. src.read(min);
  809. src.read(sec);
  810. src.read(nanosec);
  811. }
  812. void serialize(RFS_MemoryBuffer &dst) const
  813. {
  814. dst.append(year).append(month).append(day).append(hour).append(min).append(sec).append(nanosec);
  815. }
  816. void setDate(unsigned _year, unsigned _month, unsigned _day)
  817. {
  818. year = _year;
  819. month = _month;
  820. day = _day;
  821. }
  822. void setTime(unsigned _hour, unsigned _min, unsigned _sec, unsigned _nanosec)
  823. {
  824. hour = _hour;
  825. min = _min;
  826. sec = _sec;
  827. nanosec = _nanosec;
  828. }
  829. void getDate(int & _year, int & _month, int & _day) const
  830. {
  831. _year = year;
  832. _month = month;
  833. _day = day;
  834. }
  835. void getTime(int & _hour, int & _min, int & _sec, int & _nanosec) const
  836. {
  837. _hour = hour;
  838. _min = min;
  839. _sec = sec;
  840. _nanosec = nanosec;
  841. }
  842. void set(time_t time)
  843. {
  844. struct tm tm_r;
  845. struct tm * gmt;
  846. #ifdef _WIN32
  847. #if _MSC_VER < 1400 // VC6
  848. tm_r = *localtime(&time);
  849. #else
  850. localtime_s(&tm_r,&time);
  851. #endif
  852. gmt = &tm_r;
  853. #else
  854. gmt = localtime_r(&time,&tm_r);
  855. #endif
  856. setDate(gmt->tm_year + 1900, gmt->tm_mon + 1, gmt->tm_mday);
  857. setTime(gmt->tm_hour, gmt->tm_min, gmt->tm_sec, 0);
  858. }
  859. time_t get()
  860. {
  861. int unused;
  862. struct tm ttm;
  863. getDate(ttm.tm_year, ttm.tm_mon, ttm.tm_mday);
  864. getTime(ttm.tm_hour, ttm.tm_min, ttm.tm_sec, unused);
  865. ttm.tm_isdst = -1;
  866. if(ttm.tm_year >= 1900)
  867. ttm.tm_year -= 1900;
  868. ttm.tm_mon -= 1;
  869. time_t time = mktime(&ttm);
  870. if (time == (time_t)-1)
  871. time = 0;
  872. return time;
  873. }
  874. protected:
  875. short year;
  876. byte month;
  877. byte day;
  878. byte hour;
  879. byte min;
  880. byte sec;
  881. unsigned nanosec;
  882. };
  883. class RFS_Exception
  884. {
  885. public:
  886. char *str;
  887. int rfserr;
  888. int err;
  889. bool fatal;
  890. RFS_Exception() { str = NULL; rfserr = 0; err = 0; fatal = false; }
  891. RFS_Exception(int _rfserr, int _err,const char *msg,bool _fatal)
  892. {
  893. rfserr = _rfserr;
  894. err = _err;
  895. fatal = _fatal;
  896. char es[1024];
  897. const char *ename = NULL;
  898. if (rfserr==RFSERR_SysError) {
  899. #ifdef _WIN32
  900. if (err>1000) {
  901. LPVOID lpMsgBuf=NULL;
  902. FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL,
  903. err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) &lpMsgBuf,0,NULL);
  904. if (lpMsgBuf) {
  905. //wsprintf(buf, "%d: %s", dw, lpMsgBuf);
  906. strncpy(es,(char *)lpMsgBuf,sizeof(es)-1);
  907. LocalFree( lpMsgBuf );
  908. ename = es;
  909. }
  910. else
  911. ename = strerror(err);
  912. }
  913. else
  914. #endif
  915. ename = strerror(err);
  916. }
  917. else {
  918. for (unsigned i=0;;i++) {
  919. ename = mapErrs[i].str;
  920. if (!ename||(mapErrs[i].val==rfserr))
  921. break;
  922. }
  923. if (!ename) {
  924. _itoa(rfserr,es,10);
  925. ename = es;
  926. }
  927. }
  928. size_t msgsz = msg?strlen(msg):0;
  929. msgsz += strlen(ename)+32;
  930. str = (char *)malloc(msgsz);
  931. sprintf(str,"ERROR: %s(%d) '%s'",ename,err,msg?msg:"");
  932. }
  933. ~RFS_Exception() { free(str); }
  934. };
  935. static unsigned long crc_32_tab[] = { /* CRC polynomial 0xedb88320 */
  936. 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, 0x706af48fL,
  937. 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L,
  938. 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L,
  939. 0xf3b97148L, 0x84be41deL, 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L,
  940. 0x136c9856L, 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
  941. 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, 0xa2677172L,
  942. 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, 0x35b5a8faL, 0x42b2986cL,
  943. 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L,
  944. 0x26d930acL, 0x51de003aL, 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L,
  945. 0xcfba9599L, 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
  946. 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, 0x01db7106L,
  947. 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, 0x9fbfe4a5L, 0xe8b8d433L,
  948. 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL,
  949. 0x91646c97L, 0xe6635c01L, 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL,
  950. 0x6c0695edL, 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
  951. 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, 0xfbd44c65L,
  952. 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, 0x4adfa541L, 0x3dd895d7L,
  953. 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, 0x346ed9fcL, 0xad678846L, 0xda60b8d0L,
  954. 0x44042d73L, 0x33031de5L, 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL,
  955. 0xbe0b1010L, 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
  956. 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, 0x2eb40d81L,
  957. 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, 0x03b6e20cL, 0x74b1d29aL,
  958. 0xead54739L, 0x9dd277afL, 0x04db2615L, 0x73dc1683L, 0xe3630b12L, 0x94643b84L,
  959. 0x0d6d6a3eL, 0x7a6a5aa8L, 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L,
  960. 0xf00f9344L, 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
  961. 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, 0x67dd4accL,
  962. 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, 0xd6d6a3e8L, 0xa1d1937eL,
  963. 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL,
  964. 0xd80d2bdaL, 0xaf0a1b4cL, 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L,
  965. 0x316e8eefL, 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
  966. 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, 0xb2bd0b28L,
  967. 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, 0x2cd99e8bL, 0x5bdeae1dL,
  968. 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL,
  969. 0x72076785L, 0x05005713L, 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L,
  970. 0x92d28e9bL, 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
  971. 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, 0x18b74777L,
  972. 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, 0x8f659effL, 0xf862ae69L,
  973. 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L,
  974. 0xa7672661L, 0xd06016f7L, 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL,
  975. 0x40df0b66L, 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
  976. 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, 0xcdd70693L,
  977. 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, 0x5d681b02L, 0x2a6f2b94L,
  978. 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, 0x2d02ef8dL
  979. };
  980. #define UPDC32(octet, crc) (crc_32_tab[((crc) ^ (octet)) & 0xff] ^ ((crc) >> 8))
  981. unsigned long crc32(const char *buf, unsigned len, unsigned long crc)
  982. {
  983. byte c;
  984. while(len >= 12)
  985. {
  986. c = *buf++; crc = UPDC32(c,crc);
  987. c = *buf++; crc = UPDC32(c,crc);
  988. c = *buf++; crc = UPDC32(c,crc);
  989. c = *buf++; crc = UPDC32(c,crc);
  990. len -= 4;
  991. }
  992. switch (len)
  993. {
  994. case 11: c = *buf++; crc = UPDC32(c,crc);
  995. case 10: c = *buf++; crc = UPDC32(c,crc);
  996. case 9: c = *buf++; crc = UPDC32(c,crc);
  997. case 8: c = *buf++; crc = UPDC32(c,crc);
  998. case 7: c = *buf++; crc = UPDC32(c,crc);
  999. case 6: c = *buf++; crc = UPDC32(c,crc);
  1000. case 5: c = *buf++; crc = UPDC32(c,crc);
  1001. case 4: c = *buf++; crc = UPDC32(c,crc);
  1002. case 3: c = *buf++; crc = UPDC32(c,crc);
  1003. case 2: c = *buf++; crc = UPDC32(c,crc);
  1004. case 1: c = *buf++; crc = UPDC32(c,crc);
  1005. }
  1006. return(crc);
  1007. }
  1008. static size_t do_recv(int sock, void *buf, size_t len, int &err)
  1009. {
  1010. do {
  1011. int sz = (int)recv(sock,(char *)buf,len,0);
  1012. if (sz>=0) {
  1013. err = 0;
  1014. return (size_t)sz;
  1015. }
  1016. err = ERRNO();
  1017. } while (err==EINTRCALL);
  1018. return (size_t)-1;
  1019. }
  1020. bool sendBuffer(RFS_ServerBase *base,T_SOCKET socket, RFS_MemoryBuffer & src)
  1021. {
  1022. unsigned length = src.length() - sizeof(unsigned);
  1023. byte * buffer = src.toByteArray();
  1024. memcpy(buffer, &length, sizeof(unsigned));
  1025. BECONV(*(unsigned *)buffer);
  1026. size_t remaining = src.length();
  1027. while(1) {
  1028. int ret = send(socket, (const char *)buffer, remaining,0);
  1029. #ifdef _TRACE_RW
  1030. LogF("SEND(%d)",remaining);
  1031. #endif
  1032. if (ret<0) {
  1033. int err = ERRNO();
  1034. if (err!=EINTRCALL) {
  1035. logError(base,"sendBuffer",err); // cant return to caller!
  1036. return false;
  1037. }
  1038. ret = 0;
  1039. }
  1040. remaining -= ret;
  1041. if (remaining==0)
  1042. break;
  1043. buffer += ret;
  1044. }
  1045. return true;
  1046. }
  1047. class RFS_ConnectionList
  1048. {
  1049. unsigned maxconn;
  1050. RFS_ConnectionBase **conn;
  1051. static int nextsalt;
  1052. int salt;
  1053. public:
  1054. RFS_ConnectionList()
  1055. {
  1056. salt = nextsalt;
  1057. nextsalt += 1000;
  1058. maxconn = 16;
  1059. conn = (RFS_ConnectionBase **)calloc(sizeof(RFS_ConnectionBase *),maxconn);
  1060. }
  1061. ~RFS_ConnectionList()
  1062. {
  1063. while (maxconn--)
  1064. delete conn[maxconn];
  1065. free(conn);
  1066. }
  1067. RFS_ConnectionBase *find(int handle)
  1068. {
  1069. handle-=salt;
  1070. if ((unsigned)handle>=maxconn)
  1071. return NULL;
  1072. return conn[handle];
  1073. }
  1074. int add(RFS_ConnectionBase *c)
  1075. {
  1076. unsigned i;
  1077. for (i=0;;i++) {
  1078. if (i==maxconn) {
  1079. maxconn+=16;
  1080. conn = (RFS_ConnectionBase **)realloc(conn,sizeof(RFS_ConnectionBase *)*maxconn);
  1081. memset(conn+i,0,16*sizeof(RFS_ConnectionBase *));
  1082. break;
  1083. }
  1084. if (!conn[i])
  1085. break;
  1086. }
  1087. conn[i] = c;
  1088. return i+salt;
  1089. }
  1090. bool remove(RFS_ConnectionBase *c)
  1091. {
  1092. unsigned i;
  1093. for (i=0;i<maxconn;i++)
  1094. if (conn[i]==c) {
  1095. conn[i] = NULL;
  1096. return true;
  1097. }
  1098. return false;
  1099. }
  1100. void swapWith(RFS_ConnectionList &other)
  1101. {
  1102. unsigned tmpmaxconn = maxconn;
  1103. maxconn = other.maxconn;
  1104. other.maxconn = tmpmaxconn;
  1105. RFS_ConnectionBase **tmpconn = conn;
  1106. conn = other.conn;
  1107. other.conn = tmpconn;
  1108. int tmpsalt = salt;
  1109. salt = other.salt;
  1110. other.salt = tmpsalt;
  1111. }
  1112. };
  1113. int RFS_ConnectionList::nextsalt = 1000;
  1114. static bool processCommand(RFS_ServerBase &base, RFS_context &context, RFS_ConnectionList &connlist, T_SOCKET sock,RFS_MemoryBuffer &in)
  1115. {
  1116. RFS_MemoryBuffer out;
  1117. out.append((unsigned)0); // for length
  1118. RFS_MemoryBuffer tmp;
  1119. RFS_MemoryBuffer tmp2;
  1120. RFS_RemoteFileCommandType cmd;
  1121. try {
  1122. in.read(cmd);
  1123. context.cmd = cmd;
  1124. switch (cmd) {
  1125. case RFCopenIO: {
  1126. const char * name = in.readFileName(tmp);
  1127. byte mode;
  1128. in.read(mode);
  1129. byte share;
  1130. in.read(share);
  1131. int handleout = -1;
  1132. RFS_ConnectionBase *conn = base.open(name,mode,share);
  1133. if (conn)
  1134. handleout = connlist.add(conn);
  1135. out.append((unsigned)RFEnoerror).append(handleout);
  1136. }
  1137. break;
  1138. case RFCcloseIO: {
  1139. int handle;
  1140. in.read(handle);
  1141. RFS_ConnectionBase *conn = connlist.find(handle);
  1142. if (conn) {
  1143. connlist.remove(conn);
  1144. conn->close();
  1145. delete conn; // should delete even if close raises error?
  1146. }
  1147. else if (handle!=-1)
  1148. logError(&base,"Unexpected handle (close)",0,(unsigned)handle);
  1149. out.append((unsigned)RFEnoerror);
  1150. }
  1151. break;
  1152. case RFCread: {
  1153. int handle;
  1154. in.read(handle);
  1155. rfs_fpos_t pos;
  1156. in.read(pos);
  1157. size_t len = in.readsize();
  1158. // mabe loop here if big?
  1159. size_t posOfErr = out.length();
  1160. out.append((unsigned)RFEnoerror);
  1161. size_t newlen = out.length()+sizeof(unsigned);
  1162. unsigned *outlen = (unsigned *)out.reserve(len+sizeof(unsigned));
  1163. *outlen = 0;
  1164. RFS_ConnectionBase *conn = connlist.find(handle);
  1165. if (conn) {
  1166. size_t outl = 0;
  1167. conn->read(pos,len,outl,outlen+1);
  1168. *outlen = (unsigned)outl;
  1169. }
  1170. else if (handle!=-1)
  1171. logError(&base,"Unexpected handle (read)",0,(unsigned)handle);
  1172. newlen += *outlen;
  1173. BECONV(*outlen);
  1174. out.setLength(newlen);
  1175. }
  1176. break;
  1177. case RFCwrite: {
  1178. int handle;
  1179. in.read(handle);
  1180. rfs_fpos_t pos;
  1181. in.read(pos);
  1182. size_t len = in.readsize();
  1183. RFS_ConnectionBase *conn = connlist.find(handle);
  1184. if (conn)
  1185. conn->write(pos,len,in.readBlock(len)); // maybe loop here if big?
  1186. else if (handle!=-1) {
  1187. logError(&base,"Unexpected handle (write)",0,(unsigned)handle);
  1188. len = 0;
  1189. }
  1190. out.append((unsigned)RFEnoerror).append((unsigned)len);
  1191. }
  1192. break;
  1193. case RFCsize: {
  1194. int handle;
  1195. in.read(handle);
  1196. rfs_fpos_t sizeout=(rfs_fpos_t)-1;
  1197. RFS_ConnectionBase *conn = connlist.find(handle);
  1198. if (conn)
  1199. sizeout = conn->size();
  1200. else if (handle!=-1)
  1201. logError(&base,"Unexpected handle (size)",0,(unsigned)handle);
  1202. out.append((unsigned)RFEnoerror).append(sizeout);
  1203. }
  1204. break;
  1205. case RFCexists: {
  1206. const char * name = in.readFileName(tmp);
  1207. bool existsout = false;
  1208. base.existFile(name,existsout);
  1209. out.append((unsigned)RFEnoerror).append(existsout);
  1210. }
  1211. break;
  1212. case RFCremove: {
  1213. const char * name = in.readFileName(tmp);
  1214. base.removeFile(name);
  1215. out.append((unsigned)RFEnoerror).append((bool)true);
  1216. }
  1217. break;
  1218. case RFCrename: {
  1219. const char * name = in.readFileName(tmp);
  1220. const char * name2 = in.readFileName(tmp2);
  1221. base.renameFile(name,name2);
  1222. out.append((unsigned)RFEnoerror);
  1223. }
  1224. break;
  1225. case RFCgetver: {
  1226. char programname[256];
  1227. short version;
  1228. base.getVersion(sizeof(programname)-1,programname,version);
  1229. programname[255] = 0;
  1230. char ver[1024];
  1231. if (programname[0])
  1232. strcpy(ver,programname);
  1233. else
  1234. strcpy(ver,context.argv[0]);
  1235. strcat(ver,
  1236. #ifdef _WIN32
  1237. " - Windows"
  1238. #else
  1239. " - Linux"
  1240. #endif
  1241. );
  1242. if (in.length()-in.curPos()>sizeof(unsigned))
  1243. out.append((unsigned)RFEnoerror).append(ver);
  1244. else
  1245. out.append((unsigned)0x10000+version).append(ver);
  1246. }
  1247. break;
  1248. case RFCisfile:
  1249. case RFCisdirectory:
  1250. case RFCisreadonly: {
  1251. const char * name = in.readFileName(tmp);
  1252. bool existsout = false;
  1253. base.existFile(name,existsout);
  1254. unsigned ret = (unsigned)notFound;
  1255. if (existsout) {
  1256. if (cmd==RFCisfile)
  1257. base.isFile(name,existsout);
  1258. else if (cmd==RFCisdirectory)
  1259. base.isDir(name,existsout);
  1260. else
  1261. base.isReadOnly(name,existsout);
  1262. if (existsout)
  1263. ret = (unsigned)foundYes;
  1264. else
  1265. ret = (unsigned)foundNo;
  1266. }
  1267. out.append((unsigned)RFEnoerror).append(ret);
  1268. }
  1269. break;
  1270. case RFCgettime: {
  1271. const char * name = in.readFileName(tmp);
  1272. bool existsout = false;
  1273. base.existFile(name,existsout);
  1274. if (existsout) {
  1275. RFS_DateTime createTime;
  1276. RFS_DateTime modifiedTime;
  1277. RFS_DateTime accessedTime;
  1278. time_t created = 0;
  1279. time_t accessed = 0;
  1280. time_t modified = 0;
  1281. base.getFileTime(name,accessed,created,modified);
  1282. createTime.set(created);
  1283. modifiedTime.set(modified);
  1284. accessedTime.set(modified);
  1285. out.append((unsigned)RFEnoerror).append((bool)true);
  1286. createTime.serialize(out);
  1287. modifiedTime.serialize(out);
  1288. accessedTime.serialize(out);
  1289. }
  1290. else
  1291. out.append((unsigned)RFEnoerror).append((bool)false);
  1292. }
  1293. break;
  1294. case RFCsettime: {
  1295. const char * name = in.readFileName(tmp);
  1296. bool existsout = false;
  1297. base.existFile(name,existsout);
  1298. if (existsout) {
  1299. bool creategot;
  1300. RFS_DateTime createTime;
  1301. bool modifiedgot;
  1302. RFS_DateTime modifiedTime;
  1303. bool accessedgot;
  1304. RFS_DateTime accessedTime;
  1305. time_t created = 0;
  1306. time_t accessed = 0;
  1307. time_t modified = 0;
  1308. in.read(creategot);
  1309. if (creategot) {
  1310. createTime.deserialize(in);
  1311. created = createTime.get();
  1312. }
  1313. in.read(modifiedgot);
  1314. if (modifiedgot) {
  1315. modifiedTime.deserialize(in);
  1316. modified = modifiedTime.get();
  1317. }
  1318. in.read(accessedgot);
  1319. if (accessedgot) {
  1320. accessedTime.deserialize(in);
  1321. accessed = accessedTime.get();
  1322. }
  1323. base.setFileTime(name,accessedgot?&accessed:NULL,creategot?&created:NULL,modifiedgot?&modified:NULL);
  1324. out.append((unsigned)RFEnoerror).append((bool)true);
  1325. }
  1326. else
  1327. out.append((unsigned)RFEnoerror).append((bool)false);
  1328. }
  1329. break;
  1330. case RFCcreatedir: {
  1331. const char * name = in.readFileName(tmp);
  1332. bool createdout = false;
  1333. base.createDir(name,createdout);
  1334. out.append((unsigned)RFEnoerror).append(createdout);
  1335. }
  1336. break;
  1337. case RFCgetdir: {
  1338. const char * name = in.readFileName(tmp); // dir
  1339. const char * name2 = in.readFileName(tmp2); // mask -- need readFilename here?
  1340. bool includedir;
  1341. bool sub;
  1342. in.read(includedir);
  1343. in.read(sub);
  1344. void *handle;
  1345. base.openDir(name,name2,sub,includedir,handle);
  1346. char fn[1024];
  1347. byte b = 1;
  1348. out.append((unsigned)RFEnoerror);
  1349. while (1) {
  1350. fn[0] = 0;
  1351. time_t modified;
  1352. bool isdir = false;
  1353. rfs_fpos_t filesize = 0;
  1354. base.nextDirEntry(handle,sizeof(fn)-1,fn,isdir,filesize,modified);
  1355. if (!fn[0])
  1356. break;
  1357. out.append(b);
  1358. out.append(isdir);
  1359. if (isdir)
  1360. filesize = 0;
  1361. out.append(filesize);
  1362. RFS_DateTime dt;
  1363. dt.set(modified);
  1364. dt.serialize(out);
  1365. out.append(fn);
  1366. }
  1367. b = 0;
  1368. out.append(b);
  1369. }
  1370. break;
  1371. case RFCgetcrc: {
  1372. const char * name = in.readFileName(tmp);
  1373. int handle = 0;
  1374. class cH
  1375. {
  1376. public:
  1377. RFS_ConnectionBase *conn;
  1378. cH() { conn = NULL; }
  1379. ~cH() { delete conn; }
  1380. } ch;
  1381. ch.conn = base.open(name,RFS_OPEN_MODE_READ,RFS_SHARING_NONE);
  1382. if (!ch.conn)
  1383. base.throwError(2,name);
  1384. class cBuf
  1385. {
  1386. public:
  1387. byte * b;
  1388. size_t size;
  1389. cBuf() { size = 0x100000; b = (byte *)malloc(size); }
  1390. ~cBuf() { free(b); }
  1391. } buf;
  1392. rfs_fpos_t pos=0;
  1393. unsigned long crc=~0;
  1394. while (1) {
  1395. size_t sz = 0;
  1396. ch.conn->read(pos,buf.size,sz,buf.b);
  1397. if (sz==0)
  1398. break;
  1399. crc = crc32((const char *)buf.b,sz,crc);
  1400. pos += sz;
  1401. }
  1402. }
  1403. break;
  1404. default: {
  1405. char errormsg[256];
  1406. strcpy(errormsg,"RFSERR_InvalidCommand:");
  1407. _itoa(cmd,&errormsg[strlen(errormsg)],10);
  1408. out.clear().append(RFSERR_InvalidCommand).append(errormsg);
  1409. }
  1410. }
  1411. }
  1412. catch (RFS_Exception *e)
  1413. {
  1414. if (e->fatal)
  1415. throw;
  1416. out.clear().append(e->rfserr).append(e->str);
  1417. RFS_SimpleString errs("RFS_Exception: ");
  1418. struct sockaddr_in *nameptr;
  1419. struct sockaddr_in name;
  1420. socklen_t namelen = sizeof(name);
  1421. nameptr = &name;
  1422. if(getpeername(sock,(struct sockaddr*)&name, &namelen)>=0) {
  1423. errs.appends(inet_ntoa(nameptr->sin_addr));
  1424. errs.appendc(' ');
  1425. }
  1426. errs.appends(e->str);
  1427. logError(&base,errs.str(),0);
  1428. delete e;
  1429. }
  1430. context.cmd = RFCnone;
  1431. return sendBuffer(&base,sock,out);
  1432. }
  1433. RFS_ServerBase::~RFS_ServerBase()
  1434. {
  1435. if (context) {
  1436. setLogFilename(NULL);
  1437. while (context->argc--)
  1438. free((char *)context->argv[context->argc]);
  1439. free(context->argv);
  1440. if (context->listensock!=INVALID_SOCKET)
  1441. #ifdef _WIN32
  1442. ::closesocket(context->listensock);
  1443. #else
  1444. ::close(context->listensock);
  1445. #endif
  1446. }
  1447. #ifdef _WIN32
  1448. delete context->ws32_lib;
  1449. #endif
  1450. delete context;
  1451. }
  1452. #ifdef _WIN32
  1453. // Service initialization
  1454. //==============================================================================
  1455. class RFS_WindowsService
  1456. {
  1457. RFS_ServerBase &parent;
  1458. char servicename[256];
  1459. char displayname[256];
  1460. SERVICE_STATUS ServiceStatus;
  1461. SERVICE_STATUS_HANDLE hStatus;
  1462. // Control handler function
  1463. void doControlHandler(DWORD request)
  1464. {
  1465. switch(request) {
  1466. case SERVICE_CONTROL_STOP:
  1467. ServiceStatus.dwWin32ExitCode = 0;
  1468. ServiceStatus.dwCurrentState = SERVICE_STOPPED;
  1469. break;
  1470. case SERVICE_CONTROL_SHUTDOWN:
  1471. ServiceStatus.dwWin32ExitCode = 0;
  1472. ServiceStatus.dwCurrentState = SERVICE_STOPPED;
  1473. break;
  1474. case SERVICE_CONTROL_INTERROGATE:
  1475. break;
  1476. default:
  1477. break;
  1478. }
  1479. // Report current status
  1480. SetServiceStatus (hStatus, &ServiceStatus);
  1481. return;
  1482. }
  1483. void doServiceMain(int argc, char** argv)
  1484. {
  1485. ServiceStatus.dwServiceType = SERVICE_WIN32;
  1486. ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
  1487. ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  1488. ServiceStatus.dwWin32ExitCode = 0;
  1489. ServiceStatus.dwServiceSpecificExitCode = 0;
  1490. ServiceStatus.dwCheckPoint = 0;
  1491. ServiceStatus.dwWaitHint = 0;
  1492. parent.getServiceName(sizeof(servicename),servicename,sizeof(displayname),displayname);
  1493. hStatus = RegisterServiceCtrlHandlerA(servicename, (LPHANDLER_FUNCTION)ControlHandler);
  1494. if (hStatus == (SERVICE_STATUS_HANDLE)0) {
  1495. // Registering Control Handler failed
  1496. logError(&parent,"RegisterServiceCtrlHandler",GetLastError());
  1497. return;
  1498. }
  1499. bool multi=false;
  1500. if (!parent.queryContext()||(parent.serviceInit(parent.queryContext()->argc,parent.queryContext()->argv,multi)!=0)) {
  1501. // Initialization failed
  1502. ServiceStatus.dwCurrentState = SERVICE_STOPPED;
  1503. ServiceStatus.dwWin32ExitCode = -1;
  1504. SetServiceStatus(hStatus, &ServiceStatus);
  1505. return;
  1506. }
  1507. ServiceStatus.dwCurrentState = SERVICE_RUNNING;
  1508. SetServiceStatus (hStatus, &ServiceStatus);
  1509. // Autentication gets params from HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\XXXX\Parameters
  1510. // Not yet implemented (clients do not currently require authentication)
  1511. parent.run(multi,parent.logFilename());
  1512. }
  1513. public:
  1514. RFS_WindowsService(RFS_ServerBase &_parent)
  1515. : parent(_parent)
  1516. {
  1517. }
  1518. void start()
  1519. {
  1520. parent.getServiceName(sizeof(servicename),servicename,sizeof(displayname),displayname);
  1521. SERVICE_TABLE_ENTRYA ServiceTable[2];
  1522. ServiceTable[0].lpServiceName = servicename;
  1523. ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTIONA)ServiceMain;
  1524. ServiceTable[1].lpServiceName = NULL;
  1525. ServiceTable[1].lpServiceProc = NULL;
  1526. // Start the control dispatcher thread for our service
  1527. if (!StartServiceCtrlDispatcherA(ServiceTable)) {
  1528. logError(&parent,"StartServiceCtrlDispatcher",GetLastError());
  1529. }
  1530. }
  1531. void stop()
  1532. {
  1533. ServiceStatus.dwCurrentState = SERVICE_STOPPED;
  1534. ServiceStatus.dwCheckPoint = 0;
  1535. ServiceStatus.dwWaitHint = 0;
  1536. ServiceStatus.dwWin32ExitCode = 0;
  1537. ServiceStatus.dwServiceSpecificExitCode = 0;
  1538. SetServiceStatus(hStatus, &ServiceStatus);
  1539. }
  1540. // Control handler function
  1541. static void ControlHandler(DWORD request)
  1542. {
  1543. RFS_context::RFS_Service->doControlHandler(request) ;
  1544. }
  1545. static void ServiceMain(int argc, char** argv)
  1546. {
  1547. RFS_context::RFS_Service->doServiceMain(argc, argv);
  1548. }
  1549. bool running() { return ServiceStatus.dwCurrentState == SERVICE_RUNNING; }
  1550. };
  1551. bool installService(const char *servicename,const char *servicedisplayname,const char *dependancies,int argc, const char **argv)
  1552. {
  1553. DWORD err = ERROR_SUCCESS;
  1554. char path[512];
  1555. if (GetModuleFileNameA( NULL, path, sizeof(path) )) {
  1556. SC_HANDLE hSCM = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS); // full access rights
  1557. if (hSCM) {
  1558. size_t sz = strlen(path)+12; // calc max size for command line
  1559. for (int i0=0;i0<argc;i0++) {
  1560. if (argv[i0])
  1561. sz += strlen(argv[i0])+1;
  1562. }
  1563. char *fullpath = (char *)malloc(sz);
  1564. strcpy(fullpath,path);
  1565. strcat(fullpath," --service");
  1566. for (int i=0;i<argc;i++) {
  1567. strcat(fullpath," ");
  1568. strcat(fullpath,argv[i]);
  1569. }
  1570. SC_HANDLE hService = CreateServiceA(
  1571. hSCM, servicename, servicedisplayname,
  1572. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  1573. SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
  1574. fullpath,NULL,NULL,dependancies,NULL,NULL);
  1575. if (hService) {
  1576. Sleep(1000);
  1577. StartService(hService,0,0);
  1578. CloseServiceHandle(hService);
  1579. }
  1580. else
  1581. err = GetLastError();
  1582. free(fullpath);
  1583. CloseServiceHandle(hSCM); }
  1584. else
  1585. err = GetLastError();
  1586. }
  1587. else
  1588. err = GetLastError();
  1589. if (err!=ERROR_SUCCESS) {
  1590. logError(NULL,"Install failed",err);
  1591. return false;
  1592. }
  1593. return true;
  1594. }
  1595. bool uninstallService(const char *servicename,const char *servicedisplayname)
  1596. {
  1597. DWORD err = ERROR_SUCCESS;
  1598. SC_HANDLE hSCM = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS); // full access rights
  1599. if (hSCM) {
  1600. SC_HANDLE hService = OpenServiceA(hSCM, servicename, SERVICE_STOP|SERVICE_QUERY_STATUS);
  1601. if (hService) {
  1602. // try to stop the service
  1603. SERVICE_STATUS ss;
  1604. if ( ControlService( hService, SERVICE_CONTROL_STOP, &ss ) ) {
  1605. Sleep( 1000 );
  1606. while( QueryServiceStatus( hService, &ss ) ) {
  1607. if ( ss.dwCurrentState != SERVICE_STOP_PENDING )
  1608. break;
  1609. Sleep( 1000 );
  1610. }
  1611. if ( ss.dwCurrentState != SERVICE_STOPPED )
  1612. logError(NULL,"Failed to stop",0);
  1613. }
  1614. CloseServiceHandle(hService);
  1615. }
  1616. hService = OpenServiceA(hSCM, servicename, DELETE);
  1617. if (hService) {
  1618. // now remove the service
  1619. if (!DeleteService(hService))
  1620. err = GetLastError();
  1621. CloseServiceHandle(hService);
  1622. }
  1623. else
  1624. err = GetLastError();
  1625. CloseServiceHandle(hSCM);
  1626. }
  1627. else
  1628. err = GetLastError();
  1629. if (err!=ERROR_SUCCESS) {
  1630. logError(NULL,"Uninstall failed",err);
  1631. return false;
  1632. }
  1633. return true;
  1634. }
  1635. class RFS_WindowsService *RFS_context::RFS_Service = NULL;
  1636. #else // linux
  1637. // Daemon initialization
  1638. //==============================================================================
  1639. static int makeDaemon()
  1640. {
  1641. pid_t pid, sid;
  1642. pid = fork();
  1643. if (pid < 0) {
  1644. logError(NULL,"fork failed",errno);
  1645. return(EXIT_FAILURE);
  1646. }
  1647. if (pid > 0)
  1648. exit(EXIT_SUCCESS);
  1649. if ((sid = setsid()) < 0) {
  1650. logError(NULL,"setsid failed",errno);
  1651. return(EXIT_FAILURE);
  1652. }
  1653. umask(0);
  1654. freopen("/dev/null", "r", stdin);
  1655. freopen("/dev/null", "w", stdout);
  1656. freopen("/dev/null", "w", stderr);
  1657. pid = fork(); // To prevent zombies
  1658. if (pid < 0) {
  1659. logError(NULL,"fork failed(2)",errno);
  1660. return(EXIT_FAILURE);
  1661. }
  1662. if (pid > 0)
  1663. exit(EXIT_SUCCESS);
  1664. return(EXIT_SUCCESS);
  1665. }
  1666. #endif
  1667. int RFS_ServerBase::run(bool multi, const char *logname)
  1668. {
  1669. assert(!multi); // multi TBD
  1670. assert(context);
  1671. assert(context->port);
  1672. context->cmd = RFCnone;
  1673. short ver = 0;
  1674. char *progname = (char *)malloc(1024);
  1675. char *hostname = (char *)malloc(1024);
  1676. progname[0] = 0;
  1677. hostname[0] = 0;
  1678. getVersion(1024,progname, ver);
  1679. #ifdef _WIN32
  1680. if (gethostname(hostname, 1024)!=0) {
  1681. int err = ERRNO();
  1682. if ((err==WSANOTINITIALISED)&&!context->ws32_lib)
  1683. context->ws32_lib = new win_socket_library;
  1684. gethostname(hostname, 1024);
  1685. }
  1686. #else
  1687. gethostname(hostname, 1024);
  1688. #endif
  1689. setLogFilename(logname);
  1690. log("Opening DIFS Server %s on %s port %d", progname, hostname, (int)context->port);
  1691. log("Version: %d", (int)ver);
  1692. log("PID: %d", (int)getpid());
  1693. free(progname);
  1694. free(hostname);
  1695. unsigned maxsocks = 16;
  1696. unsigned numsocks = 0;
  1697. T_SOCKET *socks = new T_SOCKET[maxsocks];
  1698. RFS_MemoryBuffer *inbuf = new RFS_MemoryBuffer[maxsocks];
  1699. RFS_ConnectionList *conns = new RFS_ConnectionList[maxsocks];
  1700. try {
  1701. context->listensock = ::socket(AF_INET, SOCK_STREAM, 0);
  1702. if (context->listensock == INVALID_SOCKET)
  1703. throwError(ERRNO(),"::socket",true);
  1704. #ifndef _WIN32
  1705. {
  1706. int on = 1;
  1707. setsockopt( context->listensock, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on));
  1708. }
  1709. #endif
  1710. socks[numsocks++] = context->listensock;
  1711. struct sockaddr_in u;
  1712. memset(&u, 0, sizeof(u));
  1713. u.sin_family = AF_INET;
  1714. u.sin_addr.s_addr = htonl(INADDR_ANY);
  1715. u.sin_port = htons(context->port);
  1716. if (::bind(context->listensock, (struct sockaddr *)&u, sizeof(u)) == -1)
  1717. throwError(ERRNO(),"::bind",true);
  1718. if (::listen(context->listensock, 16) == -1)
  1719. throwError(ERRNO(),"::listen",true);
  1720. time_t lastpoll = time(NULL);
  1721. unsigned idlecount = 0;
  1722. context->running = true;
  1723. while (context->running) {
  1724. struct timeval tv;
  1725. tv.tv_sec = 1;
  1726. tv.tv_usec = 0;
  1727. int fdmax = 0;
  1728. fd_set fds;
  1729. FD_ZERO(&fds);
  1730. for (unsigned i=0;i<numsocks;i++) { // this can be expensive but hopefully not large here
  1731. if (socks[i]!=INVALID_SOCKET) {
  1732. FD_SET(socks[i],&fds);
  1733. if (fdmax<(int)socks[i])
  1734. fdmax = socks[i];
  1735. }
  1736. }
  1737. int rc = ::select(fdmax+1, &fds, NULL, NULL, &tv);
  1738. if (rc > 0) {
  1739. // select suceeded
  1740. unsigned i = 0;
  1741. while (context->running&&(i<numsocks)) {
  1742. T_SOCKET sock = socks[i];
  1743. if (sock!=INVALID_SOCKET) {
  1744. if ((FD_ISSET(sock,&fds))) {
  1745. if (i==0) { // connection
  1746. int newsock = ::accept(context->listensock, NULL, NULL);
  1747. if (newsock==-1) {
  1748. throwError(ERRNO(),"::accept",true);
  1749. }
  1750. unsigned j;
  1751. for (j=0;j<numsocks;j++) {
  1752. if (socks[j]==INVALID_SOCKET) {
  1753. socks[j] = newsock;
  1754. break;
  1755. }
  1756. }
  1757. if (j==numsocks) {
  1758. if (numsocks>=maxsocks) {
  1759. maxsocks += 16;
  1760. T_SOCKET *old = socks;
  1761. socks = NULL;
  1762. socks = new T_SOCKET[maxsocks];
  1763. memcpy(socks,old,sizeof(T_SOCKET)*numsocks);
  1764. delete [] old;
  1765. RFS_MemoryBuffer *oldbuf = inbuf;
  1766. inbuf = NULL;
  1767. inbuf = new RFS_MemoryBuffer[maxsocks];
  1768. unsigned j;
  1769. for (j=0;j<maxsocks-16;j++)
  1770. inbuf[j].swapWith(oldbuf[j]);
  1771. delete [] oldbuf;
  1772. RFS_ConnectionList *oldcl = conns;
  1773. conns = NULL;
  1774. conns = new RFS_ConnectionList[maxsocks];
  1775. for (j=0;j<maxsocks-16;j++)
  1776. conns[j].swapWith(oldcl[j]);
  1777. delete [] oldcl;
  1778. }
  1779. socks[numsocks++] = newsock;
  1780. }
  1781. }
  1782. else { // command
  1783. RFS_MemoryBuffer &in = inbuf[i];
  1784. RFS_ConnectionList &connlist = conns[i];
  1785. int err;
  1786. if (!in.maxLength()) {
  1787. // read size
  1788. unsigned blocksize;
  1789. size_t ret = do_recv(sock, (char *)&blocksize, sizeof(blocksize),err);
  1790. if (ret!=sizeof(blocksize)) {
  1791. if (ret!=0)
  1792. logError(this,"recv failed",ERRNO(),(unsigned)ret);
  1793. blocksize = 0;
  1794. }
  1795. BECONV(blocksize);
  1796. if (blocksize>MAX_BLOCK_SIZE) {
  1797. logError(this,"recv failed block too big",ERRNO(),(unsigned)blocksize);
  1798. blocksize = 0;
  1799. }
  1800. if (blocksize==0) {
  1801. for (unsigned j=0;j<numsocks;j++) {
  1802. if (socks[i]==sock) {
  1803. socks[i] = INVALID_SOCKET;
  1804. break;
  1805. }
  1806. ::closesocket(sock);
  1807. }
  1808. sock = INVALID_SOCKET;
  1809. }
  1810. in.clear(blocksize);
  1811. }
  1812. if (sock != INVALID_SOCKET) {
  1813. // read as much as have
  1814. #ifdef _WIN32
  1815. u_long avail;
  1816. if (ioctlsocket(sock, FIONREAD, &avail)!=0)
  1817. #else
  1818. int avail;
  1819. if (ioctl(sock, FIONREAD, &avail)!=0)
  1820. #endif
  1821. {
  1822. logError(this,"ioctl failed",ERRNO());
  1823. avail = 0;
  1824. }
  1825. if (avail) {
  1826. if (avail>in.maxLength()-in.length()) // protocol error?
  1827. avail = in.maxLength()-in.length();
  1828. size_t ret = do_recv(sock, (char *)in.reserve(avail), avail,err);
  1829. if (ret!=avail) {
  1830. char ln[255];
  1831. sprintf(ln,"recv failed expected %d, got %d",avail,ret);
  1832. logError(this,ln,ERRNO());
  1833. }
  1834. }
  1835. if (in.maxLength()==in.length()) {
  1836. if (!processCommand(*this,*context,connlist,sock,in)) {
  1837. if (socks[i]==sock) {
  1838. socks[i] = INVALID_SOCKET;
  1839. break;
  1840. }
  1841. ::closesocket(sock);
  1842. }
  1843. in.clear();
  1844. }
  1845. }
  1846. }
  1847. }
  1848. }
  1849. i++;
  1850. }
  1851. }
  1852. else if (rc<0) {
  1853. int err = ERRNO();
  1854. if (err==EINTRCALL)
  1855. continue;
  1856. throwError(ERRNO(),"::select",true);
  1857. }
  1858. time_t t = time(NULL);
  1859. if (t-lastpoll>0) {
  1860. if (rc>0)
  1861. idlecount = 0;
  1862. else
  1863. idlecount += (unsigned)(t-lastpoll);
  1864. lastpoll = t;
  1865. poll();
  1866. }
  1867. #ifdef _WIN32
  1868. if (context->RFS_Service&&!context->RFS_Service->running())
  1869. context->running = false;
  1870. #endif
  1871. }
  1872. }
  1873. catch (RFS_Exception *e)
  1874. {
  1875. logError(this,e->str,0);
  1876. delete e;
  1877. }
  1878. catch (...) {
  1879. logError(this,"Unknown exception raised",0);
  1880. }
  1881. delete [] conns;
  1882. delete [] socks;
  1883. delete [] inbuf;
  1884. return 0;
  1885. }
  1886. void RFS_ServerBase::stop()
  1887. {
  1888. context->running = false;
  1889. }
  1890. void RFS_ServerBase::throwError(int err, const char *errstr, bool fatal)
  1891. {
  1892. int rfserr = RFSERR_SysError;
  1893. for (unsigned i=0;;i++)
  1894. if (mapCmdToErr[i].cmd == context->cmd) {
  1895. rfserr = mapCmdToErr[i].err;
  1896. break;
  1897. }
  1898. else if (mapCmdToErr[i].cmd == RFCmax)
  1899. break;
  1900. throw new RFS_Exception(rfserr, err, errstr, fatal);
  1901. }
  1902. bool RFS_ServerBase::init(int &argc, const char **argv)
  1903. {
  1904. assert(context==NULL); // must be called once at start
  1905. assert(argc);
  1906. assert(argv);
  1907. context = new RFS_context;
  1908. context->port = 0;
  1909. context->running = false;
  1910. context->listensock = INVALID_SOCKET;
  1911. context->cmd = RFCnone;
  1912. context->logname = NULL;
  1913. context->debug = 0;
  1914. #ifdef _WIN32
  1915. context->ws32_lib = NULL;
  1916. context->RFS_Service = NULL;
  1917. #else
  1918. context->daemon = false;
  1919. #endif
  1920. context->argc = 1;
  1921. context->argv = (const char **)malloc(sizeof(const char *));
  1922. context->argv[0] = _strdup(argv[0]);
  1923. int fp = 1;
  1924. // first param can be service/daemon
  1925. if (argc>1) {
  1926. #ifdef _WIN32
  1927. if (_stricmp(argv[1],"--install")==0) {
  1928. char servicename[256];
  1929. char displayname[256];
  1930. getServiceName(sizeof(servicename),servicename,sizeof(displayname),displayname);
  1931. if (installService(servicename,displayname,NULL,argc-2,argv+2)) {
  1932. printf("Service %s installed",displayname);
  1933. return 0;
  1934. }
  1935. return false;
  1936. }
  1937. if (_stricmp(argv[1],"--remove")==0) {
  1938. char servicename[256];
  1939. char displayname[256];
  1940. getServiceName(sizeof(servicename)-1,servicename,sizeof(displayname)-1,displayname);
  1941. if (uninstallService(servicename,displayname)) {
  1942. printf("Service %s uninstalled",displayname);
  1943. return 0;
  1944. }
  1945. return false;
  1946. }
  1947. #else
  1948. if (_stricmp(argv[1],"--daemon=")==0) {
  1949. context->daemon = true;
  1950. }
  1951. #endif
  1952. }
  1953. // other params
  1954. for (int i=fp;i<argc;i++) {
  1955. const char *arg = argv[i];
  1956. if (!arg)
  1957. break;
  1958. bool consumed = false;
  1959. if (*arg=='-') {
  1960. if (strncasecmp(arg+1,"-port=",6)==0) {
  1961. context->port = atoi(arg+7);
  1962. consumed = true;
  1963. }
  1964. if (strncasecmp(arg+1,"-debug=",7)==0) {
  1965. context->debug = atoi(arg+8);
  1966. consumed = true;
  1967. }
  1968. #ifdef _WIN32
  1969. if (_stricmp(arg+1,"-service")==0) {
  1970. context->RFS_Service = new RFS_WindowsService(*this);
  1971. consumed = true;
  1972. }
  1973. #endif
  1974. }
  1975. if (consumed) {
  1976. for (int j=i+1;j<argc;j++)
  1977. argv[j-1] = argv[j];
  1978. argc--;
  1979. i--;
  1980. }
  1981. else {
  1982. context->argc++;
  1983. context->argv = (const char **)realloc(context->argv,sizeof(const char *)*context->argc);
  1984. context->argv[context->argc-1] = _strdup(arg);
  1985. }
  1986. }
  1987. if (!context->port) {
  1988. context->port = getDefaultPort();
  1989. if (!context->port)
  1990. return false;
  1991. }
  1992. #ifdef _WIN32
  1993. if (context->RFS_Service) {
  1994. context->RFS_Service->start();
  1995. return false;
  1996. }
  1997. #endif
  1998. return true;
  1999. }
  2000. void RFS_ServerBase::setLogFilename(const char *filename)
  2001. {
  2002. free(context->logname);
  2003. if (!filename) {
  2004. context->logname = NULL;
  2005. return;
  2006. }
  2007. char *deflogname=NULL;
  2008. if (!*filename) {
  2009. const char * ts = context->argv[0];
  2010. const char * te = ts;
  2011. const char * ex = NULL;
  2012. #ifdef _WIN32
  2013. char tmp[256];
  2014. if (context->RFS_Service) {
  2015. char displayname[256];
  2016. strcpy(tmp,"c:\\");
  2017. getServiceName(sizeof(tmp)-4,tmp+3,sizeof(displayname)-1,displayname);
  2018. ts = tmp;
  2019. te = ts+strlen(ts);
  2020. }
  2021. #endif
  2022. while (*te) {
  2023. if ((*te=='/')||(*te=='\\')) {
  2024. if (te[1])
  2025. ts = te+1;
  2026. }
  2027. else if (*te=='.')
  2028. ex = te;
  2029. te++;
  2030. }
  2031. if (!ex)
  2032. ex = te;
  2033. deflogname = (char *)malloc(strlen(ts)+32);
  2034. time_t st;
  2035. time(&st);
  2036. struct tm *_tm = localtime(&st);
  2037. int l = (int)(ex-ts);
  2038. sprintf(deflogname,"%.*s.%02u_%02u_%02u_%02u_%02u_%02u.log", (int)(ex-ts), ts, _tm->tm_mon+1,_tm->tm_mday,_tm->tm_year%100,_tm->tm_hour,_tm->tm_min,_tm->tm_sec);
  2039. filename = deflogname;
  2040. }
  2041. context->logname = (char *)malloc(512);
  2042. #ifdef _WIN32
  2043. char *filepart;
  2044. GetFullPathNameA(filename, 512, context->logname, &filepart);
  2045. #else
  2046. realpath(filename,context->logname);
  2047. #endif
  2048. free(deflogname);
  2049. }
  2050. void RFS_ServerBase::log(const char *fmt, ...)
  2051. {
  2052. if (context->logname==NULL)
  2053. return;
  2054. size_t sz = 1024;
  2055. va_list ap;
  2056. char *s = (char *)malloc(sz);
  2057. while (s) {
  2058. va_start(ap, fmt);
  2059. int ret = _vsnprintf (s, sz, fmt, ap);
  2060. va_end(ap);
  2061. if ((ret >= 0)&&(ret<(int)sz)) {
  2062. sz = ret;
  2063. break;
  2064. }
  2065. if (ret >= 0)
  2066. sz = ret+1;
  2067. else
  2068. sz *= 2;
  2069. void *n = realloc(s,sz);
  2070. if (n)
  2071. free(s);
  2072. s = (char *)n;
  2073. }
  2074. if (s) {
  2075. char timeStamp[32];
  2076. time_t tNow;
  2077. time(&tNow);
  2078. #ifdef WIN32
  2079. strftime(timeStamp, 32, "%Y-%m-%d %H:%M:%S ", localtime(&tNow));
  2080. #else
  2081. struct tm ltNow;
  2082. localtime_r(&tNow, &ltNow);
  2083. strftime(timeStamp, 32, "%Y-%m-%d %H:%M:%S ", &ltNow);
  2084. #endif
  2085. RFS_SimpleString out(timeStamp);
  2086. out.appends(s);
  2087. out.appendc('\n');
  2088. int logfile = _open(context->logname,_O_WRONLY | _O_CREAT | _O_APPEND ,
  2089. _S_IREAD|_S_IWRITE // not quite sure about this
  2090. );
  2091. if (logfile>=0) {
  2092. if (_write(logfile,out.str(),out.length())>0) {
  2093. free(s);
  2094. _close(logfile);
  2095. return;
  2096. }
  2097. _close(logfile);
  2098. }
  2099. static bool firsterr = true;
  2100. if (firsterr) {
  2101. firsterr = false;
  2102. logError(this, context->logname ,errno);
  2103. }
  2104. fprintf(stderr,"%.*s",out.length(),out.str());
  2105. free(s);
  2106. }
  2107. }
  2108. int RFS_ServerBase::debugLevel() { return context?context->debug:0; }
  2109. const char * RFS_ServerBase::logFilename()
  2110. {
  2111. return context?context->logname:NULL;
  2112. }
  2113. unsigned short RFS_ServerBase::getDefaultPort()
  2114. {
  2115. logError(NULL,"port not specified (e.g. --port=7080)",0);
  2116. return 0;
  2117. }
  2118. void RFS_ServerBase::getServiceName(size_t maxname, char *outname,
  2119. size_t maxdisplayname, char *outdisplayname)
  2120. {
  2121. logError(NULL,"Service installation not allowed",0);
  2122. outname[0] = 0;
  2123. outdisplayname[0] = 0;
  2124. }
  2125. int RFS_ServerBase::serviceInit(int argc, const char **argv,
  2126. bool &outmulti)
  2127. {
  2128. return 0;
  2129. }
  2130. RFS_context *RFS_ServerBase::queryContext()
  2131. {
  2132. return context;
  2133. }
  2134. RFS_CSVwriter::RFS_CSVwriter()
  2135. : out(NULL,0x10000)
  2136. {
  2137. }
  2138. void RFS_CSVwriter::rewrite()
  2139. {
  2140. out.clear();
  2141. }
  2142. void RFS_CSVwriter::putField(size_t fldsize,void *data)
  2143. {
  2144. out.appendc('\'');
  2145. char *s = (char *)data;
  2146. while (fldsize--) {
  2147. char c = *(s++);
  2148. if (c=='\'')
  2149. out.appendc(c);
  2150. out.appendc(c);
  2151. }
  2152. out.appendc('\'');
  2153. out.appendc(',');
  2154. }
  2155. void RFS_CSVwriter::putRow()
  2156. {
  2157. if (out.length())
  2158. out.data()[out.length()-1] = '\n';
  2159. }
  2160. void RFS_CSVwriter::consume(size_t sz)
  2161. {
  2162. // this could be done better (copies a bit too much!)
  2163. assert(sz<=out.length());
  2164. if (sz>out.length())
  2165. sz = out.length();
  2166. memmove(out.data(),out.data()+sz,out.length()-sz);
  2167. out.setLength(out.length()-sz);
  2168. }
  2169. RFS_CSVreader::RFS_CSVreader()
  2170. : fld(NULL,0x10000)
  2171. {
  2172. str = NULL;
  2173. end = NULL;
  2174. }
  2175. void RFS_CSVreader::reset(size_t sz,const void *data)
  2176. {
  2177. str = (char *)data;
  2178. end = str + (str?sz:0);
  2179. fld.clear();
  2180. }
  2181. bool RFS_CSVreader::nextRow()
  2182. {
  2183. while (str!=end) {
  2184. if (*str!='\n')
  2185. return true;
  2186. str++;
  2187. }
  2188. return false;
  2189. }
  2190. const char * RFS_CSVreader::getField(size_t &fldsize)
  2191. {
  2192. if ((str==end) || (*str=='\n')) {
  2193. fldsize = 0;
  2194. return NULL;
  2195. }
  2196. fld.clear();
  2197. char quote = 0;
  2198. if (*str=='\'')
  2199. quote = *(str++);
  2200. while (str!=end) {
  2201. char c = *(str++);
  2202. if (c==quote) {
  2203. if ((str==end)||(*str!=quote))
  2204. break;
  2205. str++;
  2206. } else if (!quote&&(c==','))
  2207. break;
  2208. fld.appendc(c);
  2209. }
  2210. if (*str==',')
  2211. str++;
  2212. fldsize = fld.length();
  2213. return fld.str();
  2214. }
  2215. RFS_SimpleString::RFS_SimpleString(const char *inits,size_t initsz)
  2216. {
  2217. inc = initsz;
  2218. if (inc<0x1000)
  2219. inc = 0x1000;
  2220. max = initsz;
  2221. if (inits) {
  2222. size_t sz = strlen(inits);
  2223. if (sz>=max)
  2224. max = sz+1;
  2225. base = (char *)malloc(max);
  2226. memcpy(base,inits,sz);
  2227. end = base+sz;
  2228. }
  2229. else {
  2230. base = (char *)malloc(max);
  2231. end = base;
  2232. }
  2233. }
  2234. void RFS_SimpleString::appendc(char c)
  2235. {
  2236. size_t l = end-base;
  2237. if (l+1>=max) {
  2238. max += 0x1000;
  2239. base = (char *)realloc(base,max);
  2240. end = base+l;
  2241. }
  2242. *(end++) = c;
  2243. }
  2244. void RFS_SimpleString::appends(const char *s)
  2245. {
  2246. while (*s)
  2247. appendc(*(s++));
  2248. }
  2249. void RFS_SimpleString::trim()
  2250. {
  2251. while ((end!=base)&&(isspace((unsigned char)*(end-1))))
  2252. end--;
  2253. }