vlmcsd.c 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774
  1. #ifndef CONFIG
  2. #define CONFIG "config.h"
  3. #endif // CONFIG
  4. #include CONFIG
  5. #if defined(USE_MSRPC) && !defined(_WIN32) && !defined(__CYGWIN__)
  6. #error Microsoft RPC is only available on Windows and Cygwin
  7. #endif
  8. #if defined(USE_MSRPC) && defined(SIMPLE_SOCKETS)
  9. #error You can only define either USE_MSRPC or SIMPLE_SOCKETS but not both
  10. #endif
  11. #if defined(NO_SOCKETS) && defined(USE_MSRPC)
  12. #error Cannot use inetd mode with Microsoft RPC
  13. #endif
  14. #ifndef _GNU_SOURCE
  15. #define _GNU_SOURCE
  16. #endif
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <errno.h>
  21. #include <stdint.h>
  22. #ifndef _WIN32
  23. #include <pwd.h>
  24. #include <grp.h>
  25. #include <sys/types.h>
  26. #if !defined(NO_LIMIT) && !__minix__
  27. #include <sys/ipc.h>
  28. #if !__ANDROID__
  29. #include <sys/shm.h>
  30. #else // __ANDROID__
  31. #include <sys/syscall.h>
  32. #endif // __ANDROID__
  33. #endif // !defined(NO_LIMIT) && !__minix__
  34. #include <sys/wait.h>
  35. #include <unistd.h>
  36. #include <fcntl.h>
  37. #include <sys/stat.h>
  38. #ifndef NO_LIMIT
  39. #include <semaphore.h>
  40. #endif // NO_LIMIT
  41. #endif // !_WIN32
  42. #if __APPLE__
  43. #include <mach-o/dyld.h>
  44. #endif // __APPLE__
  45. #if __linux__ && defined(USE_AUXV)
  46. #include <sys/auxv.h>
  47. #endif
  48. #if __FreeBSD__
  49. #include <sys/sysctl.h>
  50. #endif
  51. #include "vlmcsd.h"
  52. #include "endian.h"
  53. #include "shared_globals.h"
  54. #include "output.h"
  55. #ifndef USE_MSRPC
  56. #include "network.h"
  57. #else // USE_MSRPC
  58. #include "msrpc-server.h"
  59. #endif // USE_MSRPC
  60. #include "ntservice.h"
  61. #include "helpers.h"
  62. static const char* const optstring = "N:B:m:t:w:0:3:H:A:R:u:g:L:p:i:P:l:r:U:W:C:F:o:T:SseDdVvqkZ";
  63. #if !defined(NO_SOCKETS) && !defined(USE_MSRPC) && !defined(SIMPLE_SOCKETS)
  64. static uint_fast8_t maxsockets = 0;
  65. #endif // !defined(NO_SOCKETS) && !defined(USE_MSRPC) && !defined(SIMPLE_SOCKETS)
  66. #ifdef _NTSERVICE
  67. static int_fast8_t installService = 0;
  68. static const char *restrict ServiceUser = NULL;
  69. static const char *restrict ServicePassword = "";
  70. #endif
  71. #ifndef NO_PID_FILE
  72. static const char *fn_pid = NULL;
  73. #endif
  74. #ifndef NO_INI_FILE
  75. #ifdef INI_FILE
  76. static const char *fn_ini = INI_FILE;
  77. #else // !INI_FILE
  78. static const char *fn_ini = NULL;
  79. #endif // !INI_FILE
  80. static const char* IniFileErrorMessage = "";
  81. char* IniFileErrorBuffer = NULL;
  82. #define INIFILE_ERROR_BUFFERSIZE 256
  83. static IniFileParameter_t IniFileParameterList[] =
  84. {
  85. # ifndef NO_RANDOM_EPID
  86. { "RandomizationLevel", INI_PARAM_RANDOMIZATION_LEVEL },
  87. { "LCID", INI_PARAM_LCID },
  88. # endif // NO_RANDOM_EPID
  89. # if !defined(NO_SOCKETS) && (defined(USE_MSRPC) || defined(SIMPLE_SOCKETS) || defined(HAVE_GETIFADDR))
  90. { "Port", INI_PARAM_PORT },
  91. # endif // defined(USE_MSRPC) || defined(SIMPLE_SOCKETS)
  92. # if !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  93. # ifndef SIMPLE_SOCKETS
  94. { "Listen", INI_PARAM_LISTEN },
  95. # endif // SIMPLE_SOCKETS
  96. # if HAVE_FREEBIND
  97. { "FreeBind", INI_PARAM_FREEBIND },
  98. # endif // HAVE_FREEBIND
  99. # if !defined(NO_LIMIT) && !__minix__
  100. { "MaxWorkers", INI_PARAM_MAX_WORKERS },
  101. # endif // !defined(NO_LIMIT) && !__minix__
  102. # endif // !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  103. # if !defined(NO_TIMEOUT) && !__minix__ && !defined(USE_MSRPC) & !defined(USE_MSRPC)
  104. { "ConnectionTimeout", INI_PARAM_CONNECTION_TIMEOUT },
  105. # endif // !defined(NO_TIMEOUT) && !__minix__ && !defined(USE_MSRPC) & !defined(USE_MSRPC)
  106. # ifndef USE_MSRPC
  107. { "DisconnectClientsImmediately", INI_PARAM_DISCONNECT_IMMEDIATELY },
  108. { "UseNDR64", INI_PARAM_RPC_NDR64 },
  109. { "UseBTFN", INI_PARAM_RPC_BTFN },
  110. # endif // USE_MSRPC
  111. # ifndef NO_PID_FILE
  112. { "PIDFile", INI_PARAM_PID_FILE },
  113. # endif // NO_PID_FILE
  114. # ifndef NO_LOG
  115. { "LogDateAndTime", INI_PARAM_LOG_DATE_AND_TIME },
  116. { "LogFile", INI_PARAM_LOG_FILE },
  117. # ifndef NO_VERBOSE_LOG
  118. { "LogVerbose", INI_PARAM_LOG_VERBOSE },
  119. # endif // NO_VERBOSE_LOG
  120. # endif // NO_LOG
  121. # ifndef NO_CUSTOM_INTERVALS
  122. {"ActivationInterval", INI_PARAM_ACTIVATION_INTERVAL },
  123. {"RenewalInterval", INI_PARAM_RENEWAL_INTERVAL },
  124. # endif // NO_CUSTOM_INTERVALS
  125. # if !defined(NO_USER_SWITCH) && !defined(_WIN32)
  126. { "user", INI_PARAM_UID },
  127. { "group", INI_PARAM_GID},
  128. # endif // !defined(NO_USER_SWITCH) && !defined(_WIN32)
  129. # if !defined(NO_PRIVATE_IP_DETECT)
  130. {"PublicIPProtectionLevel", INI_PARAM_PUBLIC_IP_PROTECTION_LEVEL },
  131. # endif
  132. };
  133. #endif // NO_INI_FILE
  134. #if !defined(NO_LIMIT) && !defined (NO_SOCKETS) && !__minix__
  135. #if !defined(USE_THREADS) && !defined(CYGWIN) && !defined(USE_MSRPC)
  136. static int shmid = -1;
  137. #endif
  138. #if __ANDROID__ && !defined(USE_THREADS) // Bionic does not wrap these syscalls (willingly because Google fears, developers don't know how to use it)
  139. #ifdef __NR_shmget
  140. static int shmget(key_t key, size_t size, int shmflg)
  141. {
  142. return syscall(__NR_shmget, key, size, shmflg);
  143. }
  144. #endif // __NR_shmget
  145. #ifdef __NR_shmat
  146. static void *shmat(int shmid, const void *shmaddr, int shmflg)
  147. {
  148. return (void *)syscall(__NR_shmat, shmid, shmaddr, shmflg);
  149. }
  150. #endif // __NR_shmat
  151. #ifdef __NR_shmdt
  152. static int shmdt(const void *shmaddr)
  153. {
  154. return syscall(__NR_shmdt, shmaddr);
  155. }
  156. #endif // __NR_shmdt
  157. #ifdef __NR_shmctl
  158. static int shmctl(int shmid, int cmd, /*struct shmid_ds*/void *buf)
  159. {
  160. return syscall(__NR_shmctl, shmid, cmd, buf);
  161. }
  162. #endif // __NR_shmctl
  163. #endif // __ANDROID__ && !defined(USE_THREADS)
  164. #endif // !defined(NO_LIMIT) && !defined (NO_SOCKETS) && !__minix__
  165. #ifndef NO_USER_SWITCH
  166. #ifndef _WIN32
  167. static const char *uname = NULL, *gname = NULL;
  168. static gid_t gid = INVALID_GID;
  169. static uid_t uid = INVALID_UID;
  170. // Get Numeric id of user/group
  171. static char GetNumericId(gid_t *restrict id, const char *const c)
  172. {
  173. char* endptr;
  174. gid_t temp;
  175. temp = (gid_t)strtoll(c, &endptr, 10);
  176. if (!*endptr) *id = temp;
  177. if (*endptr || temp == (gid_t)-1) errno = EINVAL;
  178. return *endptr || *id == (gid_t)-1;
  179. }
  180. // Get group id from option argument
  181. static char GetGid()
  182. {
  183. struct group *g;
  184. if ((g = getgrnam(optarg)))
  185. gid = g->gr_gid;
  186. else
  187. return GetNumericId(&gid, optarg);
  188. return 0;
  189. }
  190. // Get user id from option argument
  191. static char GetUid()
  192. {
  193. struct passwd *u;
  194. ////PORTABILITY: Assumes uid_t and gid_t are of same size (shouldn't be a problem)
  195. if ((u = getpwnam(optarg)))
  196. uid = u->pw_uid;
  197. else
  198. return GetNumericId((gid_t*)&uid, optarg);
  199. return 0;
  200. }
  201. #endif // _WIN32
  202. #endif //NO_USER_SWITCH
  203. #ifdef NO_HELP
  204. static __noreturn void usage()
  205. {
  206. printerrorf("Incorrect parameters\n\n");
  207. exit(!0);
  208. }
  209. #else // HELP
  210. static __noreturn void usage()
  211. {
  212. printerrorf("vlmcsd %s\n"
  213. "\nUsage:\n"
  214. " %s [ options ]\n\n"
  215. "Where:\n"
  216. #ifndef NO_CL_PIDS
  217. " -w <ePID> always use <ePID> for Windows\n"
  218. " -0 <ePID> always use <ePID> for Office2010\n"
  219. " -3 <ePID> always use <ePID> for Office2013\n"
  220. " -H <HwId> always use hardware Id <HwId>\n"
  221. #endif // NO_CL_PIDS
  222. #if !defined(_WIN32) && !defined(NO_USER_SWITCH)
  223. " -u <user> set uid to <user>\n"
  224. " -g <group> set gid to <group>\n"
  225. #endif // !defined(_WIN32) && !defined(NO_USER_SWITCH)
  226. #ifndef NO_RANDOM_EPID
  227. " -r 0|1|2\t\tset ePID randomization level (default 1)\n"
  228. " -C <LCID>\t\tuse fixed <LCID> in random ePIDs\n"
  229. #endif // NO_RANDOM_EPID
  230. #if !defined(NO_PRIVATE_IP_DETECT)
  231. #if HAVE_GETIFADDR
  232. " -o 0|1|2|3\t\tset protection level against clients with public IP addresses (default 0)\n"
  233. #else // !HAVE_GETIFADDR
  234. " -o 0|2\t\tset protection level against clients with public IP addresses (default 0)\n"
  235. #endif // !HAVE_GETIFADDR
  236. #endif // !defined(NO_PRIVATE_IP_DETECT)
  237. #ifndef NO_SOCKETS
  238. #if !defined(USE_MSRPC) && !defined(SIMPLE_SOCKETS)
  239. " -L <address>[:<port>]\tlisten on IP address <address> with optional <port>\n"
  240. " -P <port>\t\tset TCP port <port> for subsequent -L statements (default 1688)\n"
  241. #if HAVE_FREEBIND
  242. " -F0, -F1\t\tdisable/enable binding to foreign IP addresses\n"
  243. #endif // HAVE_FREEBIND
  244. #else // defined(USE_MSRPC) || defined(SIMPLE_SOCKETS)
  245. " -P <port>\t\tuse TCP port <port> (default 1688)\n"
  246. #endif // defined(USE_MSRPC) || defined(SIMPLE_SOCKETS)
  247. #if !defined(NO_LIMIT) && !__minix__
  248. " -m <clients>\t\tHandle max. <clients> simultaneously (default no limit)\n"
  249. #endif // !defined(NO_LIMIT) && !__minix__
  250. #ifdef _NTSERVICE
  251. " -s install vlmcsd as an NT service. Ignores -e"
  252. #ifndef _WIN32
  253. ", -f and -D"
  254. #endif // _WIN32
  255. "\n"
  256. " -S remove vlmcsd service. Ignores all other options\n"
  257. " -U <username> run NT service as <username>. Must be used with -s\n"
  258. " -W <password> optional <password> for -U. Must be used with -s\n"
  259. #endif // _NTSERVICE
  260. #ifndef NO_LOG
  261. " -e log to stdout\n"
  262. #endif // NO_LOG
  263. #ifndef _WIN32 //
  264. " -D run in foreground\n"
  265. #else // _WIN32
  266. " -D does nothing. Provided for compatibility with POSIX versions only\n"
  267. #endif // _WIN32
  268. #endif // NO_SOCKETS
  269. #ifndef USE_MSRPC
  270. #if !defined(NO_TIMEOUT) && !__minix__
  271. " -t <seconds>\t\tdisconnect clients after <seconds> of inactivity (default 30)\n"
  272. #endif // !defined(NO_TIMEOUT) && !__minix__
  273. " -d\t\t\tdisconnect clients after each request\n"
  274. " -k\t\t\tdon't disconnect clients after each request (default)\n"
  275. " -N0, -N1\t\tdisable/enable NDR64\n"
  276. " -B0, -B1\t\tdisable/enable bind time feature negotiation\n"
  277. #endif // USE_MSRPC
  278. #ifndef NO_PID_FILE
  279. " -p <file> write pid to <file>\n"
  280. #endif // NO_PID_FILE
  281. #ifndef NO_INI_FILE
  282. " -i <file>\t\tuse config file <file>\n"
  283. #endif // NO_INI_FILE
  284. #ifndef NO_CUSTOM_INTERVALS
  285. " -R <interval> renew activation every <interval> (default 1w)\n"
  286. " -A <interval> retry activation every <interval> (default 2h)\n"
  287. #endif // NO_CUSTOM_INTERVALS
  288. #ifndef NO_LOG
  289. #ifndef _WIN32
  290. " -l syslog log to syslog\n"
  291. #endif // _WIN32
  292. " -l <file> log to <file>\n"
  293. " -T0, -T1\t\tdisable/enable logging with time and date (default -T1)\n"
  294. #ifndef NO_VERBOSE_LOG
  295. " -v\t\t\tlog verbose\n"
  296. " -q\t\t\tdon't log verbose (default)\n"
  297. #endif // NO_VERBOSE_LOG
  298. #endif // NO_LOG
  299. #ifndef NO_VERSION_INFORMATION
  300. " -V display version information and exit\n"
  301. #endif // NO_VERSION_INFORMATION
  302. ,
  303. Version, global_argv[0]);
  304. exit(!0);
  305. }
  306. #endif // HELP
  307. #ifndef NO_CUSTOM_INTERVALS
  308. // Convert time span strings (e.g. "2h", "5w") to minutes
  309. __pure static DWORD timeSpanString2Minutes(const char *const restrict argument)
  310. {
  311. char *unitId;
  312. long long val = strtoll(argument, &unitId, 10);
  313. switch(toupper((int)*unitId))
  314. {
  315. case 0:
  316. case 'M':
  317. break;
  318. case 'H':
  319. val *= 60;
  320. break;
  321. case 'D':
  322. val *= 60 * 24;
  323. break;
  324. case 'W':
  325. val *= 60 * 24 * 7;
  326. break;
  327. case 'S':
  328. val /= 60;
  329. break;
  330. default:
  331. return 0;
  332. }
  333. if (val < 1) val = 1;
  334. if (val > UINT_MAX) val = UINT_MAX;
  335. return (DWORD)val;
  336. }
  337. #ifndef NO_INI_FILE
  338. __pure static BOOL getTimeSpanFromIniFile(DWORD* result, const char *const restrict argument)
  339. {
  340. DWORD val = timeSpanString2Minutes(argument);
  341. if (!val)
  342. {
  343. IniFileErrorMessage = "Incorrect time span.";
  344. return FALSE;
  345. }
  346. *result = val;
  347. return TRUE;
  348. }
  349. #endif // NO_INI_FILE
  350. __pure static DWORD getTimeSpanFromCommandLine(const char *const restrict optarg, const char optchar)
  351. {
  352. long long val = timeSpanString2Minutes(optarg);
  353. if (!val)
  354. {
  355. printerrorf("Fatal: No valid time span specified in option -%c.\n", optchar);
  356. exit (!0);
  357. }
  358. return (DWORD)val;
  359. }
  360. #endif // NO_CUSTOM_INTERVALS
  361. #ifndef NO_INI_FILE
  362. static void ignoreIniFileParameter(uint_fast8_t iniFileParameterId)
  363. {
  364. uint_fast8_t i;
  365. for (i = 0; i < _countof(IniFileParameterList); i++)
  366. {
  367. if (IniFileParameterList[i].Id != iniFileParameterId) continue;
  368. IniFileParameterList[i].Id = 0;
  369. break;
  370. }
  371. }
  372. #else // NO_INI_FILE
  373. #define ignoreIniFileParameter(x)
  374. #endif // NO_INI_FILE
  375. #ifndef NO_INI_FILE
  376. static BOOL getIniFileArgumentBool(int_fast8_t *result, const char *const argument)
  377. {
  378. IniFileErrorMessage = "Argument must be true/on/yes/1 or false/off/no/0";
  379. return getArgumentBool(result, argument);
  380. }
  381. static BOOL getIniFileArgumentInt(unsigned int *result, const char *const argument, const unsigned int min, const unsigned int max)
  382. {
  383. unsigned int tempResult;
  384. if (!stringToInt(argument, min, max, &tempResult))
  385. {
  386. snprintf(IniFileErrorBuffer, INIFILE_ERROR_BUFFERSIZE, "Must be integer between %u and %u", min, max);
  387. IniFileErrorMessage = IniFileErrorBuffer;
  388. return FALSE;
  389. }
  390. *result = tempResult;
  391. return TRUE;
  392. }
  393. static char* allocateStringArgument(const char *const argument)
  394. {
  395. char* result = (char*)vlmcsd_malloc(strlen(argument) + 1);
  396. strcpy(result, argument);
  397. return result;
  398. }
  399. static BOOL setIniFileParameter(uint_fast8_t id, const char *const iniarg)
  400. {
  401. unsigned int result;
  402. BOOL success = TRUE;
  403. switch(id)
  404. {
  405. # if !defined(NO_USER_SWITCH) && !defined(_WIN32)
  406. case INI_PARAM_GID:
  407. {
  408. struct group *g;
  409. IniFileErrorMessage = "Invalid group id or name";
  410. if (!(gname = allocateStringArgument(iniarg))) return FALSE;
  411. if ((g = getgrnam(iniarg)))
  412. gid = g->gr_gid;
  413. else
  414. success = !GetNumericId(&gid, iniarg);
  415. break;
  416. }
  417. case INI_PARAM_UID:
  418. {
  419. struct passwd *p;
  420. IniFileErrorMessage = "Invalid user id or name";
  421. if (!(uname = allocateStringArgument(iniarg))) return FALSE;
  422. if ((p = getpwnam(iniarg)))
  423. uid = p->pw_uid;
  424. else
  425. success = !GetNumericId(&uid, iniarg);
  426. break;
  427. }
  428. # endif // !defined(NO_USER_SWITCH) && !defined(_WIN32)
  429. # ifndef NO_RANDOM_EPID
  430. case INI_PARAM_LCID:
  431. success = getIniFileArgumentInt(&result, iniarg, 0, 32767);
  432. if (success) Lcid = (uint16_t)result;
  433. break;
  434. case INI_PARAM_RANDOMIZATION_LEVEL:
  435. success = getIniFileArgumentInt(&result, iniarg, 0, 2);
  436. if (success) RandomizationLevel = (int_fast8_t)result;
  437. break;
  438. # endif // NO_RANDOM_EPID
  439. # if (defined(USE_MSRPC) || defined(SIMPLE_SOCKETS) || defined(HAVE_GETIFADDR)) && !defined(NO_SOCKETS)
  440. case INI_PARAM_PORT:
  441. defaultport = allocateStringArgument(iniarg);
  442. break;
  443. # endif // (defined(USE_MSRPC) || defined(SIMPLE_SOCKETS) || defined(HAVE_GETIFADDR)) && !defined(NO_SOCKETS)
  444. # if !defined(NO_SOCKETS) && !defined(USE_MSRPC) && !defined(SIMPLE_SOCKETS)
  445. case INI_PARAM_LISTEN:
  446. maxsockets++;
  447. return TRUE;
  448. # endif // !defined(NO_SOCKETS) && !defined(USE_MSRPC) && !defined(SIMPLE_SOCKETS)
  449. # if !defined(NO_LIMIT) && !defined(NO_SOCKETS) && !__minix__
  450. case INI_PARAM_MAX_WORKERS:
  451. # ifdef USE_MSRPC
  452. success = getIniFileArgumentInt(&MaxTasks, iniarg, 1, RPC_C_LISTEN_MAX_CALLS_DEFAULT);
  453. # else // !USE_MSRPC
  454. success = getIniFileArgumentInt(&MaxTasks, iniarg, 1, SEM_VALUE_MAX);
  455. # endif // !USE_MSRPC
  456. break;
  457. # endif // !defined(NO_LIMIT) && !defined(NO_SOCKETS) && !__minix__
  458. # ifndef NO_PID_FILE
  459. case INI_PARAM_PID_FILE:
  460. fn_pid = allocateStringArgument(iniarg);
  461. break;
  462. # endif // NO_PID_FILE
  463. # ifndef NO_LOG
  464. case INI_PARAM_LOG_FILE:
  465. fn_log = allocateStringArgument(iniarg);
  466. break;
  467. case INI_PARAM_LOG_DATE_AND_TIME:
  468. success = getIniFileArgumentBool(&LogDateAndTime, iniarg);
  469. break;
  470. # ifndef NO_VERBOSE_LOG
  471. case INI_PARAM_LOG_VERBOSE:
  472. success = getIniFileArgumentBool(&logverbose, iniarg);
  473. break;
  474. # endif // NO_VERBOSE_LOG
  475. # endif // NO_LOG
  476. # ifndef NO_CUSTOM_INTERVALS
  477. case INI_PARAM_ACTIVATION_INTERVAL:
  478. success = getTimeSpanFromIniFile(&VLActivationInterval, iniarg);
  479. break;
  480. case INI_PARAM_RENEWAL_INTERVAL:
  481. success = getTimeSpanFromIniFile(&VLRenewalInterval, iniarg);
  482. break;
  483. # endif // NO_CUSTOM_INTERVALS
  484. # ifndef USE_MSRPC
  485. # if !defined(NO_TIMEOUT) && !__minix__
  486. case INI_PARAM_CONNECTION_TIMEOUT:
  487. success = getIniFileArgumentInt(&result, iniarg, 1, 600);
  488. if (success) ServerTimeout = (DWORD)result;
  489. break;
  490. # endif // !defined(NO_TIMEOUT) && !__minix__
  491. case INI_PARAM_DISCONNECT_IMMEDIATELY:
  492. success = getIniFileArgumentBool(&DisconnectImmediately, iniarg);
  493. break;
  494. case INI_PARAM_RPC_NDR64:
  495. success = getIniFileArgumentBool(&UseRpcNDR64, iniarg);
  496. break;
  497. case INI_PARAM_RPC_BTFN:
  498. success = getIniFileArgumentBool(&UseRpcBTFN, iniarg);
  499. break;
  500. # endif // USE_MSRPC
  501. # if HAVE_FREEBIND
  502. case INI_PARAM_FREEBIND:
  503. success = getIniFileArgumentBool(&freebind, iniarg);
  504. break;
  505. # endif // HAVE_FREEBIND
  506. # if !defined(NO_PRIVATE_IP_DETECT)
  507. case INI_PARAM_PUBLIC_IP_PROTECTION_LEVEL:
  508. success = getIniFileArgumentInt(&PublicIPProtectionLevel, iniarg, 0, 3);
  509. # if !HAVE_GETIFADDR
  510. if (PublicIPProtectionLevel & 1)
  511. {
  512. IniFileErrorMessage = "Must be 0 or 2";
  513. success = FALSE;
  514. }
  515. # endif // !HAVE_GETIFADDR
  516. break;
  517. # endif // !defined(NO_PRIVATE_IP_DETECT)
  518. default:
  519. return FALSE;
  520. }
  521. return success;
  522. }
  523. static __pure int isControlCharOrSlash(const char c)
  524. {
  525. if ((unsigned char)c < '!') return !0;
  526. if (c == '/') return !0;
  527. return 0;
  528. }
  529. static void iniFileLineNextWord(const char **s)
  530. {
  531. while ( **s && isspace((int)**s) ) (*s)++;
  532. }
  533. static BOOL setHwIdFromIniFileLine(const char **s, const ProdListIndex_t index)
  534. {
  535. iniFileLineNextWord(s);
  536. if (**s == '/')
  537. {
  538. if (KmsResponseParameters[index].HwId) return TRUE;
  539. BYTE* HwId = (BYTE*)vlmcsd_malloc(sizeof(((RESPONSE_V6 *)0)->HwId));
  540. hex2bin(HwId, *s + 1, sizeof(((RESPONSE_V6 *)0)->HwId));
  541. KmsResponseParameters[index].HwId = HwId;
  542. }
  543. return TRUE;
  544. }
  545. static BOOL checkGuidInIniFileLine(const char **s, ProdListIndex_t *const index)
  546. {
  547. GUID AppGuid;
  548. if (!string2Uuid(*s, &AppGuid)) return FALSE;
  549. (*s) += GUID_STRING_LENGTH;
  550. getProductNameHE(&AppGuid, AppList, index);
  551. if (*index > getAppListSize() - 2)
  552. {
  553. IniFileErrorMessage = "Unknown App Guid.";
  554. return FALSE;
  555. }
  556. iniFileLineNextWord(s);
  557. if ( *(*s)++ != '=' ) return FALSE;
  558. return TRUE;
  559. }
  560. static BOOL setEpidFromIniFileLine(const char **s, const ProdListIndex_t index)
  561. {
  562. iniFileLineNextWord(s);
  563. const char *savedPosition = *s;
  564. uint_fast16_t i;
  565. for (i = 0; !isControlCharOrSlash(**s); i++)
  566. {
  567. if (utf8_to_ucs2_char((const unsigned char*)*s, (const unsigned char**)s) == (WCHAR)~0)
  568. {
  569. return FALSE;
  570. }
  571. }
  572. if (i < 1 || i >= PID_BUFFER_SIZE) return FALSE;
  573. if (KmsResponseParameters[index].Epid) return TRUE;
  574. size_t size = *s - savedPosition + 1;
  575. char* epidbuffer = (char*)vlmcsd_malloc(size);
  576. memcpy(epidbuffer, savedPosition, size - 1);
  577. epidbuffer[size - 1] = 0;
  578. KmsResponseParameters[index].Epid = epidbuffer;
  579. #ifndef NO_LOG
  580. KmsResponseParameters[index].EpidSource = fn_ini;
  581. #endif //NO_LOG
  582. return TRUE;
  583. }
  584. static BOOL getIniFileArgument(const char **s)
  585. {
  586. while (!isspace((int)**s) && **s != '=' && **s) (*s)++;
  587. iniFileLineNextWord(s);
  588. if (*((*s)++) != '=')
  589. {
  590. IniFileErrorMessage = "'=' required after keyword.";
  591. return FALSE;
  592. }
  593. iniFileLineNextWord(s);
  594. if (!**s)
  595. {
  596. IniFileErrorMessage = "missing argument after '='.";
  597. return FALSE;
  598. }
  599. return TRUE;
  600. }
  601. static BOOL handleIniFileParameter(const char *s)
  602. {
  603. uint_fast8_t i;
  604. for (i = 0; i < _countof(IniFileParameterList); i++)
  605. {
  606. if (strncasecmp(IniFileParameterList[i].Name, s, strlen(IniFileParameterList[i].Name))) continue;
  607. if (!IniFileParameterList[i].Id) return TRUE;
  608. if (!getIniFileArgument(&s)) return FALSE;
  609. return setIniFileParameter(IniFileParameterList[i].Id, s);
  610. }
  611. IniFileErrorMessage = "Unknown keyword.";
  612. return FALSE;
  613. }
  614. #if !defined(NO_SOCKETS) && !defined(SIMPLE_SOCKETS) && !defined(USE_MSRPC)
  615. static BOOL setupListeningSocketsFromIniFile(const char *s)
  616. {
  617. if (!maxsockets) return TRUE;
  618. if (strncasecmp("Listen", s, 6)) return TRUE;
  619. if (!getIniFileArgument(&s)) return TRUE;
  620. snprintf(IniFileErrorBuffer, INIFILE_ERROR_BUFFERSIZE, "Cannot listen on %s.", s);
  621. IniFileErrorMessage = IniFileErrorBuffer;
  622. return addListeningSocket(s);
  623. }
  624. #endif // !defined(NO_SOCKETS) && !defined(SIMPLE_SOCKETS) && !defined(USE_MSRPC)
  625. static BOOL readIniFile(const uint_fast8_t pass)
  626. {
  627. char line[256];
  628. const char *s;
  629. ProdListIndex_t appIndex;
  630. unsigned int lineNumber;
  631. uint_fast8_t lineParseError;
  632. FILE *restrict f;
  633. BOOL result = TRUE;
  634. IniFileErrorBuffer = (char*)vlmcsd_malloc(INIFILE_ERROR_BUFFERSIZE);
  635. if ( !(f = fopen(fn_ini, "r") )) return FALSE;
  636. for (lineNumber = 1; (s = fgets(line, sizeof(line), f)); lineNumber++)
  637. {
  638. line[strlen(line) - 1] = 0;
  639. iniFileLineNextWord(&s);
  640. if (*s == ';' || *s == '#' || !*s) continue;
  641. # ifndef NO_SOCKETS
  642. if (pass == INI_FILE_PASS_1)
  643. # endif // NO_SOCKETS
  644. {
  645. if (handleIniFileParameter(s)) continue;
  646. lineParseError = !checkGuidInIniFileLine(&s, &appIndex) ||
  647. !setEpidFromIniFileLine(&s, appIndex) ||
  648. !setHwIdFromIniFileLine(&s, appIndex);
  649. }
  650. # if !defined(NO_SOCKETS) && !defined(SIMPLE_SOCKETS) && !defined(USE_MSRPC)
  651. else if (pass == INI_FILE_PASS_2)
  652. {
  653. lineParseError = !setupListeningSocketsFromIniFile(s);
  654. }
  655. else
  656. {
  657. return FALSE;
  658. }
  659. # endif // !defined(NO_SOCKETS) && && !defined(SIMPLE_SOCKETS) && !defined(USE_MSRPC)
  660. if (lineParseError)
  661. {
  662. printerrorf("Warning: %s line %u: \"%s\". %s\n", fn_ini, lineNumber, line, IniFileErrorMessage);
  663. continue;
  664. }
  665. }
  666. if (ferror(f)) result = FALSE;
  667. free(IniFileErrorBuffer);
  668. fclose(f);
  669. # if !defined(NO_SOCKETS) && !defined(NO_LOG)
  670. if (pass == INI_FILE_PASS_1 && !InetdMode && result)
  671. {
  672. # ifdef _NTSERVICE
  673. if (!installService)
  674. # endif // _NTSERVICE
  675. logger("Read ini file %s\n", fn_ini);
  676. }
  677. # endif // !defined(NO_SOCKETS) && !defined(NO_LOG)
  678. return result;
  679. }
  680. #endif // NO_INI_FILE
  681. #if !defined(NO_SOCKETS)
  682. #if !defined(_WIN32)
  683. #if !defined(NO_SIGHUP)
  684. static void exec_self(char** argv)
  685. {
  686. # if __linux__ && defined(USE_AUXV)
  687. char *execname_ptr = (char*)getauxval(AT_EXECFN);
  688. if (execname_ptr) execv(execname_ptr, argv);
  689. # elif (__linux__ || __CYGWIN__) && !defined(NO_PROCFS)
  690. execv(realpath("/proc/self/exe", NULL), argv);
  691. # elif (__FreeBSD__) && !defined(NO_PROCFS)
  692. int mib[4];
  693. mib[0] = CTL_KERN;
  694. mib[1] = KERN_PROC;
  695. mib[2] = KERN_PROC_PATHNAME;
  696. mib[3] = -1;
  697. char path[PATH_MAX + 1];
  698. size_t cb = sizeof(path);
  699. if (!sysctl(mib, 4, path, &cb, NULL, 0)) execv(path, argv);
  700. # elif (__DragonFly__) && !defined(NO_PROCFS)
  701. execv(realpath("/proc/curproc/file", NULL), argv);
  702. # elif __NetBSD__ && !defined(NO_PROCFS)
  703. execv(realpath("/proc/curproc/exe", NULL), argv);
  704. # elif __sun__
  705. const char* exename = getexecname();
  706. if (exename) execv(exename, argv);
  707. # elif __APPLE__
  708. char path[PATH_MAX + 1];
  709. uint32_t size = sizeof(path);
  710. if (_NSGetExecutablePath(path, &size) == 0) execv(path, argv);
  711. # else
  712. execvp(argv[0], argv);
  713. # endif
  714. }
  715. static void HangupHandler(const int signal_unused)
  716. {
  717. int i;
  718. int_fast8_t daemonize_protection = TRUE;
  719. CARGV argv_in = multi_argv == NULL ? global_argv : multi_argv;
  720. int argc_in = multi_argc == 0 ? global_argc : multi_argc;
  721. const char** argv_out = (const char**)vlmcsd_malloc((argc_in + 2) * sizeof(char**));
  722. for (i = 0; i < argc_in; i++)
  723. {
  724. if (!strcmp(argv_in[i], "-Z")) daemonize_protection = FALSE;
  725. argv_out[i] = argv_in[i];
  726. }
  727. argv_out[argc_in] = argv_out[argc_in + 1] = NULL;
  728. if (daemonize_protection) argv_out[argc_in] = (char*) "-Z";
  729. exec_self((char**)argv_out);
  730. # ifndef NO_LOG
  731. logger("Fatal: Unable to restart on SIGHUP: %s\n", strerror(errno));
  732. # endif
  733. # ifndef NO_PID_FILE
  734. if (fn_pid) unlink(fn_pid);
  735. # endif // NO_PID_FILE
  736. exit(errno);
  737. }
  738. #endif // NO_SIGHUP
  739. static void terminationHandler(const int signal_unused)
  740. {
  741. cleanup();
  742. exit(0);
  743. }
  744. #if defined(CHILD_HANDLER) || __minix__
  745. static void childHandler(const int signal)
  746. {
  747. waitpid(-1, NULL, WNOHANG);
  748. }
  749. #endif // defined(CHILD_HANDLER) || __minix__
  750. static int daemonizeAndSetSignalAction()
  751. {
  752. struct sigaction sa;
  753. sigemptyset(&sa.sa_mask);
  754. # ifndef NO_LOG
  755. if ( !nodaemon) if (daemon(!0, logstdout))
  756. # else // NO_LOG
  757. if ( !nodaemon) if (daemon(!0, 0))
  758. # endif // NO_LOG
  759. {
  760. printerrorf("Fatal: Could not daemonize to background.\n");
  761. return(errno);
  762. }
  763. if (!InetdMode)
  764. {
  765. # ifndef USE_THREADS
  766. # if defined(CHILD_HANDLER) || __minix__
  767. sa.sa_handler = childHandler;
  768. # else // !(defined(CHILD_HANDLER) || __minix__)
  769. sa.sa_handler = SIG_IGN;
  770. # endif // !(defined(CHILD_HANDLER) || __minix__)
  771. sa.sa_flags = SA_NOCLDWAIT;
  772. if (sigaction(SIGCHLD, &sa, NULL))
  773. return(errno);
  774. # endif // !USE_THREADS
  775. sa.sa_handler = terminationHandler;
  776. sa.sa_flags = 0;
  777. sigaction(SIGINT, &sa, NULL);
  778. sigaction(SIGTERM, &sa, NULL);
  779. # ifndef NO_SIGHUP
  780. sa.sa_handler = HangupHandler;
  781. sa.sa_flags = SA_NODEFER;
  782. sigaction(SIGHUP, &sa, NULL);
  783. # endif // NO_SIGHUP
  784. }
  785. return 0;
  786. }
  787. #else // _WIN32
  788. static BOOL terminationHandler(const DWORD fdwCtrlType)
  789. {
  790. // What a lame substitute for Unix signal handling
  791. switch(fdwCtrlType)
  792. {
  793. case CTRL_C_EVENT:
  794. case CTRL_CLOSE_EVENT:
  795. case CTRL_BREAK_EVENT:
  796. case CTRL_LOGOFF_EVENT:
  797. case CTRL_SHUTDOWN_EVENT:
  798. cleanup();
  799. exit(0);
  800. default:
  801. return FALSE;
  802. }
  803. }
  804. static DWORD daemonizeAndSetSignalAction()
  805. {
  806. if(!SetConsoleCtrlHandler( (PHANDLER_ROUTINE) terminationHandler, TRUE ))
  807. {
  808. #ifndef NO_LOG
  809. DWORD rc = GetLastError();
  810. logger("Warning: Could not register Windows signal handler: Error %u\n", rc);
  811. #endif // NO_LOG
  812. }
  813. return ERROR_SUCCESS;
  814. }
  815. #endif // _WIN32
  816. #endif // !defined(NO_SOCKETS)
  817. // Workaround for Cygwin fork bug (only affects cygwin processes that are Windows services)
  818. // Best is to compile for Cygwin with threads. fork() is slow and unreliable on Cygwin
  819. #if !defined(NO_INI_FILE) || !defined(NO_LOG) || !defined(NO_CL_PIDS)
  820. __pure static char* getCommandLineArg(char *const restrict optarg)
  821. {
  822. #if !defined (__CYGWIN__) || defined(USE_THREADS) || defined(NO_SOCKETS)
  823. return optarg;
  824. #else
  825. if (!IsNTService) return optarg;
  826. return allocateStringArgument(optarg);
  827. #endif
  828. }
  829. #endif // !defined(NO_INI_FILE) || !defined(NO_LOG) || !defined(NO_CL_PIDS)
  830. static void parseGeneralArguments() {
  831. int o;
  832. #ifndef NO_CL_PIDS
  833. BYTE* HwId;
  834. #endif // NO_CL_PIDS
  835. for (opterr = 0; ( o = getopt(global_argc, (char* const*)global_argv, optstring) ) > 0; ) switch (o)
  836. {
  837. #if !defined(NO_SOCKETS) && !defined(NO_SIGHUP) && !defined(_WIN32)
  838. case 'Z':
  839. IsRestarted = TRUE;
  840. nodaemon = TRUE;
  841. break;
  842. #endif // !defined(NO_SOCKETS) && !defined(NO_SIGHUP) && !defined(_WIN32)
  843. #ifndef NO_CL_PIDS
  844. case 'w':
  845. KmsResponseParameters[APP_ID_WINDOWS].Epid = getCommandLineArg(optarg);
  846. #ifndef NO_LOG
  847. KmsResponseParameters[APP_ID_WINDOWS].EpidSource = "command line";
  848. #endif // NO_LOG
  849. break;
  850. case '0':
  851. KmsResponseParameters[APP_ID_OFFICE2010].Epid = getCommandLineArg(optarg);
  852. #ifndef NO_LOG
  853. KmsResponseParameters[APP_ID_OFFICE2010].EpidSource = "command line";
  854. #endif // NO_LOG
  855. break;
  856. case '3':
  857. KmsResponseParameters[APP_ID_OFFICE2013].Epid = getCommandLineArg(optarg);
  858. #ifndef NO_LOG
  859. KmsResponseParameters[APP_ID_OFFICE2013].EpidSource = "command line";
  860. #endif // NO_LOG
  861. break;
  862. case 'H':
  863. HwId = (BYTE*)vlmcsd_malloc(sizeof(((RESPONSE_V6 *)0)->HwId));
  864. hex2bin(HwId, optarg, sizeof(((RESPONSE_V6 *)0)->HwId));
  865. KmsResponseParameters[APP_ID_WINDOWS].HwId = HwId;
  866. KmsResponseParameters[APP_ID_OFFICE2010].HwId = HwId;
  867. KmsResponseParameters[APP_ID_OFFICE2013].HwId = HwId;
  868. break;
  869. #endif // NO_CL_PIDS
  870. #ifndef NO_SOCKETS
  871. case 'P':
  872. ignoreIniFileParameter(INI_PARAM_PORT);
  873. #if !defined(SIMPLE_SOCKETS) && !defined(USE_MSRPC)
  874. ignoreIniFileParameter(INI_PARAM_LISTEN);
  875. #else
  876. defaultport = optarg;
  877. #endif // !SIMPLE_SOCKETS
  878. break;
  879. #if !defined(NO_LIMIT) && !__minix__
  880. case 'm':
  881. #ifdef USE_MSRPC
  882. MaxTasks = getOptionArgumentInt(o, 1, RPC_C_LISTEN_MAX_CALLS_DEFAULT);
  883. #else // !USE_MSRPC
  884. MaxTasks = getOptionArgumentInt(o, 1, SEM_VALUE_MAX);
  885. #endif // !USE_MSRPC
  886. ignoreIniFileParameter(INI_PARAM_MAX_WORKERS);
  887. break;
  888. #endif // !defined(NO_LIMIT) && !__minix__
  889. #endif // NO_SOCKETS
  890. #if !defined(NO_TIMEOUT) && !__minix__ && !defined(USE_MSRPC)
  891. case 't':
  892. ServerTimeout = getOptionArgumentInt(o, 1, 600);
  893. ignoreIniFileParameter(INI_PARAM_CONNECTION_TIMEOUT);
  894. break;
  895. #endif // !defined(NO_TIMEOUT) && !__minix__ && !defined(USE_MSRPC)
  896. #ifndef NO_PID_FILE
  897. case 'p':
  898. fn_pid = getCommandLineArg(optarg);
  899. ignoreIniFileParameter(INI_PARAM_PID_FILE);
  900. break;
  901. #endif
  902. #ifndef NO_INI_FILE
  903. case 'i':
  904. fn_ini = getCommandLineArg(optarg);
  905. if (!strcmp(fn_ini, "-")) fn_ini = NULL;
  906. break;
  907. #endif
  908. #ifndef NO_LOG
  909. case 'T':
  910. if (!getArgumentBool(&LogDateAndTime, optarg)) usage();
  911. ignoreIniFileParameter(INI_PARAM_LOG_DATE_AND_TIME);
  912. break;
  913. case 'l':
  914. fn_log = getCommandLineArg(optarg);
  915. ignoreIniFileParameter(INI_PARAM_LOG_FILE);
  916. break;
  917. #ifndef NO_VERBOSE_LOG
  918. case 'v':
  919. case 'q':
  920. logverbose = o == 'v';
  921. ignoreIniFileParameter(INI_PARAM_LOG_VERBOSE);
  922. break;
  923. #endif // NO_VERBOSE_LOG
  924. #endif // NO_LOG
  925. #if !defined(NO_PRIVATE_IP_DETECT)
  926. case 'o':
  927. ignoreIniFileParameter(INI_PARAM_PUBLIC_IP_PROTECTION_LEVEL);
  928. PublicIPProtectionLevel = getOptionArgumentInt(o, 0, 3);
  929. #if !HAVE_GETIFADDR
  930. if (PublicIPProtectionLevel & 1) usage();
  931. #endif // !HAVE_GETIFADDR
  932. break;
  933. #endif // !defined(NO_PRIVATE_IP_DETECT)
  934. #ifndef NO_SOCKETS
  935. #if !defined(USE_MSRPC) && !defined(SIMPLE_SOCKETS)
  936. case 'L':
  937. maxsockets++;
  938. ignoreIniFileParameter(INI_PARAM_LISTEN);
  939. break;
  940. #if HAVE_FREEBIND
  941. case 'F':
  942. if (!getArgumentBool(&freebind, optarg)) usage();
  943. ignoreIniFileParameter(INI_PARAM_FREEBIND);
  944. break;
  945. #endif // HAVE_FREEBIND
  946. #endif // !defined(USE_MSRPC) && !defined(SIMPLE_SOCKETS)
  947. #ifdef _NTSERVICE
  948. case 'U':
  949. ServiceUser = optarg;
  950. break;
  951. case 'W':
  952. ServicePassword = optarg;
  953. break;
  954. case 's':
  955. #ifndef USE_MSRPC
  956. if (InetdMode) usage();
  957. #endif // USE_MSRPC
  958. if (!IsNTService) installService = 1; // Install
  959. break;
  960. case 'S':
  961. if (!IsNTService) installService = 2; // Remove
  962. break;
  963. #endif // _NTSERVICE
  964. case 'D':
  965. #ifndef _WIN32
  966. nodaemon = 1;
  967. #else // _WIN32
  968. #ifdef _PEDANTIC
  969. printerrorf("Warning: Option -D has no effect in the Windows version of vlmcsd.\n");
  970. #endif // _PEDANTIC
  971. #endif // _WIN32
  972. break;
  973. #ifndef NO_LOG
  974. case 'e':
  975. logstdout = 1;
  976. break;
  977. #endif // NO_LOG
  978. #endif // NO_SOCKETS
  979. #ifndef NO_RANDOM_EPID
  980. case 'r':
  981. RandomizationLevel = (int_fast8_t)getOptionArgumentInt(o, 0, 2);
  982. ignoreIniFileParameter(INI_PARAM_RANDOMIZATION_LEVEL);
  983. break;
  984. case 'C':
  985. Lcid = (uint16_t)getOptionArgumentInt(o, 0, 32767);
  986. ignoreIniFileParameter(INI_PARAM_LCID);
  987. #ifdef _PEDANTIC
  988. if (!IsValidLcid(Lcid))
  989. {
  990. printerrorf("Warning: %s is not a valid LCID.\n", optarg);
  991. }
  992. #endif // _PEDANTIC
  993. break;
  994. #endif // NO_RANDOM_PID
  995. #if !defined(NO_USER_SWITCH) && !defined(_WIN32)
  996. case 'g':
  997. gname = optarg;
  998. ignoreIniFileParameter(INI_PARAM_GID);
  999. #ifndef NO_SIGHUP
  1000. if (!IsRestarted)
  1001. #endif // NO_SIGHUP
  1002. if (GetGid())
  1003. {
  1004. printerrorf("Fatal: %s for %s failed: %s\n", "setgid", gname, strerror(errno));
  1005. exit(errno);
  1006. }
  1007. break;
  1008. case 'u':
  1009. uname = optarg;
  1010. ignoreIniFileParameter(INI_PARAM_UID);
  1011. #ifndef NO_SIGHUP
  1012. if (!IsRestarted)
  1013. #endif // NO_SIGHUP
  1014. if (GetUid())
  1015. {
  1016. printerrorf("Fatal: %s for %s failed: %s\n", "setuid", uname, strerror(errno));
  1017. exit(errno);
  1018. }
  1019. break;
  1020. #endif // NO_USER_SWITCH && !_WIN32
  1021. #ifndef NO_CUSTOM_INTERVALS
  1022. case 'R':
  1023. VLRenewalInterval = getTimeSpanFromCommandLine(optarg, o);
  1024. ignoreIniFileParameter(INI_PARAM_RENEWAL_INTERVAL);
  1025. break;
  1026. case 'A':
  1027. VLActivationInterval = getTimeSpanFromCommandLine(optarg, o);
  1028. ignoreIniFileParameter(INI_PARAM_ACTIVATION_INTERVAL);
  1029. break;
  1030. #endif
  1031. #ifndef USE_MSRPC
  1032. case 'd':
  1033. case 'k':
  1034. DisconnectImmediately = o == 'd';
  1035. ignoreIniFileParameter(INI_PARAM_DISCONNECT_IMMEDIATELY);
  1036. break;
  1037. case 'N':
  1038. if (!getArgumentBool(&UseRpcNDR64, optarg)) usage();
  1039. ignoreIniFileParameter(INI_PARAM_RPC_NDR64);
  1040. break;
  1041. case 'B':
  1042. if (!getArgumentBool(&UseRpcBTFN, optarg)) usage();
  1043. ignoreIniFileParameter(INI_PARAM_RPC_BTFN);
  1044. break;
  1045. #endif // !USE_MSRPC
  1046. #ifndef NO_VERSION_INFORMATION
  1047. case 'V':
  1048. #ifdef _NTSERVICE
  1049. if (IsNTService) break;
  1050. #endif
  1051. #if defined(__s390__) && !defined(__zarch__) && !defined(__s390x__)
  1052. printf("vlmcsd %s %i-bit\n", Version, sizeof(void*) == 4 ? 31 : (int)sizeof(void*) << 3);
  1053. #else
  1054. printf("vlmcsd %s %i-bit\n", Version, (int)sizeof(void*) << 3);
  1055. #endif // defined(__s390__) && !defined(__zarch__) && !defined(__s390x__)
  1056. printPlatform();
  1057. printCommonFlags();
  1058. printServerFlags();
  1059. exit(0);
  1060. #endif // NO_VERSION_INFORMATION
  1061. default:
  1062. usage();
  1063. }
  1064. // Do not allow non-option arguments
  1065. if (optind != global_argc)
  1066. usage();
  1067. #ifdef _NTSERVICE
  1068. // -U and -W must be used with -s
  1069. if ((ServiceUser || *ServicePassword) && installService != 1) usage();
  1070. #endif // _NTSERVICE
  1071. }
  1072. #ifndef NO_PID_FILE
  1073. static void writePidFile()
  1074. {
  1075. # ifndef NO_SIGHUP
  1076. if (IsRestarted) return;
  1077. # endif // NO_SIGHUP
  1078. if (fn_pid && !InetdMode)
  1079. {
  1080. FILE *_f = fopen(fn_pid, "w");
  1081. if ( _f )
  1082. {
  1083. fprintf(_f, "%u", (uint32_t)getpid());
  1084. fclose(_f);
  1085. }
  1086. #ifndef NO_LOG
  1087. else
  1088. {
  1089. logger("Warning: Cannot write pid file '%s'. %s.\n", fn_pid, strerror(errno));
  1090. }
  1091. #endif // NO_LOG
  1092. }
  1093. }
  1094. #else
  1095. #define writePidFile(x)
  1096. #endif // NO_PID_FILE
  1097. #if !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1098. void cleanup()
  1099. {
  1100. if (!InetdMode)
  1101. {
  1102. #ifndef NO_PID_FILE
  1103. if (fn_pid) unlink(fn_pid);
  1104. #endif // NO_PID_FILE
  1105. closeAllListeningSockets();
  1106. #if !defined(NO_LIMIT) && !defined(NO_SOCKETS) && !defined(_WIN32) && !__minix__
  1107. sem_unlink("/vlmcsd");
  1108. #if !defined(USE_THREADS) && !defined(CYGWIN)
  1109. if (shmid >= 0)
  1110. {
  1111. if (Semaphore != (sem_t*)-1) shmdt(Semaphore);
  1112. shmctl(shmid, IPC_RMID, NULL);
  1113. }
  1114. #endif // !defined(USE_THREADS) && !defined(CYGWIN)
  1115. #endif // !defined(NO_LIMIT) && !defined(NO_SOCKETS) && !defined(_WIN32) && !__minix__
  1116. #ifndef NO_LOG
  1117. logger("vlmcsd %s was shutdown\n", Version);
  1118. #endif // NO_LOG
  1119. }
  1120. }
  1121. #elif defined(USE_MSRPC)
  1122. void cleanup()
  1123. {
  1124. # ifndef NO_PID_FILE
  1125. if (fn_pid) unlink(fn_pid);
  1126. # endif // NO_PID_FILE
  1127. # ifndef NO_LOG
  1128. logger("vlmcsd %s was shutdown\n", Version);
  1129. # endif // NO_LOG
  1130. }
  1131. #else // Neither Sockets nor RPC
  1132. __pure void cleanup() {}
  1133. #endif // Neither Sockets nor RPC
  1134. #if !defined(USE_MSRPC) && !defined(NO_LIMIT) && !defined(NO_SOCKETS) && !__minix__
  1135. // Get a semaphore for limiting the maximum concurrent tasks
  1136. static void allocateSemaphore(void)
  1137. {
  1138. #ifdef USE_THREADS
  1139. #define sharemode 0
  1140. #else
  1141. #define sharemode 1
  1142. #endif
  1143. #ifndef _WIN32
  1144. sem_unlink("/vlmcsd");
  1145. #endif
  1146. if(MaxTasks < SEM_VALUE_MAX && !InetdMode)
  1147. {
  1148. #ifndef _WIN32
  1149. #if !defined(USE_THREADS) && !defined(CYGWIN)
  1150. if ((Semaphore = sem_open("/vlmcsd", O_CREAT /*| O_EXCL*/, 0700, MaxTasks)) == SEM_FAILED) // fails on many systems
  1151. {
  1152. // We didn't get a named Semaphore (/dev/shm on Linux) so let's try our own shared page
  1153. if (
  1154. ( shmid = shmget(IPC_PRIVATE, sizeof(sem_t), IPC_CREAT | 0600) ) < 0 ||
  1155. ( Semaphore = (sem_t*)shmat(shmid, NULL, 0) ) == (sem_t*)-1 ||
  1156. sem_init(Semaphore, 1, MaxTasks) < 0
  1157. )
  1158. {
  1159. int errno_save = errno;
  1160. if (Semaphore != (sem_t*)-1) shmdt(Semaphore);
  1161. if (shmid >= 0) shmctl(shmid, IPC_RMID, NULL);
  1162. printerrorf("Warning: Could not create semaphore: %s\n", vlmcsd_strerror(errno_save));
  1163. MaxTasks = SEM_VALUE_MAX;
  1164. }
  1165. }
  1166. #else // THREADS or CYGWIN
  1167. Semaphore = (sem_t*)vlmcsd_malloc(sizeof(sem_t));
  1168. if (sem_init(Semaphore, sharemode, MaxTasks) < 0) // sem_init is not implemented on Darwin (returns ENOSYS)
  1169. {
  1170. free(Semaphore);
  1171. if ((Semaphore = sem_open("/vlmcsd", O_CREAT /*| O_EXCL*/, 0700, MaxTasks)) == SEM_FAILED)
  1172. {
  1173. printerrorf("Warning: Could not create semaphore: %s\n", vlmcsd_strerror(errno));
  1174. MaxTasks = SEM_VALUE_MAX;
  1175. }
  1176. }
  1177. #endif // THREADS or CYGWIN
  1178. #else // _WIN32
  1179. if (!(Semaphore = CreateSemaphoreA(NULL, MaxTasks, MaxTasks, NULL)))
  1180. {
  1181. printerrorf("Warning: Could not create semaphore: %s\n", vlmcsd_strerror(GetLastError()));
  1182. MaxTasks = SEM_VALUE_MAX;
  1183. }
  1184. #endif // _WIN32
  1185. }
  1186. }
  1187. #endif // !defined(NO_LIMIT) && !defined(NO_SOCKETS) && !__minix__
  1188. #if !defined(NO_SOCKETS) && !defined(USE_MSRPC) && !defined(SIMPLE_SOCKETS)
  1189. int setupListeningSockets()
  1190. {
  1191. int o;
  1192. # if HAVE_GETIFADDR
  1193. char** privateIPList;
  1194. int numPrivateIPs = 0;
  1195. if (PublicIPProtectionLevel & 1) getPrivateIPAddresses(&numPrivateIPs, &privateIPList);
  1196. uint_fast8_t allocsockets = maxsockets ? (maxsockets + numPrivateIPs) : ((PublicIPProtectionLevel & 1) ? numPrivateIPs : 2);
  1197. # else // !HAVE_GETIFADDR
  1198. uint_fast8_t allocsockets = maxsockets ? maxsockets : 2;
  1199. # endif // !HAVE_GETIFADDR
  1200. SocketList = (SOCKET*)vlmcsd_malloc((size_t)allocsockets * sizeof(SOCKET));
  1201. int_fast8_t haveIPv4Stack = checkProtocolStack(AF_INET);
  1202. int_fast8_t haveIPv6Stack = checkProtocolStack(AF_INET6);
  1203. // Reset getopt since we've alread used it
  1204. optReset();
  1205. for (opterr = 0; ( o = getopt(global_argc, (char* const*)global_argv, optstring) ) > 0; ) switch (o)
  1206. {
  1207. case 'P':
  1208. defaultport = optarg;
  1209. break;
  1210. case 'L':
  1211. addListeningSocket(optarg);
  1212. break;
  1213. default:
  1214. break;
  1215. }
  1216. # ifndef NO_INI_FILE
  1217. if (maxsockets && !numsockets)
  1218. {
  1219. if (fn_ini && !readIniFile(INI_FILE_PASS_2))
  1220. {
  1221. #ifdef INI_FILE
  1222. if (strcmp(fn_ini, INI_FILE))
  1223. #endif // INI_FILE
  1224. printerrorf("Warning: Can't read %s: %s\n", fn_ini, strerror(errno));
  1225. }
  1226. }
  1227. # endif
  1228. # if HAVE_GETIFADDR
  1229. if (PublicIPProtectionLevel & 1)
  1230. {
  1231. int i;
  1232. for (i = 0; i < numPrivateIPs; i++)
  1233. {
  1234. addListeningSocket(privateIPList[i]);
  1235. free(privateIPList[i]);
  1236. }
  1237. free(privateIPList);
  1238. }
  1239. # endif // HAVE_GETIFADDR
  1240. // if -L hasn't been specified on the command line, use default sockets (all IP addresses)
  1241. // maxsocket results from first pass parsing the arguments
  1242. if (!maxsockets)
  1243. {
  1244. # if HAVE_GETIFADDR
  1245. if (!(PublicIPProtectionLevel & 1) && haveIPv6Stack) addListeningSocket("::");
  1246. if (!(PublicIPProtectionLevel & 1) && haveIPv4Stack) addListeningSocket("0.0.0.0");
  1247. # else // !HAVE_GETIFADDR
  1248. if (haveIPv6Stack) addListeningSocket("::");
  1249. if (haveIPv4Stack) addListeningSocket("0.0.0.0");
  1250. # endif // !HAVE_GETIFADDR
  1251. }
  1252. if (!numsockets)
  1253. {
  1254. printerrorf("Fatal: Could not listen on any socket.\n");
  1255. return(!0);
  1256. }
  1257. return 0;
  1258. }
  1259. #endif // !defined(NO_SOCKETS) && !defined(USE_MSRPC) && !defined(SIMPLE_SOCKETS)
  1260. int server_main(int argc, CARGV argv)
  1261. {
  1262. #if !defined(_NTSERVICE) && !defined(NO_SOCKETS)
  1263. int error;
  1264. #endif // !defined(_NTSERVICE) && !defined(NO_SOCKETS)
  1265. // Initialize ePID / HwId parameters
  1266. memset(KmsResponseParameters, 0, sizeof(KmsResponseParameters));
  1267. global_argc = argc;
  1268. global_argv = argv;
  1269. #ifdef _NTSERVICE // #endif is in newmain()
  1270. DWORD lasterror = ERROR_SUCCESS;
  1271. if (!StartServiceCtrlDispatcher(NTServiceDispatchTable) && (lasterror = GetLastError()) == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
  1272. {
  1273. IsNTService = FALSE;
  1274. return newmain();
  1275. }
  1276. return lasterror;
  1277. }
  1278. int newmain()
  1279. {
  1280. int error;
  1281. // Initialize thread synchronization objects for Windows and Cygwin
  1282. #ifdef USE_THREADS
  1283. #ifndef NO_LOG
  1284. // Initialize the Critical Section for proper logging
  1285. InitializeCriticalSection(&logmutex);
  1286. #endif // NO_LOG
  1287. #endif // USE_THREADS
  1288. #ifdef _WIN32
  1289. #ifndef USE_MSRPC
  1290. // Windows Sockets must be initialized
  1291. WSADATA wsadata;
  1292. if ((error = WSAStartup(0x0202, &wsadata)))
  1293. {
  1294. printerrorf("Fatal: Could not initialize Windows sockets (Error: %d).\n", error);
  1295. return error;
  1296. }
  1297. #endif // USE_MSRPC
  1298. // Windows can never daemonize
  1299. //nodaemon = 1;
  1300. #else // __CYGWIN__
  1301. // Do not daemonize if we are a Windows service
  1302. if (IsNTService) nodaemon = 1;
  1303. #endif // _WIN32 / __CYGWIN__
  1304. #endif // _NTSERVICE ( #ifdef is main(int argc, CARGV argv) )
  1305. parseGeneralArguments(); // Does not return if an error occurs
  1306. #if !defined(_WIN32) && !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1307. struct stat statbuf;
  1308. fstat(STDIN_FILENO, &statbuf);
  1309. if (S_ISSOCK(statbuf.st_mode))
  1310. {
  1311. InetdMode = 1;
  1312. nodaemon = 1;
  1313. #ifndef SIMPLE_SOCKETS
  1314. maxsockets = 0;
  1315. #endif // SIMPLE_SOCKETS
  1316. #ifndef NO_LOG
  1317. logstdout = 0;
  1318. #endif // NO_LOG
  1319. }
  1320. #endif // !defined(_WIN32) && !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1321. #ifndef NO_INI_FILE
  1322. if (fn_ini && !readIniFile(INI_FILE_PASS_1))
  1323. {
  1324. #ifdef INI_FILE
  1325. if (strcmp(fn_ini, INI_FILE))
  1326. #endif // INI_FILE
  1327. printerrorf("Warning: Can't read %s: %s\n", fn_ini, strerror(errno));
  1328. }
  1329. #endif // NO_INI_FILE
  1330. #if !defined(NO_LIMIT) && !defined(NO_SOCKETS) && !__minix__ && !defined(USE_MSRPC)
  1331. allocateSemaphore();
  1332. #endif // !defined(NO_LIMIT) && !defined(NO_SOCKETS) && __minix__
  1333. #ifdef _NTSERVICE
  1334. if (installService)
  1335. return NtServiceInstallation(installService, ServiceUser, ServicePassword);
  1336. #endif // _NTSERVICE
  1337. #if !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1338. if (!InetdMode)
  1339. {
  1340. #ifdef SIMPLE_SOCKETS
  1341. if ((error = listenOnAllAddresses())) return error;
  1342. #else // !SIMPLE_SOCKETS
  1343. if ((error = setupListeningSockets())) return error;
  1344. #endif // !SIMPLE_SOCKETS
  1345. }
  1346. #endif // !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1347. // After sockets have been set up, we may switch to a lower privileged user
  1348. #if !defined(_WIN32) && !defined(NO_USER_SWITCH)
  1349. #ifndef NO_SIGHUP
  1350. if (!IsRestarted)
  1351. {
  1352. #endif // NO_SIGHUP
  1353. if (gid != INVALID_GID)
  1354. {
  1355. if (setgid(gid))
  1356. {
  1357. printerrorf("Fatal: %s for %s failed: %s\n", "setgid", gname, strerror(errno));
  1358. return errno;
  1359. }
  1360. if (setgroups(1, &gid))
  1361. {
  1362. printerrorf("Fatal: %s for %s failed: %s\n", "setgroups", gname, strerror(errno));
  1363. return errno;
  1364. }
  1365. }
  1366. if (uid != INVALID_UID && setuid(uid))
  1367. {
  1368. printerrorf("Fatal: %s for %s failed: %s\n", "setuid", uname, strerror(errno));
  1369. return errno;
  1370. }
  1371. #ifndef NO_SIGHUP
  1372. }
  1373. #endif // NO_SIGHUP
  1374. #endif // !defined(_WIN32) && !defined(NO_USER_SWITCH)
  1375. randomNumberInit();
  1376. // Randomization Level 1 means generate ePIDs at startup and use them during
  1377. // the lifetime of the process. So we generate them now
  1378. #ifndef NO_RANDOM_EPID
  1379. if (RandomizationLevel == 1) randomPidInit();
  1380. #endif
  1381. #if !defined(NO_SOCKETS)
  1382. #ifdef _WIN32
  1383. if (!IsNTService)
  1384. #endif // _WIN32
  1385. if ((error = daemonizeAndSetSignalAction())) return error;
  1386. #endif // !defined(NO_SOCKETS)
  1387. writePidFile();
  1388. #if !defined(NO_LOG) && !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1389. if (!InetdMode)
  1390. logger("vlmcsd %s started successfully\n", Version);
  1391. #endif // !defined(NO_LOG) && !defined(NO_SOCKETS) && !defined(USE_MSRPC)
  1392. #if defined(_NTSERVICE) && !defined(USE_MSRPC)
  1393. if (IsNTService) ReportServiceStatus(SERVICE_RUNNING, NO_ERROR, 200);
  1394. #endif // defined(_NTSERVICE) && !defined(USE_MSRPC)
  1395. int rc;
  1396. rc = runServer();
  1397. // Clean up things and exit
  1398. #ifdef _NTSERVICE
  1399. if (!ServiceShutdown)
  1400. #endif
  1401. cleanup();
  1402. #ifdef _NTSERVICE
  1403. else
  1404. ReportServiceStatus(SERVICE_STOPPED, NO_ERROR, 0);
  1405. #endif
  1406. return rc;
  1407. }