vlmcsd.c 43 KB

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