utils.c 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185
  1. /*
  2. Copyright 1987, 1998 The Open Group
  3. Permission to use, copy, modify, distribute, and sell this software and its
  4. documentation for any purpose is hereby granted without fee, provided that
  5. the above copyright notice appear in all copies and that both that
  6. copyright notice and this permission notice appear in supporting
  7. documentation.
  8. The above copyright notice and this permission notice shall be included
  9. in all copies or substantial portions of the Software.
  10. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  13. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
  14. OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  15. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  16. OTHER DEALINGS IN THE SOFTWARE.
  17. Except as contained in this notice, the name of The Open Group shall
  18. not be used in advertising or otherwise to promote the sale, use or
  19. other dealings in this Software without prior written authorization
  20. from The Open Group.
  21. Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts,
  22. Copyright 1994 Quarterdeck Office Systems.
  23. All Rights Reserved
  24. Permission to use, copy, modify, and distribute this software and its
  25. documentation for any purpose and without fee is hereby granted,
  26. provided that the above copyright notice appear in all copies and that
  27. both that copyright notice and this permission notice appear in
  28. supporting documentation, and that the names of Digital and
  29. Quarterdeck not be used in advertising or publicity pertaining to
  30. distribution of the software without specific, written prior
  31. permission.
  32. DIGITAL AND QUARTERDECK DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
  33. SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  34. FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT
  35. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  36. OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  37. OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
  38. OR PERFORMANCE OF THIS SOFTWARE.
  39. */
  40. #ifdef HAVE_DIX_CONFIG_H
  41. #include <dix-config.h>
  42. #endif
  43. #ifdef __CYGWIN__
  44. #include <stdlib.h>
  45. #include <signal.h>
  46. /*
  47. Sigh... We really need a prototype for this to know it is stdcall,
  48. but #include-ing <windows.h> here is not a good idea...
  49. */
  50. __stdcall unsigned long GetTickCount(void);
  51. #endif
  52. #if defined(WIN32) && !defined(__CYGWIN__)
  53. #include <X11/Xwinsock.h>
  54. #endif
  55. #include <X11/Xos.h>
  56. #include <stdio.h>
  57. #include <time.h>
  58. #if !defined(WIN32) || !defined(__MINGW32__)
  59. #include <sys/time.h>
  60. #include <sys/resource.h>
  61. # define SMART_SCHEDULE_POSSIBLE
  62. #endif
  63. #include "misc.h"
  64. #include <X11/X.h>
  65. #define XSERV_t
  66. #define TRANS_SERVER
  67. #define TRANS_REOPEN
  68. #include <X11/Xtrans/Xtrans.h>
  69. #include "input.h"
  70. #include "dixfont.h"
  71. #include "osdep.h"
  72. #include "extension.h"
  73. #ifdef X_POSIX_C_SOURCE
  74. #define _POSIX_C_SOURCE X_POSIX_C_SOURCE
  75. #include <signal.h>
  76. #undef _POSIX_C_SOURCE
  77. #else
  78. #if defined(_POSIX_SOURCE)
  79. #include <signal.h>
  80. #else
  81. #define _POSIX_SOURCE
  82. #include <signal.h>
  83. #undef _POSIX_SOURCE
  84. #endif
  85. #endif
  86. #ifndef WIN32
  87. #include <sys/wait.h>
  88. #endif
  89. #if !defined(SYSV) && !defined(WIN32)
  90. #include <sys/resource.h>
  91. #endif
  92. #include <sys/stat.h>
  93. #include <ctype.h> /* for isspace */
  94. #include <stdarg.h>
  95. #include <stdlib.h> /* for malloc() */
  96. #if defined(TCPCONN) || defined(STREAMSCONN)
  97. #ifndef WIN32
  98. #include <netdb.h>
  99. #endif
  100. #endif
  101. #include "opaque.h"
  102. #include "dixstruct.h"
  103. #include "xkbsrv.h"
  104. #include "picture.h"
  105. Bool noTestExtensions;
  106. #ifdef COMPOSITE
  107. Bool noCompositeExtension = FALSE;
  108. #endif
  109. #ifdef DAMAGE
  110. Bool noDamageExtension = FALSE;
  111. #endif
  112. #ifdef DBE
  113. Bool noDbeExtension = FALSE;
  114. #endif
  115. #ifdef DPMSExtension
  116. Bool noDPMSExtension = FALSE;
  117. #endif
  118. #ifdef GLXEXT
  119. Bool noGlxExtension = FALSE;
  120. #endif
  121. #ifdef SCREENSAVER
  122. Bool noScreenSaverExtension = FALSE;
  123. #endif
  124. #ifdef MITSHM
  125. Bool noMITShmExtension = FALSE;
  126. #endif
  127. #ifdef RANDR
  128. Bool noRRExtension = FALSE;
  129. #endif
  130. Bool noRenderExtension = FALSE;
  131. #ifdef XCSECURITY
  132. Bool noSecurityExtension = FALSE;
  133. #endif
  134. #ifdef RES
  135. Bool noResExtension = FALSE;
  136. #endif
  137. #ifdef XF86BIGFONT
  138. Bool noXFree86BigfontExtension = FALSE;
  139. #endif
  140. #ifdef XFreeXDGA
  141. Bool noXFree86DGAExtension = FALSE;
  142. #endif
  143. #ifdef XF86DRI
  144. Bool noXFree86DRIExtension = FALSE;
  145. #endif
  146. #ifdef XF86VIDMODE
  147. Bool noXFree86VidModeExtension = FALSE;
  148. #endif
  149. Bool noXFixesExtension = FALSE;
  150. #ifdef PANORAMIX
  151. /* Xinerama is disabled by default unless enabled via +xinerama */
  152. Bool noPanoramiXExtension = TRUE;
  153. #endif
  154. #ifdef XSELINUX
  155. Bool noSELinuxExtension = FALSE;
  156. int selinuxEnforcingState = SELINUX_MODE_DEFAULT;
  157. #endif
  158. #ifdef XV
  159. Bool noXvExtension = FALSE;
  160. #endif
  161. #ifdef DRI2
  162. Bool noDRI2Extension = FALSE;
  163. #endif
  164. Bool noGEExtension = FALSE;
  165. #define X_INCLUDE_NETDB_H
  166. #include <X11/Xos_r.h>
  167. #include <errno.h>
  168. Bool CoreDump;
  169. Bool enableIndirectGLX = TRUE;
  170. #ifdef PANORAMIX
  171. Bool PanoramiXExtensionDisabledHack = FALSE;
  172. #endif
  173. int auditTrailLevel = 1;
  174. char *SeatId = NULL;
  175. sig_atomic_t inSignalContext = FALSE;
  176. #if defined(SVR4) || defined(__linux__) || defined(CSRG_BASED)
  177. #define HAS_SAVED_IDS_AND_SETEUID
  178. #endif
  179. OsSigHandlerPtr
  180. OsSignal(int sig, OsSigHandlerPtr handler)
  181. {
  182. #if defined(WIN32) && !defined(__CYGWIN__)
  183. return signal(sig, handler);
  184. #else
  185. struct sigaction act, oact;
  186. sigemptyset(&act.sa_mask);
  187. if (handler != SIG_IGN)
  188. sigaddset(&act.sa_mask, sig);
  189. act.sa_flags = 0;
  190. act.sa_handler = handler;
  191. if (sigaction(sig, &act, &oact))
  192. perror("sigaction");
  193. return oact.sa_handler;
  194. #endif
  195. }
  196. /*
  197. * Explicit support for a server lock file like the ones used for UUCP.
  198. * For architectures with virtual terminals that can run more than one
  199. * server at a time. This keeps the servers from stomping on each other
  200. * if the user forgets to give them different display numbers.
  201. */
  202. #define LOCK_DIR "/tmp"
  203. #define LOCK_TMP_PREFIX "/.tX"
  204. #define LOCK_PREFIX "/.X"
  205. #define LOCK_SUFFIX "-lock"
  206. #if !defined(WIN32) || defined(__CYGWIN__)
  207. #define LOCK_SERVER
  208. #endif
  209. #ifndef LOCK_SERVER
  210. void
  211. LockServer(void)
  212. {}
  213. void
  214. UnlockServer(void)
  215. {}
  216. #else /* LOCK_SERVER */
  217. static Bool StillLocking = FALSE;
  218. static char LockFile[PATH_MAX];
  219. static Bool nolock = FALSE;
  220. /*
  221. * LockServer --
  222. * Check if the server lock file exists. If so, check if the PID
  223. * contained inside is valid. If so, then die. Otherwise, create
  224. * the lock file containing the PID.
  225. */
  226. void
  227. LockServer(void)
  228. {
  229. char tmp[PATH_MAX], pid_str[12];
  230. int lfd, i, haslock, l_pid, t;
  231. const char *tmppath = LOCK_DIR;
  232. int len;
  233. char port[20];
  234. if (nolock || NoListenAll)
  235. return;
  236. /*
  237. * Path names
  238. */
  239. snprintf(port, sizeof(port), "%d", atoi(display));
  240. len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) :
  241. strlen(LOCK_TMP_PREFIX);
  242. len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1;
  243. if (len > sizeof(LockFile))
  244. FatalError("Display name `%s' is too long\n", port);
  245. (void) sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, port);
  246. (void) sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port);
  247. /*
  248. * Create a temporary file containing our PID. Attempt three times
  249. * to create the file.
  250. */
  251. StillLocking = TRUE;
  252. i = 0;
  253. do {
  254. i++;
  255. lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644);
  256. if (lfd < 0)
  257. sleep(2);
  258. else
  259. break;
  260. } while (i < 3);
  261. if (lfd < 0) {
  262. unlink(tmp);
  263. i = 0;
  264. do {
  265. i++;
  266. lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644);
  267. if (lfd < 0)
  268. sleep(2);
  269. else
  270. break;
  271. } while (i < 3);
  272. }
  273. if (lfd < 0)
  274. FatalError("Could not create lock file in %s\n", tmp);
  275. snprintf(pid_str, sizeof(pid_str), "%10ld\n", (long) getpid());
  276. if (write(lfd, pid_str, 11) != 11)
  277. FatalError("Could not write pid to lock file in %s\n", tmp);
  278. #ifdef __OpenBSD__
  279. /* if possible give away the lock file to the real uid/gid */
  280. fchown(lfd, getuid(), getgid());
  281. #endif
  282. (void) fchmod(lfd, 0444);
  283. (void) close(lfd);
  284. /*
  285. * OK. Now the tmp file exists. Try three times to move it in place
  286. * for the lock.
  287. */
  288. i = 0;
  289. haslock = 0;
  290. while ((!haslock) && (i++ < 3)) {
  291. haslock = (link(tmp, LockFile) == 0);
  292. if (haslock) {
  293. /*
  294. * We're done.
  295. */
  296. break;
  297. }
  298. else {
  299. /*
  300. * Read the pid from the existing file
  301. */
  302. lfd = open(LockFile, O_RDONLY | O_NOFOLLOW);
  303. if (lfd < 0) {
  304. unlink(tmp);
  305. FatalError("Can't read lock file %s\n", LockFile);
  306. }
  307. pid_str[0] = '\0';
  308. if (read(lfd, pid_str, 11) != 11) {
  309. /*
  310. * Bogus lock file.
  311. */
  312. unlink(LockFile);
  313. close(lfd);
  314. continue;
  315. }
  316. pid_str[11] = '\0';
  317. sscanf(pid_str, "%d", &l_pid);
  318. close(lfd);
  319. /*
  320. * Now try to kill the PID to see if it exists.
  321. */
  322. errno = 0;
  323. t = kill(l_pid, 0);
  324. if ((t < 0) && (errno == ESRCH)) {
  325. /*
  326. * Stale lock file.
  327. */
  328. unlink(LockFile);
  329. continue;
  330. }
  331. else if (((t < 0) && (errno == EPERM)) || (t == 0)) {
  332. /*
  333. * Process is still active.
  334. */
  335. unlink(tmp);
  336. FatalError
  337. ("Server is already active for display %s\n%s %s\n%s\n",
  338. port, "\tIf this server is no longer running, remove",
  339. LockFile, "\tand start again.");
  340. }
  341. }
  342. }
  343. unlink(tmp);
  344. if (!haslock)
  345. FatalError("Could not create server lock file: %s\n", LockFile);
  346. StillLocking = FALSE;
  347. }
  348. /*
  349. * UnlockServer --
  350. * Remove the server lock file.
  351. */
  352. void
  353. UnlockServer(void)
  354. {
  355. if (nolock || NoListenAll)
  356. return;
  357. if (!StillLocking) {
  358. (void) unlink(LockFile);
  359. }
  360. }
  361. #endif /* LOCK_SERVER */
  362. #ifdef X_PRIVSEP
  363. int
  364. ChownLock(uid_t uid, gid_t gid)
  365. {
  366. return chown(LockFile, uid, gid);
  367. }
  368. #endif
  369. /* Force connections to close on SIGHUP from init */
  370. void
  371. AutoResetServer(int sig)
  372. {
  373. int olderrno = errno;
  374. dispatchException |= DE_RESET;
  375. isItTimeToYield = TRUE;
  376. errno = olderrno;
  377. }
  378. /* Force connections to close and then exit on SIGTERM, SIGINT */
  379. void
  380. GiveUp(int sig)
  381. {
  382. int olderrno = errno;
  383. dispatchException |= DE_TERMINATE;
  384. isItTimeToYield = TRUE;
  385. errno = olderrno;
  386. }
  387. #if (defined WIN32 && defined __MINGW32__) || defined(__CYGWIN__)
  388. CARD32
  389. GetTimeInMillis(void)
  390. {
  391. return GetTickCount();
  392. }
  393. CARD64
  394. GetTimeInMicros(void)
  395. {
  396. return (CARD64) GetTickCount() * 1000;
  397. }
  398. #else
  399. CARD32
  400. GetTimeInMillis(void)
  401. {
  402. struct timeval tv;
  403. #ifdef MONOTONIC_CLOCK
  404. struct timespec tp;
  405. static clockid_t clockid;
  406. if (!clockid) {
  407. #ifdef CLOCK_MONOTONIC_COARSE
  408. if (clock_getres(CLOCK_MONOTONIC_COARSE, &tp) == 0 &&
  409. (tp.tv_nsec / 1000) <= 1000 &&
  410. clock_gettime(CLOCK_MONOTONIC_COARSE, &tp) == 0)
  411. clockid = CLOCK_MONOTONIC_COARSE;
  412. else
  413. #endif
  414. if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0)
  415. clockid = CLOCK_MONOTONIC;
  416. else
  417. clockid = ~0L;
  418. }
  419. if (clockid != ~0L && clock_gettime(clockid, &tp) == 0)
  420. return (tp.tv_sec * 1000) + (tp.tv_nsec / 1000000L);
  421. #endif
  422. X_GETTIMEOFDAY(&tv);
  423. return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
  424. }
  425. CARD64
  426. GetTimeInMicros(void)
  427. {
  428. struct timeval tv;
  429. #ifdef MONOTONIC_CLOCK
  430. struct timespec tp;
  431. static clockid_t clockid;
  432. if (!clockid) {
  433. if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0)
  434. clockid = CLOCK_MONOTONIC;
  435. else
  436. clockid = ~0L;
  437. }
  438. if (clockid != ~0L && clock_gettime(clockid, &tp) == 0)
  439. return (CARD64) tp.tv_sec * (CARD64)1000000 + tp.tv_nsec / 1000;
  440. #endif
  441. X_GETTIMEOFDAY(&tv);
  442. return (CARD64) tv.tv_sec * (CARD64)1000000000 + (CARD64) tv.tv_usec * 1000;
  443. }
  444. #endif
  445. void
  446. AdjustWaitForDelay(void *waitTime, unsigned long newdelay)
  447. {
  448. static struct timeval delay_val;
  449. struct timeval **wt = (struct timeval **) waitTime;
  450. unsigned long olddelay;
  451. if (*wt == NULL) {
  452. delay_val.tv_sec = newdelay / 1000;
  453. delay_val.tv_usec = 1000 * (newdelay % 1000);
  454. *wt = &delay_val;
  455. }
  456. else {
  457. olddelay = (*wt)->tv_sec * 1000 + (*wt)->tv_usec / 1000;
  458. if (newdelay < olddelay) {
  459. (*wt)->tv_sec = newdelay / 1000;
  460. (*wt)->tv_usec = 1000 * (newdelay % 1000);
  461. }
  462. }
  463. }
  464. void
  465. UseMsg(void)
  466. {
  467. ErrorF("use: X [:<display>] [option]\n");
  468. ErrorF("-a # default pointer acceleration (factor)\n");
  469. ErrorF("-ac disable access control restrictions\n");
  470. ErrorF("-audit int set audit trail level\n");
  471. ErrorF("-auth file select authorization file\n");
  472. ErrorF("-br create root window with black background\n");
  473. ErrorF("+bs enable any backing store support\n");
  474. ErrorF("-bs disable any backing store support\n");
  475. ErrorF("-c turns off key-click\n");
  476. ErrorF("c # key-click volume (0-100)\n");
  477. ErrorF("-cc int default color visual class\n");
  478. ErrorF("-nocursor disable the cursor\n");
  479. ErrorF("-core generate core dump on fatal error\n");
  480. ErrorF("-displayfd fd file descriptor to write display number to when ready to connect\n");
  481. ErrorF("-dpi int screen resolution in dots per inch\n");
  482. #ifdef DPMSExtension
  483. ErrorF("-dpms disables VESA DPMS monitor control\n");
  484. #endif
  485. ErrorF
  486. ("-deferglyphs [none|all|16] defer loading of [no|all|16-bit] glyphs\n");
  487. ErrorF("-f # bell base (0-100)\n");
  488. ErrorF("-fc string cursor font\n");
  489. ErrorF("-fn string default font name\n");
  490. ErrorF("-fp string default font path\n");
  491. ErrorF("-help prints message with these options\n");
  492. ErrorF("+iglx Allow creating indirect GLX contexts (default)\n");
  493. ErrorF("-iglx Prohibit creating indirect GLX contexts\n");
  494. ErrorF("-I ignore all remaining arguments\n");
  495. #ifdef RLIMIT_DATA
  496. ErrorF("-ld int limit data space to N Kb\n");
  497. #endif
  498. #ifdef RLIMIT_NOFILE
  499. ErrorF("-lf int limit number of open files to N\n");
  500. #endif
  501. #ifdef RLIMIT_STACK
  502. ErrorF("-ls int limit stack space to N Kb\n");
  503. #endif
  504. #ifdef LOCK_SERVER
  505. ErrorF("-nolock disable the locking mechanism\n");
  506. #endif
  507. ErrorF("-nolisten string don't listen on protocol\n");
  508. ErrorF("-listen string listen on protocol\n");
  509. ErrorF("-noreset don't reset after last client exists\n");
  510. ErrorF("-background [none] create root window with no background\n");
  511. ErrorF("-reset reset after last client exists\n");
  512. ErrorF("-p # screen-saver pattern duration (minutes)\n");
  513. ErrorF("-pn accept failure to listen on all ports\n");
  514. ErrorF("-nopn reject failure to listen on all ports\n");
  515. ErrorF("-r turns off auto-repeat\n");
  516. ErrorF("r turns on auto-repeat \n");
  517. ErrorF("-render [default|mono|gray|color] set render color alloc policy\n");
  518. #ifndef __OpenBSD__
  519. ErrorF("-retro start with classic stipple and cursor\n");
  520. #else
  521. ErrorF("-retard start with black background and no cursor\n");
  522. #endif
  523. ErrorF("-s # screen-saver timeout (minutes)\n");
  524. ErrorF("-seat string seat to run on\n");
  525. ErrorF("-t # default pointer threshold (pixels/t)\n");
  526. ErrorF("-terminate terminate at server reset\n");
  527. ErrorF("-to # connection time out\n");
  528. ErrorF("-tst disable testing extensions\n");
  529. ErrorF("ttyxx server started from init on /dev/ttyxx\n");
  530. ErrorF("v video blanking for screen-saver\n");
  531. ErrorF("-v screen-saver without video blanking\n");
  532. ErrorF("-wm WhenMapped default backing-store\n");
  533. ErrorF("-wr create root window with white background\n");
  534. ErrorF("-maxbigreqsize set maximal bigrequest size \n");
  535. #ifdef PANORAMIX
  536. ErrorF("+xinerama Enable XINERAMA extension\n");
  537. ErrorF("-xinerama Disable XINERAMA extension\n");
  538. #endif
  539. ErrorF
  540. ("-dumbSched Disable smart scheduling, enable old behavior\n");
  541. ErrorF("-schedInterval int Set scheduler interval in msec\n");
  542. ErrorF("-sigstop Enable SIGSTOP based startup\n");
  543. ErrorF("+extension name Enable extension\n");
  544. ErrorF("-extension name Disable extension\n");
  545. #ifdef XDMCP
  546. XdmcpUseMsg();
  547. #endif
  548. XkbUseMsg();
  549. ddxUseMsg();
  550. }
  551. /* This function performs a rudimentary sanity check
  552. * on the display name passed in on the command-line,
  553. * since this string is used to generate filenames.
  554. * It is especially important that the display name
  555. * not contain a "/" and not start with a "-".
  556. * --kvajk
  557. */
  558. static int
  559. VerifyDisplayName(const char *d)
  560. {
  561. int i;
  562. int period_found = FALSE;
  563. int after_period = 0;
  564. if (d == (char *) 0)
  565. return 0; /* null */
  566. if (*d == '\0')
  567. return 0; /* empty */
  568. if (*d == '-')
  569. return 0; /* could be confused for an option */
  570. if (*d == '.')
  571. return 0; /* must not equal "." or ".." */
  572. if (strchr(d, '/') != (char *) 0)
  573. return 0; /* very important!!! */
  574. /* Since we run atoi() on the display later, only allow
  575. for digits, or exception of :0.0 and similar (two decimal points max)
  576. */
  577. for (i = 0; i < strlen(d); i++) {
  578. if (!isdigit(d[i])) {
  579. if (d[i] != '.' || period_found)
  580. return 0;
  581. period_found = TRUE;
  582. } else if (period_found)
  583. after_period++;
  584. if (after_period > 2)
  585. return 0;
  586. }
  587. /* don't allow for :0. */
  588. if (period_found && after_period == 0)
  589. return 0;
  590. if (atol(d) > INT_MAX)
  591. return 0;
  592. return 1;
  593. }
  594. static const char *defaultNoListenList[] = {
  595. #ifndef LISTEN_TCP
  596. "tcp",
  597. #endif
  598. #ifndef LISTEN_UNIX
  599. "unix",
  600. #endif
  601. #ifndef LISTEN_LOCAL
  602. "local",
  603. #endif
  604. NULL
  605. };
  606. /*
  607. * This function parses the command line. Handles device-independent fields
  608. * and allows ddx to handle additional fields. It is not allowed to modify
  609. * argc or any of the strings pointed to by argv.
  610. */
  611. void
  612. ProcessCommandLine(int argc, char *argv[])
  613. {
  614. int i, skip;
  615. defaultKeyboardControl.autoRepeat = TRUE;
  616. #ifdef NO_PART_NET
  617. PartialNetwork = FALSE;
  618. #else
  619. PartialNetwork = TRUE;
  620. #endif
  621. for (i = 0; defaultNoListenList[i] != NULL; i++) {
  622. if (_XSERVTransNoListen(defaultNoListenList[i]))
  623. ErrorF("Failed to disable listen for %s transport",
  624. defaultNoListenList[i]);
  625. }
  626. for (i = 1; i < argc; i++) {
  627. /* call ddx first, so it can peek/override if it wants */
  628. if ((skip = ddxProcessArgument(argc, argv, i))) {
  629. i += (skip - 1);
  630. }
  631. else if (argv[i][0] == ':') {
  632. /* initialize display */
  633. display = argv[i];
  634. explicit_display = TRUE;
  635. display++;
  636. if (!VerifyDisplayName(display)) {
  637. ErrorF("Bad display name: %s\n", display);
  638. UseMsg();
  639. FatalError("Bad display name, exiting: %s\n", display);
  640. }
  641. }
  642. else if (strcmp(argv[i], "-a") == 0) {
  643. if (++i < argc)
  644. defaultPointerControl.num = atoi(argv[i]);
  645. else
  646. UseMsg();
  647. }
  648. else if (strcmp(argv[i], "-ac") == 0) {
  649. defeatAccessControl = TRUE;
  650. }
  651. else if (strcmp(argv[i], "-audit") == 0) {
  652. if (++i < argc)
  653. auditTrailLevel = atoi(argv[i]);
  654. else
  655. UseMsg();
  656. }
  657. else if (strcmp(argv[i], "-auth") == 0) {
  658. if (++i < argc)
  659. InitAuthorization(argv[i]);
  660. else
  661. UseMsg();
  662. }
  663. else if (strcmp(argv[i], "-br") == 0); /* default */
  664. else if (strcmp(argv[i], "+bs") == 0)
  665. enableBackingStore = TRUE;
  666. else if (strcmp(argv[i], "-bs") == 0)
  667. disableBackingStore = TRUE;
  668. else if (strcmp(argv[i], "c") == 0) {
  669. if (++i < argc)
  670. defaultKeyboardControl.click = atoi(argv[i]);
  671. else
  672. UseMsg();
  673. }
  674. else if (strcmp(argv[i], "-c") == 0) {
  675. defaultKeyboardControl.click = 0;
  676. }
  677. else if (strcmp(argv[i], "-cc") == 0) {
  678. if (++i < argc)
  679. defaultColorVisualClass = atoi(argv[i]);
  680. else
  681. UseMsg();
  682. }
  683. else if (strcmp(argv[i], "-core") == 0) {
  684. #if !defined(WIN32) || !defined(__MINGW32__)
  685. struct rlimit core_limit;
  686. getrlimit(RLIMIT_CORE, &core_limit);
  687. core_limit.rlim_cur = core_limit.rlim_max;
  688. setrlimit(RLIMIT_CORE, &core_limit);
  689. #endif
  690. CoreDump = TRUE;
  691. }
  692. else if (strcmp(argv[i], "-nocursor") == 0) {
  693. EnableCursor = FALSE;
  694. }
  695. else if (strcmp(argv[i], "-dpi") == 0) {
  696. if (++i < argc)
  697. monitorResolution = atoi(argv[i]);
  698. else
  699. UseMsg();
  700. }
  701. else if (strcmp(argv[i], "-displayfd") == 0) {
  702. if (++i < argc) {
  703. displayfd = atoi(argv[i]);
  704. #ifdef LOCK_SERVER
  705. nolock = TRUE;
  706. #endif
  707. }
  708. else
  709. UseMsg();
  710. }
  711. #ifdef DPMSExtension
  712. else if (strcmp(argv[i], "dpms") == 0)
  713. /* ignored for compatibility */ ;
  714. else if (strcmp(argv[i], "-dpms") == 0)
  715. DPMSDisabledSwitch = TRUE;
  716. #endif
  717. else if (strcmp(argv[i], "-deferglyphs") == 0) {
  718. if (++i >= argc || !ParseGlyphCachingMode(argv[i]))
  719. UseMsg();
  720. }
  721. else if (strcmp(argv[i], "-f") == 0) {
  722. if (++i < argc)
  723. defaultKeyboardControl.bell = atoi(argv[i]);
  724. else
  725. UseMsg();
  726. }
  727. else if (strcmp(argv[i], "-fc") == 0) {
  728. if (++i < argc)
  729. defaultCursorFont = argv[i];
  730. else
  731. UseMsg();
  732. }
  733. else if (strcmp(argv[i], "-fn") == 0) {
  734. if (++i < argc)
  735. defaultTextFont = argv[i];
  736. else
  737. UseMsg();
  738. }
  739. else if (strcmp(argv[i], "-fp") == 0) {
  740. if (++i < argc) {
  741. defaultFontPath = argv[i];
  742. }
  743. else
  744. UseMsg();
  745. }
  746. else if (strcmp(argv[i], "-help") == 0) {
  747. UseMsg();
  748. exit(0);
  749. }
  750. else if (strcmp(argv[i], "+iglx") == 0)
  751. enableIndirectGLX = TRUE;
  752. else if (strcmp(argv[i], "-iglx") == 0)
  753. enableIndirectGLX = FALSE;
  754. else if ((skip = XkbProcessArguments(argc, argv, i)) != 0) {
  755. if (skip > 0)
  756. i += skip - 1;
  757. else
  758. UseMsg();
  759. }
  760. #ifdef RLIMIT_DATA
  761. else if (strcmp(argv[i], "-ld") == 0) {
  762. if (++i < argc) {
  763. limitDataSpace = atoi(argv[i]);
  764. if (limitDataSpace > 0)
  765. limitDataSpace *= 1024;
  766. }
  767. else
  768. UseMsg();
  769. }
  770. #endif
  771. #ifdef RLIMIT_NOFILE
  772. else if (strcmp(argv[i], "-lf") == 0) {
  773. if (++i < argc)
  774. limitNoFile = atoi(argv[i]);
  775. else
  776. UseMsg();
  777. }
  778. #endif
  779. #ifdef RLIMIT_STACK
  780. else if (strcmp(argv[i], "-ls") == 0) {
  781. if (++i < argc) {
  782. limitStackSpace = atoi(argv[i]);
  783. if (limitStackSpace > 0)
  784. limitStackSpace *= 1024;
  785. }
  786. else
  787. UseMsg();
  788. }
  789. #endif
  790. #ifdef LOCK_SERVER
  791. else if (strcmp(argv[i], "-nolock") == 0) {
  792. #if !defined(WIN32) && !defined(__CYGWIN__)
  793. if (getuid() != 0)
  794. ErrorF
  795. ("Warning: the -nolock option can only be used by root\n");
  796. else
  797. #endif
  798. nolock = TRUE;
  799. }
  800. #endif
  801. else if (strcmp(argv[i], "-nolisten") == 0) {
  802. if (++i < argc) {
  803. if (_XSERVTransNoListen(argv[i]))
  804. ErrorF("Failed to disable listen for %s transport",
  805. argv[i]);
  806. }
  807. else
  808. UseMsg();
  809. }
  810. else if (strcmp(argv[i], "-listen") == 0) {
  811. if (++i < argc) {
  812. if (_XSERVTransListen(argv[i]))
  813. ErrorF("Failed to enable listen for %s transport",
  814. argv[i]);
  815. }
  816. else
  817. UseMsg();
  818. }
  819. else if (strcmp(argv[i], "-noreset") == 0) {
  820. dispatchExceptionAtReset = 0;
  821. }
  822. else if (strcmp(argv[i], "-reset") == 0) {
  823. dispatchExceptionAtReset = DE_RESET;
  824. }
  825. else if (strcmp(argv[i], "-p") == 0) {
  826. if (++i < argc)
  827. defaultScreenSaverInterval = ((CARD32) atoi(argv[i])) *
  828. MILLI_PER_MIN;
  829. else
  830. UseMsg();
  831. }
  832. else if (strcmp(argv[i], "-pogo") == 0) {
  833. dispatchException = DE_TERMINATE;
  834. }
  835. else if (strcmp(argv[i], "-pn") == 0)
  836. PartialNetwork = TRUE;
  837. else if (strcmp(argv[i], "-nopn") == 0)
  838. PartialNetwork = FALSE;
  839. else if (strcmp(argv[i], "r") == 0)
  840. defaultKeyboardControl.autoRepeat = TRUE;
  841. else if (strcmp(argv[i], "-r") == 0)
  842. defaultKeyboardControl.autoRepeat = FALSE;
  843. #ifndef __OpenBSD__
  844. else if ( strcmp( argv[i], "-retro") == 0)
  845. party_like_its_1989 = TRUE;
  846. #else
  847. else if ( strcmp( argv[i], "-retard") == 0)
  848. party_like_its_1989 = FALSE;
  849. #endif
  850. else if (strcmp(argv[i], "-s") == 0) {
  851. if (++i < argc)
  852. defaultScreenSaverTime = ((CARD32) atoi(argv[i])) *
  853. MILLI_PER_MIN;
  854. else
  855. UseMsg();
  856. }
  857. else if (strcmp(argv[i], "-seat") == 0) {
  858. if (++i < argc)
  859. SeatId = argv[i];
  860. else
  861. UseMsg();
  862. }
  863. else if (strcmp(argv[i], "-t") == 0) {
  864. if (++i < argc)
  865. defaultPointerControl.threshold = atoi(argv[i]);
  866. else
  867. UseMsg();
  868. }
  869. else if (strcmp(argv[i], "-terminate") == 0) {
  870. dispatchExceptionAtReset = DE_TERMINATE;
  871. }
  872. else if (strcmp(argv[i], "-to") == 0) {
  873. if (++i < argc)
  874. TimeOutValue = ((CARD32) atoi(argv[i])) * MILLI_PER_SECOND;
  875. else
  876. UseMsg();
  877. }
  878. else if (strcmp(argv[i], "-tst") == 0) {
  879. noTestExtensions = TRUE;
  880. }
  881. else if (strcmp(argv[i], "v") == 0)
  882. defaultScreenSaverBlanking = PreferBlanking;
  883. else if (strcmp(argv[i], "-v") == 0)
  884. defaultScreenSaverBlanking = DontPreferBlanking;
  885. else if (strcmp(argv[i], "-wm") == 0)
  886. defaultBackingStore = WhenMapped;
  887. else if (strcmp(argv[i], "-wr") == 0)
  888. whiteRoot = TRUE;
  889. else if (strcmp(argv[i], "-background") == 0) {
  890. if (++i < argc) {
  891. if (!strcmp(argv[i], "none"))
  892. bgNoneRoot = TRUE;
  893. else
  894. UseMsg();
  895. }
  896. }
  897. else if (strcmp(argv[i], "-maxbigreqsize") == 0) {
  898. if (++i < argc) {
  899. long reqSizeArg = atol(argv[i]);
  900. /* Request size > 128MB does not make much sense... */
  901. if (reqSizeArg > 0L && reqSizeArg < 128L) {
  902. maxBigRequestSize = (reqSizeArg * 1048576L) - 1L;
  903. }
  904. else {
  905. UseMsg();
  906. }
  907. }
  908. else {
  909. UseMsg();
  910. }
  911. }
  912. #ifdef PANORAMIX
  913. else if (strcmp(argv[i], "+xinerama") == 0) {
  914. noPanoramiXExtension = FALSE;
  915. }
  916. else if (strcmp(argv[i], "-xinerama") == 0) {
  917. noPanoramiXExtension = TRUE;
  918. }
  919. else if (strcmp(argv[i], "-disablexineramaextension") == 0) {
  920. PanoramiXExtensionDisabledHack = TRUE;
  921. }
  922. #endif
  923. else if (strcmp(argv[i], "-I") == 0) {
  924. /* ignore all remaining arguments */
  925. break;
  926. }
  927. else if (strncmp(argv[i], "tty", 3) == 0) {
  928. /* init supplies us with this useless information */
  929. }
  930. #ifdef XDMCP
  931. else if ((skip = XdmcpOptions(argc, argv, i)) != i) {
  932. i = skip - 1;
  933. }
  934. #endif
  935. #ifdef SMART_SCHEDULE_POSSIBLE
  936. else if (strcmp(argv[i], "-dumbSched") == 0) {
  937. SmartScheduleDisable = TRUE;
  938. }
  939. else if (strcmp(argv[i], "-schedInterval") == 0) {
  940. if (++i < argc) {
  941. SmartScheduleInterval = atoi(argv[i]);
  942. SmartScheduleSlice = SmartScheduleInterval;
  943. }
  944. else
  945. UseMsg();
  946. }
  947. else if (strcmp(argv[i], "-schedMax") == 0) {
  948. if (++i < argc) {
  949. SmartScheduleMaxSlice = atoi(argv[i]);
  950. }
  951. else
  952. UseMsg();
  953. }
  954. #endif
  955. else if (strcmp(argv[i], "-render") == 0) {
  956. if (++i < argc) {
  957. int policy = PictureParseCmapPolicy(argv[i]);
  958. if (policy != PictureCmapPolicyInvalid)
  959. PictureCmapPolicy = policy;
  960. else
  961. UseMsg();
  962. }
  963. else
  964. UseMsg();
  965. }
  966. else if (strcmp(argv[i], "-sigstop") == 0) {
  967. RunFromSigStopParent = TRUE;
  968. }
  969. else if (strcmp(argv[i], "+extension") == 0) {
  970. if (++i < argc) {
  971. if (!EnableDisableExtension(argv[i], TRUE))
  972. EnableDisableExtensionError(argv[i], TRUE);
  973. }
  974. else
  975. UseMsg();
  976. }
  977. else if (strcmp(argv[i], "-extension") == 0) {
  978. if (++i < argc) {
  979. if (!EnableDisableExtension(argv[i], FALSE))
  980. EnableDisableExtensionError(argv[i], FALSE);
  981. }
  982. else
  983. UseMsg();
  984. }
  985. else {
  986. ErrorF("Unrecognized option: %s\n", argv[i]);
  987. UseMsg();
  988. FatalError("Unrecognized option: %s\n", argv[i]);
  989. }
  990. }
  991. }
  992. /* Implement a simple-minded font authorization scheme. The authorization
  993. name is "hp-hostname-1", the contents are simply the host name. */
  994. int
  995. set_font_authorizations(char **authorizations, int *authlen, void *client)
  996. {
  997. #define AUTHORIZATION_NAME "hp-hostname-1"
  998. #if defined(TCPCONN) || defined(STREAMSCONN)
  999. static char *result = NULL;
  1000. static char *p = NULL;
  1001. if (p == NULL) {
  1002. char hname[1024], *hnameptr;
  1003. unsigned int len;
  1004. #if defined(IPv6) && defined(AF_INET6)
  1005. struct addrinfo hints, *ai = NULL;
  1006. #else
  1007. struct hostent *host;
  1008. #ifdef XTHREADS_NEEDS_BYNAMEPARAMS
  1009. _Xgethostbynameparams hparams;
  1010. #endif
  1011. #endif
  1012. gethostname(hname, 1024);
  1013. #if defined(IPv6) && defined(AF_INET6)
  1014. memset(&hints, 0, sizeof(hints));
  1015. hints.ai_flags = AI_CANONNAME;
  1016. if (getaddrinfo(hname, NULL, &hints, &ai) == 0) {
  1017. hnameptr = ai->ai_canonname;
  1018. }
  1019. else {
  1020. hnameptr = hname;
  1021. }
  1022. #else
  1023. host = _XGethostbyname(hname, hparams);
  1024. if (host == NULL)
  1025. hnameptr = hname;
  1026. else
  1027. hnameptr = host->h_name;
  1028. #endif
  1029. len = strlen(hnameptr) + 1;
  1030. result = malloc(len + sizeof(AUTHORIZATION_NAME) + 4);
  1031. p = result;
  1032. *p++ = sizeof(AUTHORIZATION_NAME) >> 8;
  1033. *p++ = sizeof(AUTHORIZATION_NAME) & 0xff;
  1034. *p++ = (len) >> 8;
  1035. *p++ = (len & 0xff);
  1036. memmove(p, AUTHORIZATION_NAME, sizeof(AUTHORIZATION_NAME));
  1037. p += sizeof(AUTHORIZATION_NAME);
  1038. memmove(p, hnameptr, len);
  1039. p += len;
  1040. #if defined(IPv6) && defined(AF_INET6)
  1041. if (ai) {
  1042. freeaddrinfo(ai);
  1043. }
  1044. #endif
  1045. }
  1046. *authlen = p - result;
  1047. *authorizations = result;
  1048. return 1;
  1049. #else /* TCPCONN */
  1050. return 0;
  1051. #endif /* TCPCONN */
  1052. }
  1053. void *
  1054. Xalloc(unsigned long amount)
  1055. {
  1056. /*
  1057. * Xalloc used to return NULL when large amount of memory is requested. In
  1058. * order to catch the buggy callers this warning has been added, slated to
  1059. * removal by anyone who touches this code (or just looks at it) in 2011.
  1060. *
  1061. * -- Mikhail Gusarov
  1062. */
  1063. if ((long) amount <= 0)
  1064. ErrorF("Warning: Xalloc: "
  1065. "requesting unpleasantly large amount of memory: %lu bytes.\n",
  1066. amount);
  1067. return malloc(amount);
  1068. }
  1069. void *
  1070. XNFalloc(unsigned long amount)
  1071. {
  1072. void *ptr = malloc(amount);
  1073. if (!ptr)
  1074. FatalError("Out of memory");
  1075. return ptr;
  1076. }
  1077. void *
  1078. Xcalloc(unsigned long amount)
  1079. {
  1080. return calloc(1, amount);
  1081. }
  1082. void *
  1083. XNFcalloc(unsigned long amount)
  1084. {
  1085. void *ret = calloc(1, amount);
  1086. if (!ret)
  1087. FatalError("XNFcalloc: Out of memory");
  1088. return ret;
  1089. }
  1090. void *
  1091. Xrealloc(void *ptr, unsigned long amount)
  1092. {
  1093. /*
  1094. * Xrealloc used to return NULL when large amount of memory is requested. In
  1095. * order to catch the buggy callers this warning has been added, slated to
  1096. * removal by anyone who touches this code (or just looks at it) in 2011.
  1097. *
  1098. * -- Mikhail Gusarov
  1099. */
  1100. if ((long) amount <= 0)
  1101. ErrorF("Warning: Xrealloc: "
  1102. "requesting unpleasantly large amount of memory: %lu bytes.\n",
  1103. amount);
  1104. return realloc(ptr, amount);
  1105. }
  1106. void *
  1107. XNFrealloc(void *ptr, unsigned long amount)
  1108. {
  1109. void *ret = realloc(ptr, amount);
  1110. if (!ret)
  1111. FatalError("XNFrealloc: Out of memory");
  1112. return ret;
  1113. }
  1114. void
  1115. Xfree(void *ptr)
  1116. {
  1117. free(ptr);
  1118. }
  1119. char *
  1120. Xstrdup(const char *s)
  1121. {
  1122. if (s == NULL)
  1123. return NULL;
  1124. return strdup(s);
  1125. }
  1126. char *
  1127. XNFstrdup(const char *s)
  1128. {
  1129. char *ret;
  1130. if (s == NULL)
  1131. return NULL;
  1132. ret = strdup(s);
  1133. if (!ret)
  1134. FatalError("XNFstrdup: Out of memory");
  1135. return ret;
  1136. }
  1137. void
  1138. SmartScheduleStopTimer(void)
  1139. {
  1140. #ifdef SMART_SCHEDULE_POSSIBLE
  1141. struct itimerval timer;
  1142. if (SmartScheduleDisable)
  1143. return;
  1144. timer.it_interval.tv_sec = 0;
  1145. timer.it_interval.tv_usec = 0;
  1146. timer.it_value.tv_sec = 0;
  1147. timer.it_value.tv_usec = 0;
  1148. (void) setitimer(ITIMER_REAL, &timer, 0);
  1149. #endif
  1150. }
  1151. void
  1152. SmartScheduleStartTimer(void)
  1153. {
  1154. #ifdef SMART_SCHEDULE_POSSIBLE
  1155. struct itimerval timer;
  1156. if (SmartScheduleDisable)
  1157. return;
  1158. timer.it_interval.tv_sec = 0;
  1159. timer.it_interval.tv_usec = SmartScheduleInterval * 1000;
  1160. timer.it_value.tv_sec = 0;
  1161. timer.it_value.tv_usec = SmartScheduleInterval * 1000;
  1162. setitimer(ITIMER_REAL, &timer, 0);
  1163. #endif
  1164. }
  1165. static void
  1166. SmartScheduleTimer(int sig)
  1167. {
  1168. SmartScheduleTime += SmartScheduleInterval;
  1169. }
  1170. void
  1171. SmartScheduleInit(void)
  1172. {
  1173. #ifdef SMART_SCHEDULE_POSSIBLE
  1174. struct sigaction act;
  1175. if (SmartScheduleDisable)
  1176. return;
  1177. memset((char *) &act, 0, sizeof(struct sigaction));
  1178. /* Set up the timer signal function */
  1179. act.sa_handler = SmartScheduleTimer;
  1180. sigemptyset(&act.sa_mask);
  1181. sigaddset(&act.sa_mask, SIGALRM);
  1182. if (sigaction(SIGALRM, &act, 0) < 0) {
  1183. perror("sigaction for smart scheduler");
  1184. SmartScheduleDisable = TRUE;
  1185. }
  1186. #endif
  1187. }
  1188. #ifdef SIG_BLOCK
  1189. static sigset_t PreviousSignalMask;
  1190. static int BlockedSignalCount;
  1191. #endif
  1192. void
  1193. OsBlockSignals(void)
  1194. {
  1195. #ifdef SIG_BLOCK
  1196. if (BlockedSignalCount++ == 0) {
  1197. sigset_t set;
  1198. #ifdef SIGIO
  1199. OsBlockSIGIO();
  1200. #endif
  1201. sigemptyset(&set);
  1202. sigaddset(&set, SIGALRM);
  1203. sigaddset(&set, SIGVTALRM);
  1204. #ifdef SIGWINCH
  1205. sigaddset(&set, SIGWINCH);
  1206. #endif
  1207. sigaddset(&set, SIGTSTP);
  1208. sigaddset(&set, SIGTTIN);
  1209. sigaddset(&set, SIGTTOU);
  1210. sigaddset(&set, SIGCHLD);
  1211. sigprocmask(SIG_BLOCK, &set, &PreviousSignalMask);
  1212. }
  1213. #endif
  1214. }
  1215. #ifdef SIG_BLOCK
  1216. static sig_atomic_t sigio_blocked;
  1217. static sigset_t PreviousSigIOMask;
  1218. #endif
  1219. /**
  1220. * returns zero if this call caused SIGIO to be blocked now, non-zero if it
  1221. * was already blocked by a previous call to this function.
  1222. */
  1223. int
  1224. OsBlockSIGIO(void)
  1225. {
  1226. #ifdef SIGIO
  1227. #ifdef SIG_BLOCK
  1228. if (sigio_blocked++ == 0) {
  1229. sigset_t set;
  1230. int ret;
  1231. sigemptyset(&set);
  1232. sigaddset(&set, SIGIO);
  1233. sigprocmask(SIG_BLOCK, &set, &PreviousSigIOMask);
  1234. ret = sigismember(&PreviousSigIOMask, SIGIO);
  1235. return ret;
  1236. }
  1237. #endif
  1238. #endif
  1239. return 1;
  1240. }
  1241. void
  1242. OsReleaseSIGIO(void)
  1243. {
  1244. #ifdef SIGIO
  1245. #ifdef SIG_BLOCK
  1246. if (--sigio_blocked == 0) {
  1247. sigprocmask(SIG_SETMASK, &PreviousSigIOMask, 0);
  1248. } else if (sigio_blocked < 0) {
  1249. BUG_WARN(sigio_blocked < 0);
  1250. sigio_blocked = 0;
  1251. }
  1252. #endif
  1253. #endif
  1254. }
  1255. void
  1256. OsReleaseSignals(void)
  1257. {
  1258. #ifdef SIG_BLOCK
  1259. if (--BlockedSignalCount == 0) {
  1260. sigprocmask(SIG_SETMASK, &PreviousSignalMask, 0);
  1261. OsReleaseSIGIO();
  1262. }
  1263. #endif
  1264. }
  1265. void
  1266. OsResetSignals(void)
  1267. {
  1268. #ifdef SIG_BLOCK
  1269. while (BlockedSignalCount > 0)
  1270. OsReleaseSignals();
  1271. #ifdef SIGIO
  1272. while (sigio_blocked > 0)
  1273. OsReleaseSIGIO();
  1274. #endif
  1275. #endif
  1276. }
  1277. /*
  1278. * Pending signals may interfere with core dumping. Provide a
  1279. * mechanism to block signals when aborting.
  1280. */
  1281. void
  1282. OsAbort(void)
  1283. {
  1284. #ifndef __APPLE__
  1285. OsBlockSignals();
  1286. #endif
  1287. abort();
  1288. }
  1289. #if !defined(WIN32)
  1290. /*
  1291. * "safer" versions of system(3), popen(3) and pclose(3) which give up
  1292. * all privs before running a command.
  1293. *
  1294. * This is based on the code in FreeBSD 2.2 libc.
  1295. *
  1296. * XXX It'd be good to redirect stderr so that it ends up in the log file
  1297. * as well. As it is now, xkbcomp messages don't end up in the log file.
  1298. */
  1299. int
  1300. System(const char *command)
  1301. {
  1302. int pid, p;
  1303. void (*csig) (int);
  1304. int status;
  1305. if (!command)
  1306. return 1;
  1307. csig = signal(SIGCHLD, SIG_DFL);
  1308. if (csig == SIG_ERR) {
  1309. perror("signal");
  1310. return -1;
  1311. }
  1312. DebugF("System: `%s'\n", command);
  1313. switch (pid = fork()) {
  1314. case -1: /* error */
  1315. p = -1;
  1316. case 0: /* child */
  1317. if (setgid(getgid()) == -1)
  1318. _exit(127);
  1319. if (setuid(getuid()) == -1)
  1320. _exit(127);
  1321. execl("/bin/sh", "sh", "-c", command, (char *) NULL);
  1322. _exit(127);
  1323. default: /* parent */
  1324. do {
  1325. p = waitpid(pid, &status, 0);
  1326. } while (p == -1 && errno == EINTR);
  1327. }
  1328. if (signal(SIGCHLD, csig) == SIG_ERR) {
  1329. perror("signal");
  1330. return -1;
  1331. }
  1332. return p == -1 ? -1 : status;
  1333. }
  1334. static struct pid {
  1335. struct pid *next;
  1336. FILE *fp;
  1337. int pid;
  1338. } *pidlist;
  1339. OsSigHandlerPtr old_alarm = NULL; /* XXX horrible awful hack */
  1340. void *
  1341. Popen(const char *command, const char *type)
  1342. {
  1343. struct pid *cur;
  1344. FILE *iop;
  1345. int pdes[2], pid;
  1346. if (command == NULL || type == NULL)
  1347. return NULL;
  1348. if ((*type != 'r' && *type != 'w') || type[1])
  1349. return NULL;
  1350. if ((cur = malloc(sizeof(struct pid))) == NULL)
  1351. return NULL;
  1352. if (pipe(pdes) < 0) {
  1353. free(cur);
  1354. return NULL;
  1355. }
  1356. /* Ignore the smart scheduler while this is going on */
  1357. old_alarm = OsSignal(SIGALRM, SIG_IGN);
  1358. if (old_alarm == SIG_ERR) {
  1359. close(pdes[0]);
  1360. close(pdes[1]);
  1361. free(cur);
  1362. perror("signal");
  1363. return NULL;
  1364. }
  1365. switch (pid = fork()) {
  1366. case -1: /* error */
  1367. close(pdes[0]);
  1368. close(pdes[1]);
  1369. free(cur);
  1370. if (OsSignal(SIGALRM, old_alarm) == SIG_ERR)
  1371. perror("signal");
  1372. return NULL;
  1373. case 0: /* child */
  1374. if (setgid(getgid()) == -1)
  1375. _exit(127);
  1376. if (setuid(getuid()) == -1)
  1377. _exit(127);
  1378. if (*type == 'r') {
  1379. if (pdes[1] != 1) {
  1380. /* stdout */
  1381. dup2(pdes[1], 1);
  1382. close(pdes[1]);
  1383. }
  1384. close(pdes[0]);
  1385. }
  1386. else {
  1387. if (pdes[0] != 0) {
  1388. /* stdin */
  1389. dup2(pdes[0], 0);
  1390. close(pdes[0]);
  1391. }
  1392. close(pdes[1]);
  1393. }
  1394. execl("/bin/sh", "sh", "-c", command, (char *) NULL);
  1395. _exit(127);
  1396. }
  1397. /* Avoid EINTR during stdio calls */
  1398. OsBlockSignals();
  1399. /* parent */
  1400. if (*type == 'r') {
  1401. iop = fdopen(pdes[0], type);
  1402. close(pdes[1]);
  1403. }
  1404. else {
  1405. iop = fdopen(pdes[1], type);
  1406. close(pdes[0]);
  1407. }
  1408. cur->fp = iop;
  1409. cur->pid = pid;
  1410. cur->next = pidlist;
  1411. pidlist = cur;
  1412. DebugF("Popen: `%s', fp = %p\n", command, iop);
  1413. return iop;
  1414. }
  1415. /* fopen that drops privileges */
  1416. void *
  1417. Fopen(const char *file, const char *type)
  1418. {
  1419. FILE *iop;
  1420. #ifndef HAS_SAVED_IDS_AND_SETEUID
  1421. struct pid *cur;
  1422. int pdes[2], pid;
  1423. if (file == NULL || type == NULL)
  1424. return NULL;
  1425. if ((*type != 'r' && *type != 'w') || type[1])
  1426. return NULL;
  1427. if ((cur = malloc(sizeof(struct pid))) == NULL)
  1428. return NULL;
  1429. if (pipe(pdes) < 0) {
  1430. free(cur);
  1431. return NULL;
  1432. }
  1433. switch (pid = fork()) {
  1434. case -1: /* error */
  1435. close(pdes[0]);
  1436. close(pdes[1]);
  1437. free(cur);
  1438. return NULL;
  1439. case 0: /* child */
  1440. if (setgid(getgid()) == -1)
  1441. _exit(127);
  1442. if (setuid(getuid()) == -1)
  1443. _exit(127);
  1444. if (*type == 'r') {
  1445. if (pdes[1] != 1) {
  1446. /* stdout */
  1447. dup2(pdes[1], 1);
  1448. close(pdes[1]);
  1449. }
  1450. close(pdes[0]);
  1451. }
  1452. else {
  1453. if (pdes[0] != 0) {
  1454. /* stdin */
  1455. dup2(pdes[0], 0);
  1456. close(pdes[0]);
  1457. }
  1458. close(pdes[1]);
  1459. }
  1460. execl("/bin/cat", "cat", file, (char *) NULL);
  1461. _exit(127);
  1462. }
  1463. /* Avoid EINTR during stdio calls */
  1464. OsBlockSignals();
  1465. /* parent */
  1466. if (*type == 'r') {
  1467. iop = fdopen(pdes[0], type);
  1468. close(pdes[1]);
  1469. }
  1470. else {
  1471. iop = fdopen(pdes[1], type);
  1472. close(pdes[0]);
  1473. }
  1474. cur->fp = iop;
  1475. cur->pid = pid;
  1476. cur->next = pidlist;
  1477. pidlist = cur;
  1478. DebugF("Fopen(%s), fp = %p\n", file, iop);
  1479. return iop;
  1480. #else
  1481. int ruid, euid;
  1482. ruid = getuid();
  1483. euid = geteuid();
  1484. if (seteuid(ruid) == -1) {
  1485. return NULL;
  1486. }
  1487. iop = fopen(file, type);
  1488. if (seteuid(euid) == -1) {
  1489. fclose(iop);
  1490. return NULL;
  1491. }
  1492. return iop;
  1493. #endif /* HAS_SAVED_IDS_AND_SETEUID */
  1494. }
  1495. int
  1496. Pclose(void *iop)
  1497. {
  1498. struct pid *cur, *last;
  1499. int pstat;
  1500. int pid;
  1501. DebugF("Pclose: fp = %p\n", iop);
  1502. fclose(iop);
  1503. for (last = NULL, cur = pidlist; cur; last = cur, cur = cur->next)
  1504. if (cur->fp == iop)
  1505. break;
  1506. if (cur == NULL)
  1507. return -1;
  1508. do {
  1509. pid = waitpid(cur->pid, &pstat, 0);
  1510. } while (pid == -1 && errno == EINTR);
  1511. if (last == NULL)
  1512. pidlist = cur->next;
  1513. else
  1514. last->next = cur->next;
  1515. free(cur);
  1516. /* allow EINTR again */
  1517. OsReleaseSignals();
  1518. if (old_alarm && OsSignal(SIGALRM, old_alarm) == SIG_ERR) {
  1519. perror("signal");
  1520. return -1;
  1521. }
  1522. return pid == -1 ? -1 : pstat;
  1523. }
  1524. int
  1525. Fclose(void *iop)
  1526. {
  1527. #ifdef HAS_SAVED_IDS_AND_SETEUID
  1528. return fclose(iop);
  1529. #else
  1530. return Pclose(iop);
  1531. #endif
  1532. }
  1533. #endif /* !WIN32 */
  1534. #ifdef WIN32
  1535. #include <X11/Xwindows.h>
  1536. const char *
  1537. Win32TempDir()
  1538. {
  1539. static char buffer[PATH_MAX];
  1540. if (GetTempPath(sizeof(buffer), buffer)) {
  1541. int len;
  1542. buffer[sizeof(buffer) - 1] = 0;
  1543. len = strlen(buffer);
  1544. if (len > 0)
  1545. if (buffer[len - 1] == '\\')
  1546. buffer[len - 1] = 0;
  1547. return buffer;
  1548. }
  1549. if (getenv("TEMP") != NULL)
  1550. return getenv("TEMP");
  1551. else if (getenv("TMP") != NULL)
  1552. return getenv("TMP");
  1553. else
  1554. return "/tmp";
  1555. }
  1556. int
  1557. System(const char *cmdline)
  1558. {
  1559. STARTUPINFO si;
  1560. PROCESS_INFORMATION pi;
  1561. DWORD dwExitCode;
  1562. char *cmd = strdup(cmdline);
  1563. ZeroMemory(&si, sizeof(si));
  1564. si.cb = sizeof(si);
  1565. ZeroMemory(&pi, sizeof(pi));
  1566. if (!CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
  1567. LPVOID buffer;
  1568. if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1569. FORMAT_MESSAGE_FROM_SYSTEM |
  1570. FORMAT_MESSAGE_IGNORE_INSERTS,
  1571. NULL,
  1572. GetLastError(),
  1573. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1574. (LPTSTR) &buffer, 0, NULL)) {
  1575. ErrorF("[xkb] Starting '%s' failed!\n", cmdline);
  1576. }
  1577. else {
  1578. ErrorF("[xkb] Starting '%s' failed: %s", cmdline, (char *) buffer);
  1579. LocalFree(buffer);
  1580. }
  1581. free(cmd);
  1582. return -1;
  1583. }
  1584. /* Wait until child process exits. */
  1585. WaitForSingleObject(pi.hProcess, INFINITE);
  1586. GetExitCodeProcess(pi.hProcess, &dwExitCode);
  1587. /* Close process and thread handles. */
  1588. CloseHandle(pi.hProcess);
  1589. CloseHandle(pi.hThread);
  1590. free(cmd);
  1591. return dwExitCode;
  1592. }
  1593. #endif
  1594. /*
  1595. * CheckUserParameters: check for long command line arguments and long
  1596. * environment variables. By default, these checks are only done when
  1597. * the server's euid != ruid. In 3.3.x, these checks were done in an
  1598. * external wrapper utility.
  1599. */
  1600. /* Consider LD* variables insecure? */
  1601. #ifndef REMOVE_ENV_LD
  1602. #define REMOVE_ENV_LD 1
  1603. #endif
  1604. /* Remove long environment variables? */
  1605. #ifndef REMOVE_LONG_ENV
  1606. #define REMOVE_LONG_ENV 1
  1607. #endif
  1608. /*
  1609. * Disallow stdout or stderr as pipes? It's possible to block the X server
  1610. * when piping stdout+stderr to a pipe.
  1611. *
  1612. * Don't enable this because it looks like it's going to cause problems.
  1613. */
  1614. #ifndef NO_OUTPUT_PIPES
  1615. #define NO_OUTPUT_PIPES 0
  1616. #endif
  1617. /* Check args and env only if running setuid (euid == 0 && euid != uid) ? */
  1618. #ifndef CHECK_EUID
  1619. #ifndef WIN32
  1620. #define CHECK_EUID 1
  1621. #else
  1622. #define CHECK_EUID 0
  1623. #endif
  1624. #endif
  1625. /*
  1626. * Maybe the locale can be faked to make isprint(3) report that everything
  1627. * is printable? Avoid it by default.
  1628. */
  1629. #ifndef USE_ISPRINT
  1630. #define USE_ISPRINT 0
  1631. #endif
  1632. #define MAX_ARG_LENGTH 128
  1633. #define MAX_ENV_LENGTH 256
  1634. #define MAX_ENV_PATH_LENGTH 2048 /* Limit for *PATH and TERMCAP */
  1635. #if USE_ISPRINT
  1636. #include <ctype.h>
  1637. #define checkPrintable(c) isprint(c)
  1638. #else
  1639. #define checkPrintable(c) (((c) & 0x7f) >= 0x20 && ((c) & 0x7f) != 0x7f)
  1640. #endif
  1641. enum BadCode {
  1642. NotBad = 0,
  1643. UnsafeArg,
  1644. ArgTooLong,
  1645. UnprintableArg,
  1646. EnvTooLong,
  1647. OutputIsPipe,
  1648. InternalError
  1649. };
  1650. #if defined(VENDORSUPPORT)
  1651. #define BUGADDRESS VENDORSUPPORT
  1652. #elif defined(BUILDERADDR)
  1653. #define BUGADDRESS BUILDERADDR
  1654. #else
  1655. #define BUGADDRESS "xorg@freedesktop.org"
  1656. #endif
  1657. void
  1658. CheckUserParameters(int argc, char **argv, char **envp)
  1659. {
  1660. enum BadCode bad = NotBad;
  1661. int i = 0, j;
  1662. char *a, *e = NULL;
  1663. #if CHECK_EUID
  1664. if (geteuid() == 0 && getuid() != geteuid())
  1665. #endif
  1666. {
  1667. /* Check each argv[] */
  1668. for (i = 1; i < argc; i++) {
  1669. if (strcmp(argv[i], "-fp") == 0) {
  1670. i++; /* continue with next argument. skip the length check */
  1671. if (i >= argc)
  1672. break;
  1673. }
  1674. else {
  1675. if (strlen(argv[i]) > MAX_ARG_LENGTH) {
  1676. bad = ArgTooLong;
  1677. break;
  1678. }
  1679. }
  1680. a = argv[i];
  1681. while (*a) {
  1682. if (checkPrintable(*a) == 0) {
  1683. bad = UnprintableArg;
  1684. break;
  1685. }
  1686. a++;
  1687. }
  1688. if (bad)
  1689. break;
  1690. }
  1691. if (!bad) {
  1692. /* Check each envp[] */
  1693. for (i = 0; envp[i]; i++) {
  1694. /* Check for bad environment variables and values */
  1695. #if REMOVE_ENV_LD
  1696. while (envp[i] && (strncmp(envp[i], "LD", 2) == 0)) {
  1697. for (j = i; envp[j]; j++) {
  1698. envp[j] = envp[j + 1];
  1699. }
  1700. }
  1701. #endif
  1702. if (envp[i] && (strlen(envp[i]) > MAX_ENV_LENGTH)) {
  1703. #if REMOVE_LONG_ENV
  1704. for (j = i; envp[j]; j++) {
  1705. envp[j] = envp[j + 1];
  1706. }
  1707. i--;
  1708. #else
  1709. char *eq;
  1710. int len;
  1711. eq = strchr(envp[i], '=');
  1712. if (!eq)
  1713. continue;
  1714. len = eq - envp[i];
  1715. e = strndup(envp[i], len);
  1716. if (!e) {
  1717. bad = InternalError;
  1718. break;
  1719. }
  1720. if (len >= 4 &&
  1721. (strcmp(e + len - 4, "PATH") == 0 ||
  1722. strcmp(e, "TERMCAP") == 0)) {
  1723. if (strlen(envp[i]) > MAX_ENV_PATH_LENGTH) {
  1724. bad = EnvTooLong;
  1725. break;
  1726. }
  1727. else {
  1728. free(e);
  1729. }
  1730. }
  1731. else {
  1732. bad = EnvTooLong;
  1733. break;
  1734. }
  1735. #endif
  1736. }
  1737. }
  1738. }
  1739. #if NO_OUTPUT_PIPES
  1740. if (!bad) {
  1741. struct stat buf;
  1742. if (fstat(fileno(stdout), &buf) == 0 && S_ISFIFO(buf.st_mode))
  1743. bad = OutputIsPipe;
  1744. if (fstat(fileno(stderr), &buf) == 0 && S_ISFIFO(buf.st_mode))
  1745. bad = OutputIsPipe;
  1746. }
  1747. #endif
  1748. }
  1749. switch (bad) {
  1750. case NotBad:
  1751. return;
  1752. case UnsafeArg:
  1753. ErrorF("Command line argument number %d is unsafe\n", i);
  1754. break;
  1755. case ArgTooLong:
  1756. ErrorF("Command line argument number %d is too long\n", i);
  1757. break;
  1758. case UnprintableArg:
  1759. ErrorF("Command line argument number %d contains unprintable"
  1760. " characters\n", i);
  1761. break;
  1762. case EnvTooLong:
  1763. ErrorF("Environment variable `%s' is too long\n", e);
  1764. break;
  1765. case OutputIsPipe:
  1766. ErrorF("Stdout and/or stderr is a pipe\n");
  1767. break;
  1768. case InternalError:
  1769. ErrorF("Internal Error\n");
  1770. break;
  1771. default:
  1772. ErrorF("Unknown error\n");
  1773. break;
  1774. }
  1775. FatalError("X server aborted because of unsafe environment\n");
  1776. }
  1777. /*
  1778. * CheckUserAuthorization: check if the user is allowed to start the
  1779. * X server. This usually means some sort of PAM checking, and it is
  1780. * usually only done for setuid servers (uid != euid).
  1781. */
  1782. #ifdef USE_PAM
  1783. #include <security/pam_appl.h>
  1784. #include <security/pam_misc.h>
  1785. #include <pwd.h>
  1786. #endif /* USE_PAM */
  1787. void
  1788. CheckUserAuthorization(void)
  1789. {
  1790. #ifdef USE_PAM
  1791. static struct pam_conv conv = {
  1792. misc_conv,
  1793. NULL
  1794. };
  1795. pam_handle_t *pamh = NULL;
  1796. struct passwd *pw;
  1797. int retval;
  1798. if (getuid() != geteuid()) {
  1799. pw = getpwuid(getuid());
  1800. if (pw == NULL)
  1801. FatalError("getpwuid() failed for uid %d\n", getuid());
  1802. retval = pam_start("xserver", pw->pw_name, &conv, &pamh);
  1803. if (retval != PAM_SUCCESS)
  1804. FatalError("pam_start() failed.\n"
  1805. "\tMissing or mangled PAM config file or module?\n");
  1806. retval = pam_authenticate(pamh, 0);
  1807. if (retval != PAM_SUCCESS) {
  1808. pam_end(pamh, retval);
  1809. FatalError("PAM authentication failed, cannot start X server.\n"
  1810. "\tPerhaps you do not have console ownership?\n");
  1811. }
  1812. retval = pam_acct_mgmt(pamh, 0);
  1813. if (retval != PAM_SUCCESS) {
  1814. pam_end(pamh, retval);
  1815. FatalError("PAM authentication failed, cannot start X server.\n"
  1816. "\tPerhaps you do not have console ownership?\n");
  1817. }
  1818. /* this is not a session, so do not do session management */
  1819. pam_end(pamh, PAM_SUCCESS);
  1820. }
  1821. #endif
  1822. }
  1823. /*
  1824. * Tokenize a string into a NULL terminated array of strings. Always returns
  1825. * an allocated array unless an error occurs.
  1826. */
  1827. char **
  1828. xstrtokenize(const char *str, const char *separators)
  1829. {
  1830. char **list, **nlist;
  1831. char *tok, *tmp;
  1832. unsigned num = 0, n;
  1833. if (!str)
  1834. return NULL;
  1835. list = calloc(1, sizeof(*list));
  1836. if (!list)
  1837. return NULL;
  1838. tmp = strdup(str);
  1839. if (!tmp)
  1840. goto error;
  1841. for (tok = strtok(tmp, separators); tok; tok = strtok(NULL, separators)) {
  1842. nlist = realloc(list, (num + 2) * sizeof(*list));
  1843. if (!nlist)
  1844. goto error;
  1845. list = nlist;
  1846. list[num] = strdup(tok);
  1847. if (!list[num])
  1848. goto error;
  1849. list[++num] = NULL;
  1850. }
  1851. free(tmp);
  1852. return list;
  1853. error:
  1854. free(tmp);
  1855. for (n = 0; n < num; n++)
  1856. free(list[n]);
  1857. free(list);
  1858. return NULL;
  1859. }
  1860. /* Format a signed number into a string in a signal safe manner. The string
  1861. * should be at least 21 characters in order to handle all int64_t values.
  1862. */
  1863. void
  1864. FormatInt64(int64_t num, char *string)
  1865. {
  1866. if (num < 0) {
  1867. string[0] = '-';
  1868. num *= -1;
  1869. string++;
  1870. }
  1871. FormatUInt64(num, string);
  1872. }
  1873. /* Format a number into a string in a signal safe manner. The string should be
  1874. * at least 21 characters in order to handle all uint64_t values. */
  1875. void
  1876. FormatUInt64(uint64_t num, char *string)
  1877. {
  1878. uint64_t divisor;
  1879. int len;
  1880. int i;
  1881. for (len = 1, divisor = 10;
  1882. len < 20 && num / divisor;
  1883. len++, divisor *= 10);
  1884. for (i = len, divisor = 1; i > 0; i--, divisor *= 10)
  1885. string[i - 1] = '0' + ((num / divisor) % 10);
  1886. string[len] = '\0';
  1887. }
  1888. /**
  1889. * Format a double number as %.2f.
  1890. */
  1891. void
  1892. FormatDouble(double dbl, char *string)
  1893. {
  1894. int slen = 0;
  1895. uint64_t frac;
  1896. frac = (dbl > 0 ? dbl : -dbl) * 100.0 + 0.5;
  1897. frac %= 100;
  1898. /* write decimal part to string */
  1899. if (dbl < 0 && dbl > -1)
  1900. string[slen++] = '-';
  1901. FormatInt64((int64_t)dbl, &string[slen]);
  1902. while(string[slen] != '\0')
  1903. slen++;
  1904. /* append fractional part, but only if we have enough characters. We
  1905. * expect string to be 21 chars (incl trailing \0) */
  1906. if (slen <= 17) {
  1907. string[slen++] = '.';
  1908. if (frac < 10)
  1909. string[slen++] = '0';
  1910. FormatUInt64(frac, &string[slen]);
  1911. }
  1912. }
  1913. /* Format a number into a hexadecimal string in a signal safe manner. The string
  1914. * should be at least 17 characters in order to handle all uint64_t values. */
  1915. void
  1916. FormatUInt64Hex(uint64_t num, char *string)
  1917. {
  1918. uint64_t divisor;
  1919. int len;
  1920. int i;
  1921. for (len = 1, divisor = 0x10;
  1922. len < 16 && num / divisor;
  1923. len++, divisor *= 0x10);
  1924. for (i = len, divisor = 1; i > 0; i--, divisor *= 0x10) {
  1925. int val = (num / divisor) % 0x10;
  1926. if (val < 10)
  1927. string[i - 1] = '0' + val;
  1928. else
  1929. string[i - 1] = 'a' + val - 10;
  1930. }
  1931. string[len] = '\0';
  1932. }
  1933. /* Move a file descriptor out of the way of our select mask; this
  1934. * is useful for file descriptors which will never appear in the
  1935. * select mask to avoid reducing the number of clients that can
  1936. * connect to the server
  1937. */
  1938. int
  1939. os_move_fd(int fd)
  1940. {
  1941. int newfd;
  1942. #ifdef F_DUPFD_CLOEXEC
  1943. newfd = fcntl(fd, F_DUPFD_CLOEXEC, MAXCLIENTS);
  1944. #else
  1945. newfd = fcntl(fd, F_DUPFD, MAXCLIENTS);
  1946. #endif
  1947. if (newfd < 0)
  1948. return fd;
  1949. #ifndef F_DUPFD_CLOEXEC
  1950. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1951. #endif
  1952. close(fd);
  1953. return newfd;
  1954. }