compat.c 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2011, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file compat.c
  7. * \brief Wrappers to make calls more portable. This code defines
  8. * functions such as tor_malloc, tor_snprintf, get/set various data types,
  9. * renaming, setting socket options, switching user IDs. It is basically
  10. * where the non-portable items are conditionally included depending on
  11. * the platform.
  12. **/
  13. /* This is required on rh7 to make strptime not complain.
  14. * We also need it to make memmem get defined (where available)
  15. */
  16. /* XXXX023 We should just use AC_USE_SYSTEM_EXTENSIONS in our autoconf,
  17. * and get this (and other important stuff!) automatically */
  18. #define _GNU_SOURCE
  19. #include "compat.h"
  20. #ifdef MS_WINDOWS
  21. #include <process.h>
  22. #include <windows.h>
  23. #include <sys/locking.h>
  24. #endif
  25. #ifdef HAVE_UNAME
  26. #include <sys/utsname.h>
  27. #endif
  28. #ifdef HAVE_UNISTD_H
  29. #include <unistd.h>
  30. #endif
  31. #ifdef HAVE_SYS_FCNTL_H
  32. #include <sys/fcntl.h>
  33. #endif
  34. #ifdef HAVE_PWD_H
  35. #include <pwd.h>
  36. #endif
  37. #ifdef HAVE_GRP_H
  38. #include <grp.h>
  39. #endif
  40. #ifdef HAVE_FCNTL_H
  41. #include <fcntl.h>
  42. #endif
  43. #ifdef HAVE_ERRNO_H
  44. #include <errno.h>
  45. #endif
  46. #ifdef HAVE_ARPA_INET_H
  47. #include <arpa/inet.h>
  48. #endif
  49. #ifndef HAVE_GETTIMEOFDAY
  50. #ifdef HAVE_FTIME
  51. #include <sys/timeb.h>
  52. #endif
  53. #endif
  54. #ifdef HAVE_NETDB_H
  55. #include <netdb.h>
  56. #endif
  57. #ifdef HAVE_SYS_PARAM_H
  58. #include <sys/param.h> /* FreeBSD needs this to know what version it is */
  59. #endif
  60. #include <stdio.h>
  61. #include <stdlib.h>
  62. #include <assert.h>
  63. #ifdef HAVE_SIGNAL_H
  64. #include <signal.h>
  65. #endif
  66. #ifdef HAVE_UTIME_H
  67. #include <utime.h>
  68. #endif
  69. #ifdef HAVE_SYS_UTIME_H
  70. #include <sys/utime.h>
  71. #endif
  72. #ifdef HAVE_SYS_MMAN_H
  73. #include <sys/mman.h>
  74. #endif
  75. #ifdef HAVE_SYS_SYSLIMITS_H
  76. #include <sys/syslimits.h>
  77. #endif
  78. #ifdef HAVE_SYS_FILE_H
  79. #include <sys/file.h>
  80. #endif
  81. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  82. /* Only use the linux prctl; the IRIX prctl is totally different */
  83. #include <sys/prctl.h>
  84. #endif
  85. #include "torlog.h"
  86. #include "util.h"
  87. #include "container.h"
  88. #include "address.h"
  89. /* Inline the strl functions if the platform doesn't have them. */
  90. #ifndef HAVE_STRLCPY
  91. #include "strlcpy.c"
  92. #endif
  93. #ifndef HAVE_STRLCAT
  94. #include "strlcat.c"
  95. #endif
  96. /** As open(path, flags, mode), but return an fd with the close-on-exec mode
  97. * set. */
  98. int
  99. tor_open_cloexec(const char *path, int flags, unsigned mode)
  100. {
  101. #ifdef O_CLOEXEC
  102. return open(path, flags|O_CLOEXEC, mode);
  103. #else
  104. int fd = open(path, flags, mode);
  105. #ifdef FD_CLOEXEC
  106. if (fd >= 0)
  107. fcntl(fd, F_SETFD, FD_CLOEXEC);
  108. #endif
  109. return fd;
  110. #endif
  111. }
  112. /** DOCDOC */
  113. FILE *
  114. tor_fopen_cloexec(const char *path, const char *mode)
  115. {
  116. FILE *result = fopen(path, mode);
  117. #ifdef FD_CLOEXEC
  118. if (result != NULL)
  119. fcntl(fileno(result), F_SETFD, FD_CLOEXEC);
  120. #endif
  121. return result;
  122. }
  123. #ifdef HAVE_SYS_MMAN_H
  124. /** Try to create a memory mapping for <b>filename</b> and return it. On
  125. * failure, return NULL. Sets errno properly, using ERANGE to mean
  126. * "empty file". */
  127. tor_mmap_t *
  128. tor_mmap_file(const char *filename)
  129. {
  130. int fd; /* router file */
  131. char *string;
  132. int page_size;
  133. tor_mmap_t *res;
  134. size_t size, filesize;
  135. tor_assert(filename);
  136. fd = tor_open_cloexec(filename, O_RDONLY, 0);
  137. if (fd<0) {
  138. int save_errno = errno;
  139. int severity = (errno == ENOENT) ? LOG_INFO : LOG_WARN;
  140. log_fn(severity, LD_FS,"Could not open \"%s\" for mmap(): %s",filename,
  141. strerror(errno));
  142. errno = save_errno;
  143. return NULL;
  144. }
  145. /* XXXX why not just do fstat here? */
  146. size = filesize = (size_t) lseek(fd, 0, SEEK_END);
  147. lseek(fd, 0, SEEK_SET);
  148. /* ensure page alignment */
  149. page_size = getpagesize();
  150. size += (size%page_size) ? page_size-(size%page_size) : 0;
  151. if (!size) {
  152. /* Zero-length file. If we call mmap on it, it will succeed but
  153. * return NULL, and bad things will happen. So just fail. */
  154. log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
  155. errno = ERANGE;
  156. close(fd);
  157. return NULL;
  158. }
  159. string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
  160. close(fd);
  161. if (string == MAP_FAILED) {
  162. int save_errno = errno;
  163. log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
  164. strerror(errno));
  165. errno = save_errno;
  166. return NULL;
  167. }
  168. res = tor_malloc_zero(sizeof(tor_mmap_t));
  169. res->data = string;
  170. res->size = filesize;
  171. res->mapping_size = size;
  172. return res;
  173. }
  174. /** Release storage held for a memory mapping. */
  175. void
  176. tor_munmap_file(tor_mmap_t *handle)
  177. {
  178. munmap((char*)handle->data, handle->mapping_size);
  179. tor_free(handle);
  180. }
  181. #elif defined(MS_WINDOWS)
  182. tor_mmap_t *
  183. tor_mmap_file(const char *filename)
  184. {
  185. TCHAR tfilename[MAX_PATH]= {0};
  186. tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
  187. int empty = 0;
  188. res->file_handle = INVALID_HANDLE_VALUE;
  189. res->mmap_handle = NULL;
  190. #ifdef UNICODE
  191. mbstowcs(tfilename,filename,MAX_PATH);
  192. #else
  193. strlcpy(tfilename,filename,MAX_PATH);
  194. #endif
  195. res->file_handle = CreateFile(tfilename,
  196. GENERIC_READ, FILE_SHARE_READ,
  197. NULL,
  198. OPEN_EXISTING,
  199. FILE_ATTRIBUTE_NORMAL,
  200. 0);
  201. if (res->file_handle == INVALID_HANDLE_VALUE)
  202. goto win_err;
  203. res->size = GetFileSize(res->file_handle, NULL);
  204. if (res->size == 0) {
  205. log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
  206. empty = 1;
  207. goto err;
  208. }
  209. res->mmap_handle = CreateFileMapping(res->file_handle,
  210. NULL,
  211. PAGE_READONLY,
  212. #if SIZEOF_SIZE_T > 4
  213. (res->base.size >> 32),
  214. #else
  215. 0,
  216. #endif
  217. (res->size & 0xfffffffful),
  218. NULL);
  219. if (res->mmap_handle == NULL)
  220. goto win_err;
  221. res->data = (char*) MapViewOfFile(res->mmap_handle,
  222. FILE_MAP_READ,
  223. 0, 0, 0);
  224. if (!res->data)
  225. goto win_err;
  226. return res;
  227. win_err: {
  228. DWORD e = GetLastError();
  229. int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
  230. LOG_INFO : LOG_WARN;
  231. char *msg = format_win32_error(e);
  232. log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
  233. tor_free(msg);
  234. if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
  235. errno = ENOENT;
  236. else
  237. errno = EINVAL;
  238. }
  239. err:
  240. if (empty)
  241. errno = ERANGE;
  242. tor_munmap_file(res);
  243. return NULL;
  244. }
  245. void
  246. tor_munmap_file(tor_mmap_t *handle)
  247. {
  248. if (handle->data)
  249. /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
  250. have to be redefined as non-const. */
  251. UnmapViewOfFile( (LPVOID) handle->data);
  252. if (handle->mmap_handle != NULL)
  253. CloseHandle(handle->mmap_handle);
  254. if (handle->file_handle != INVALID_HANDLE_VALUE)
  255. CloseHandle(handle->file_handle);
  256. tor_free(handle);
  257. }
  258. #else
  259. tor_mmap_t *
  260. tor_mmap_file(const char *filename)
  261. {
  262. struct stat st;
  263. char *res = read_file_to_str(filename, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  264. tor_mmap_t *handle;
  265. if (! res)
  266. return NULL;
  267. handle = tor_malloc_zero(sizeof(tor_mmap_t));
  268. handle->data = res;
  269. handle->size = st.st_size;
  270. return handle;
  271. }
  272. void
  273. tor_munmap_file(tor_mmap_t *handle)
  274. {
  275. char *d = (char*)handle->data;
  276. tor_free(d);
  277. memset(handle, 0, sizeof(tor_mmap_t));
  278. tor_free(handle);
  279. }
  280. #endif
  281. /** Replacement for snprintf. Differs from platform snprintf in two
  282. * ways: First, always NUL-terminates its output. Second, always
  283. * returns -1 if the result is truncated. (Note that this return
  284. * behavior does <i>not</i> conform to C99; it just happens to be
  285. * easier to emulate "return -1" with conformant implementations than
  286. * it is to emulate "return number that would be written" with
  287. * non-conformant implementations.) */
  288. int
  289. tor_snprintf(char *str, size_t size, const char *format, ...)
  290. {
  291. va_list ap;
  292. int r;
  293. va_start(ap,format);
  294. r = tor_vsnprintf(str,size,format,ap);
  295. va_end(ap);
  296. return r;
  297. }
  298. /** Replacement for vsnprintf; behavior differs as tor_snprintf differs from
  299. * snprintf.
  300. */
  301. int
  302. tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
  303. {
  304. int r;
  305. if (size == 0)
  306. return -1; /* no place for the NUL */
  307. if (size > SIZE_T_CEILING)
  308. return -1;
  309. #ifdef MS_WINDOWS
  310. r = _vsnprintf(str, size, format, args);
  311. #else
  312. r = vsnprintf(str, size, format, args);
  313. #endif
  314. str[size-1] = '\0';
  315. if (r < 0 || r >= (ssize_t)size)
  316. return -1;
  317. return r;
  318. }
  319. /**
  320. * Portable asprintf implementation. Does a printf() into a newly malloc'd
  321. * string. Sets *<b>strp</b> to this string, and returns its length (not
  322. * including the terminating NUL character).
  323. *
  324. * You can treat this function as if its implementation were something like
  325. <pre>
  326. char buf[_INFINITY_];
  327. tor_snprintf(buf, sizeof(buf), fmt, args);
  328. *strp = tor_strdup(buf);
  329. return strlen(*strp):
  330. </pre>
  331. * Where _INFINITY_ is an imaginary constant so big that any string can fit
  332. * into it.
  333. */
  334. int
  335. tor_asprintf(char **strp, const char *fmt, ...)
  336. {
  337. int r;
  338. va_list args;
  339. va_start(args, fmt);
  340. r = tor_vasprintf(strp, fmt, args);
  341. va_end(args);
  342. if (!*strp || r < 0) {
  343. log_err(LD_BUG, "Internal error in asprintf");
  344. tor_assert(0);
  345. }
  346. return r;
  347. }
  348. /**
  349. * Portable vasprintf implementation. Does a printf() into a newly malloc'd
  350. * string. Differs from regular vasprintf in the same ways that
  351. * tor_asprintf() differs from regular asprintf.
  352. */
  353. int
  354. tor_vasprintf(char **strp, const char *fmt, va_list args)
  355. {
  356. /* use a temporary variable in case *strp is in args. */
  357. char *strp_tmp=NULL;
  358. #ifdef HAVE_VASPRINTF
  359. /* If the platform gives us one, use it. */
  360. int r = vasprintf(&strp_tmp, fmt, args);
  361. if (r < 0)
  362. *strp = NULL;
  363. else
  364. *strp = strp_tmp;
  365. return r;
  366. #elif defined(_MSC_VER)
  367. /* On Windows, _vsnprintf won't tell us the length of the string if it
  368. * overflows, so we need to use _vcsprintf to tell how much to allocate */
  369. int len, r;
  370. char *res;
  371. len = _vscprintf(fmt, args);
  372. if (len < 0) {
  373. *strp = NULL;
  374. return -1;
  375. }
  376. strp_tmp = tor_malloc(len + 1);
  377. r = _vsnprintf(strp_tmp, len+1, fmt, args);
  378. if (r != len) {
  379. tor_free(strp_tmp);
  380. *strp = NULL;
  381. return -1;
  382. }
  383. *strp = strp_tmp;
  384. return len;
  385. #else
  386. /* Everywhere else, we have a decent vsnprintf that tells us how many
  387. * characters we need. We give it a try on a short buffer first, since
  388. * it might be nice to avoid the second vsnprintf call.
  389. */
  390. char buf[128];
  391. int len, r;
  392. va_list tmp_args;
  393. va_copy(tmp_args, args);
  394. len = vsnprintf(buf, sizeof(buf), fmt, tmp_args);
  395. va_end(tmp_args);
  396. if (len < (int)sizeof(buf)) {
  397. *strp = tor_strdup(buf);
  398. return len;
  399. }
  400. strp_tmp = tor_malloc(len+1);
  401. r = vsnprintf(strp_tmp, len+1, fmt, args);
  402. if (r != len) {
  403. tor_free(strp_tmp);
  404. *strp = NULL;
  405. return -1;
  406. }
  407. *strp = strp_tmp;
  408. return len;
  409. #endif
  410. }
  411. /** Given <b>hlen</b> bytes at <b>haystack</b> and <b>nlen</b> bytes at
  412. * <b>needle</b>, return a pointer to the first occurrence of the needle
  413. * within the haystack, or NULL if there is no such occurrence.
  414. *
  415. * This function is <em>not</em> timing-safe.
  416. *
  417. * Requires that <b>nlen</b> be greater than zero.
  418. */
  419. const void *
  420. tor_memmem(const void *_haystack, size_t hlen,
  421. const void *_needle, size_t nlen)
  422. {
  423. #if defined(HAVE_MEMMEM) && (!defined(__GNUC__) || __GNUC__ >= 2)
  424. tor_assert(nlen);
  425. return memmem(_haystack, hlen, _needle, nlen);
  426. #else
  427. /* This isn't as fast as the GLIBC implementation, but it doesn't need to
  428. * be. */
  429. const char *p, *end;
  430. const char *haystack = (const char*)_haystack;
  431. const char *needle = (const char*)_needle;
  432. char first;
  433. tor_assert(nlen);
  434. p = haystack;
  435. end = haystack + hlen;
  436. first = *(const char*)needle;
  437. while ((p = memchr(p, first, end-p))) {
  438. if (p+nlen > end)
  439. return NULL;
  440. if (fast_memeq(p, needle, nlen))
  441. return p;
  442. ++p;
  443. }
  444. return NULL;
  445. #endif
  446. }
  447. /* Tables to implement ctypes-replacement TOR_IS*() functions. Each table
  448. * has 256 bits to look up whether a character is in some set or not. This
  449. * fails on non-ASCII platforms, but it is hard to find a platform whose
  450. * character set is not a superset of ASCII nowadays. */
  451. const uint32_t TOR_ISALPHA_TABLE[8] =
  452. { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
  453. const uint32_t TOR_ISALNUM_TABLE[8] =
  454. { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
  455. const uint32_t TOR_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
  456. const uint32_t TOR_ISXDIGIT_TABLE[8] =
  457. { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
  458. const uint32_t TOR_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
  459. const uint32_t TOR_ISPRINT_TABLE[8] =
  460. { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
  461. const uint32_t TOR_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
  462. const uint32_t TOR_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
  463. /* Upper-casing and lowercasing tables to map characters to upper/lowercase
  464. * equivalents. */
  465. const char TOR_TOUPPER_TABLE[256] = {
  466. 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
  467. 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
  468. 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
  469. 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
  470. 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
  471. 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
  472. 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
  473. 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
  474. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  475. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
  476. 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
  477. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
  478. 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
  479. 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
  480. 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
  481. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
  482. };
  483. const char TOR_TOLOWER_TABLE[256] = {
  484. 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
  485. 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
  486. 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
  487. 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
  488. 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
  489. 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
  490. 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
  491. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
  492. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  493. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
  494. 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
  495. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
  496. 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
  497. 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
  498. 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
  499. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
  500. };
  501. /** Implementation of strtok_r for platforms whose coders haven't figured out
  502. * how to write one. Hey guys! You can use this code here for free! */
  503. char *
  504. tor_strtok_r_impl(char *str, const char *sep, char **lasts)
  505. {
  506. char *cp, *start;
  507. if (str)
  508. start = cp = *lasts = str;
  509. else if (!*lasts)
  510. return NULL;
  511. else
  512. start = cp = *lasts;
  513. tor_assert(*sep);
  514. if (sep[1]) {
  515. while (*cp && !strchr(sep, *cp))
  516. ++cp;
  517. } else {
  518. tor_assert(strlen(sep) == 1);
  519. cp = strchr(cp, *sep);
  520. }
  521. if (!cp || !*cp) {
  522. *lasts = NULL;
  523. } else {
  524. *cp++ = '\0';
  525. *lasts = cp;
  526. }
  527. return start;
  528. }
  529. #ifdef MS_WINDOWS
  530. /** Take a filename and return a pointer to its final element. This
  531. * function is called on __FILE__ to fix a MSVC nit where __FILE__
  532. * contains the full path to the file. This is bad, because it
  533. * confuses users to find the home directory of the person who
  534. * compiled the binary in their warning messages.
  535. */
  536. const char *
  537. tor_fix_source_file(const char *fname)
  538. {
  539. const char *cp1, *cp2, *r;
  540. cp1 = strrchr(fname, '/');
  541. cp2 = strrchr(fname, '\\');
  542. if (cp1 && cp2) {
  543. r = (cp1<cp2)?(cp2+1):(cp1+1);
  544. } else if (cp1) {
  545. r = cp1+1;
  546. } else if (cp2) {
  547. r = cp2+1;
  548. } else {
  549. r = fname;
  550. }
  551. return r;
  552. }
  553. #endif
  554. /**
  555. * Read a 16-bit value beginning at <b>cp</b>. Equivalent to
  556. * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
  557. * unaligned memory access.
  558. */
  559. uint16_t
  560. get_uint16(const void *cp)
  561. {
  562. uint16_t v;
  563. memcpy(&v,cp,2);
  564. return v;
  565. }
  566. /**
  567. * Read a 32-bit value beginning at <b>cp</b>. Equivalent to
  568. * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
  569. * unaligned memory access.
  570. */
  571. uint32_t
  572. get_uint32(const void *cp)
  573. {
  574. uint32_t v;
  575. memcpy(&v,cp,4);
  576. return v;
  577. }
  578. /**
  579. * Read a 64-bit value beginning at <b>cp</b>. Equivalent to
  580. * *(uint64_t*)(cp), but will not cause segfaults on platforms that forbid
  581. * unaligned memory access.
  582. */
  583. uint64_t
  584. get_uint64(const void *cp)
  585. {
  586. uint64_t v;
  587. memcpy(&v,cp,8);
  588. return v;
  589. }
  590. /**
  591. * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  592. * *(uint16_t*)(cp) = v, but will not cause segfaults on platforms that forbid
  593. * unaligned memory access. */
  594. void
  595. set_uint16(void *cp, uint16_t v)
  596. {
  597. memcpy(cp,&v,2);
  598. }
  599. /**
  600. * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  601. * *(uint32_t*)(cp) = v, but will not cause segfaults on platforms that forbid
  602. * unaligned memory access. */
  603. void
  604. set_uint32(void *cp, uint32_t v)
  605. {
  606. memcpy(cp,&v,4);
  607. }
  608. /**
  609. * Set a 64-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  610. * *(uint64_t*)(cp) = v, but will not cause segfaults on platforms that forbid
  611. * unaligned memory access. */
  612. void
  613. set_uint64(void *cp, uint64_t v)
  614. {
  615. memcpy(cp,&v,8);
  616. }
  617. /**
  618. * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
  619. * the same as rename(2). On windows, this removes <b>to</b> first if
  620. * it already exists.
  621. * Returns 0 on success. Returns -1 and sets errno on failure.
  622. */
  623. int
  624. replace_file(const char *from, const char *to)
  625. {
  626. #ifndef MS_WINDOWS
  627. return rename(from,to);
  628. #else
  629. switch (file_status(to))
  630. {
  631. case FN_NOENT:
  632. break;
  633. case FN_FILE:
  634. if (unlink(to)) return -1;
  635. break;
  636. case FN_ERROR:
  637. return -1;
  638. case FN_DIR:
  639. errno = EISDIR;
  640. return -1;
  641. }
  642. return rename(from,to);
  643. #endif
  644. }
  645. /** Change <b>fname</b>'s modification time to now. */
  646. int
  647. touch_file(const char *fname)
  648. {
  649. if (utime(fname, NULL)!=0)
  650. return -1;
  651. return 0;
  652. }
  653. /** Represents a lockfile on which we hold the lock. */
  654. struct tor_lockfile_t {
  655. /** Name of the file */
  656. char *filename;
  657. /** File descriptor used to hold the file open */
  658. int fd;
  659. };
  660. /** Try to get a lock on the lockfile <b>filename</b>, creating it as
  661. * necessary. If someone else has the lock and <b>blocking</b> is true,
  662. * wait until the lock is available. Otherwise return immediately whether
  663. * we succeeded or not.
  664. *
  665. * Set *<b>locked_out</b> to true if somebody else had the lock, and to false
  666. * otherwise.
  667. *
  668. * Return a <b>tor_lockfile_t</b> on success, NULL on failure.
  669. *
  670. * (Implementation note: because we need to fall back to fcntl on some
  671. * platforms, these locks are per-process, not per-thread. If you want
  672. * to do in-process locking, use tor_mutex_t like a normal person.
  673. * On Windows, when <b>blocking</b> is true, the maximum time that
  674. * is actually waited is 10 seconds, after which NULL is returned
  675. * and <b>locked_out</b> is set to 1.)
  676. */
  677. tor_lockfile_t *
  678. tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
  679. {
  680. tor_lockfile_t *result;
  681. int fd;
  682. *locked_out = 0;
  683. log_info(LD_FS, "Locking \"%s\"", filename);
  684. fd = tor_open_cloexec(filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
  685. if (fd < 0) {
  686. log_warn(LD_FS,"Couldn't open \"%s\" for locking: %s", filename,
  687. strerror(errno));
  688. return NULL;
  689. }
  690. #ifdef WIN32
  691. _lseek(fd, 0, SEEK_SET);
  692. if (_locking(fd, blocking ? _LK_LOCK : _LK_NBLCK, 1) < 0) {
  693. if (errno != EACCES && errno != EDEADLOCK)
  694. log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
  695. else
  696. *locked_out = 1;
  697. close(fd);
  698. return NULL;
  699. }
  700. #elif defined(HAVE_FLOCK)
  701. if (flock(fd, LOCK_EX|(blocking ? 0 : LOCK_NB)) < 0) {
  702. if (errno != EWOULDBLOCK)
  703. log_warn(LD_FS,"Couldn't lock \"%s\": %s", filename, strerror(errno));
  704. else
  705. *locked_out = 1;
  706. close(fd);
  707. return NULL;
  708. }
  709. #else
  710. {
  711. struct flock lock;
  712. memset(&lock, 0, sizeof(lock));
  713. lock.l_type = F_WRLCK;
  714. lock.l_whence = SEEK_SET;
  715. if (fcntl(fd, blocking ? F_SETLKW : F_SETLK, &lock) < 0) {
  716. if (errno != EACCES && errno != EAGAIN)
  717. log_warn(LD_FS, "Couldn't lock \"%s\": %s", filename, strerror(errno));
  718. else
  719. *locked_out = 1;
  720. close(fd);
  721. return NULL;
  722. }
  723. }
  724. #endif
  725. result = tor_malloc(sizeof(tor_lockfile_t));
  726. result->filename = tor_strdup(filename);
  727. result->fd = fd;
  728. return result;
  729. }
  730. /** Release the lock held as <b>lockfile</b>. */
  731. void
  732. tor_lockfile_unlock(tor_lockfile_t *lockfile)
  733. {
  734. tor_assert(lockfile);
  735. log_info(LD_FS, "Unlocking \"%s\"", lockfile->filename);
  736. #ifdef WIN32
  737. _lseek(lockfile->fd, 0, SEEK_SET);
  738. if (_locking(lockfile->fd, _LK_UNLCK, 1) < 0) {
  739. log_warn(LD_FS,"Error unlocking \"%s\": %s", lockfile->filename,
  740. strerror(errno));
  741. }
  742. #elif defined(HAVE_FLOCK)
  743. if (flock(lockfile->fd, LOCK_UN) < 0) {
  744. log_warn(LD_FS, "Error unlocking \"%s\": %s", lockfile->filename,
  745. strerror(errno));
  746. }
  747. #else
  748. /* Closing the lockfile is sufficient. */
  749. #endif
  750. close(lockfile->fd);
  751. lockfile->fd = -1;
  752. tor_free(lockfile->filename);
  753. tor_free(lockfile);
  754. }
  755. /** @{ */
  756. /** Some old versions of Unix didn't define constants for these values,
  757. * and instead expect you to say 0, 1, or 2. */
  758. #ifndef SEEK_CUR
  759. #define SEEK_CUR 1
  760. #endif
  761. #ifndef SEEK_END
  762. #define SEEK_END 2
  763. #endif
  764. /** @} */
  765. /** Return the position of <b>fd</b> with respect to the start of the file. */
  766. off_t
  767. tor_fd_getpos(int fd)
  768. {
  769. #ifdef WIN32
  770. return (off_t) _lseek(fd, 0, SEEK_CUR);
  771. #else
  772. return (off_t) lseek(fd, 0, SEEK_CUR);
  773. #endif
  774. }
  775. /** Move <b>fd</b> to the end of the file. Return -1 on error, 0 on success. */
  776. int
  777. tor_fd_seekend(int fd)
  778. {
  779. #ifdef WIN32
  780. return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
  781. #else
  782. return lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
  783. #endif
  784. }
  785. #undef DEBUG_SOCKET_COUNTING
  786. #ifdef DEBUG_SOCKET_COUNTING
  787. /** A bitarray of all fds that should be passed to tor_socket_close(). Only
  788. * used if DEBUG_SOCKET_COUNTING is defined. */
  789. static bitarray_t *open_sockets = NULL;
  790. /** The size of <b>open_sockets</b>, in bits. */
  791. static int max_socket = -1;
  792. #endif
  793. /** Count of number of sockets currently open. (Undercounts sockets opened by
  794. * eventdns and libevent.) */
  795. static int n_sockets_open = 0;
  796. /** Mutex to protect open_sockets, max_socket, and n_sockets_open. */
  797. static tor_mutex_t *socket_accounting_mutex = NULL;
  798. /** Helper: acquire the socket accounting lock. */
  799. static INLINE void
  800. socket_accounting_lock(void)
  801. {
  802. if (PREDICT_UNLIKELY(!socket_accounting_mutex))
  803. socket_accounting_mutex = tor_mutex_new();
  804. tor_mutex_acquire(socket_accounting_mutex);
  805. }
  806. /** Helper: release the socket accounting lock. */
  807. static INLINE void
  808. socket_accounting_unlock(void)
  809. {
  810. tor_mutex_release(socket_accounting_mutex);
  811. }
  812. /** As close(), but guaranteed to work for sockets across platforms (including
  813. * Windows, where close()ing a socket doesn't work. Returns 0 on success, -1
  814. * on failure. */
  815. int
  816. tor_close_socket(tor_socket_t s)
  817. {
  818. int r = 0;
  819. /* On Windows, you have to call close() on fds returned by open(),
  820. * and closesocket() on fds returned by socket(). On Unix, everything
  821. * gets close()'d. We abstract this difference by always using
  822. * tor_close_socket to close sockets, and always using close() on
  823. * files.
  824. */
  825. #if defined(MS_WINDOWS)
  826. r = closesocket(s);
  827. #else
  828. r = close(s);
  829. #endif
  830. socket_accounting_lock();
  831. #ifdef DEBUG_SOCKET_COUNTING
  832. if (s > max_socket || ! bitarray_is_set(open_sockets, s)) {
  833. log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_"
  834. "socket(), or that was already closed or something.", s);
  835. } else {
  836. tor_assert(open_sockets && s <= max_socket);
  837. bitarray_clear(open_sockets, s);
  838. }
  839. #endif
  840. if (r == 0) {
  841. --n_sockets_open;
  842. } else {
  843. int err = tor_socket_errno(-1);
  844. log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err));
  845. #ifdef WIN32
  846. if (err != WSAENOTSOCK)
  847. --n_sockets_open;
  848. #else
  849. if (err != EBADF)
  850. --n_sockets_open;
  851. #endif
  852. r = -1;
  853. }
  854. if (n_sockets_open < 0)
  855. log_warn(LD_BUG, "Our socket count is below zero: %d. Please submit a "
  856. "bug report.", n_sockets_open);
  857. socket_accounting_unlock();
  858. return r;
  859. }
  860. /** @{ */
  861. #ifdef DEBUG_SOCKET_COUNTING
  862. /** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is
  863. * now an open socket. */
  864. static INLINE void
  865. mark_socket_open(tor_socket_t s)
  866. {
  867. /* XXXX This bitarray business will NOT work on windows: sockets aren't
  868. small ints there. */
  869. if (s > max_socket) {
  870. if (max_socket == -1) {
  871. open_sockets = bitarray_init_zero(s+128);
  872. max_socket = s+128;
  873. } else {
  874. open_sockets = bitarray_expand(open_sockets, max_socket, s+128);
  875. max_socket = s+128;
  876. }
  877. }
  878. if (bitarray_is_set(open_sockets, s)) {
  879. log_warn(LD_BUG, "I thought that %d was already open, but socket() just "
  880. "gave it to me!", s);
  881. }
  882. bitarray_set(open_sockets, s);
  883. }
  884. #else
  885. #define mark_socket_open(s) STMT_NIL
  886. #endif
  887. /** @} */
  888. /** As socket(), but counts the number of open sockets. */
  889. tor_socket_t
  890. tor_open_socket(int domain, int type, int protocol)
  891. {
  892. tor_socket_t s;
  893. #ifdef SOCK_CLOEXEC
  894. #define LINUX_CLOEXEC_OPEN_SOCKET
  895. type |= SOCK_CLOEXEC;
  896. #endif
  897. s = socket(domain, type, protocol);
  898. if (SOCKET_OK(s)) {
  899. #if !defined(LINUX_CLOEXEC_OPEN_SOCKET) && defined(FD_CLOEXEC)
  900. fcntl(s, F_SETFD, FD_CLOEXEC);
  901. #endif
  902. socket_accounting_lock();
  903. ++n_sockets_open;
  904. mark_socket_open(s);
  905. socket_accounting_unlock();
  906. }
  907. return s;
  908. }
  909. /** As socket(), but counts the number of open sockets. */
  910. tor_socket_t
  911. tor_accept_socket(int sockfd, struct sockaddr *addr, socklen_t *len)
  912. {
  913. tor_socket_t s;
  914. #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
  915. #define LINUX_CLOEXEC_ACCEPT
  916. s = accept4(sockfd, addr, len, SOCK_CLOEXEC);
  917. #else
  918. s = accept(sockfd, addr, len);
  919. #endif
  920. if (SOCKET_OK(s)) {
  921. #if !defined(LINUX_CLOEXEC_ACCEPT) && defined(FD_CLOEXEC)
  922. fcntl(s, F_SETFD, FD_CLOEXEC);
  923. #endif
  924. socket_accounting_lock();
  925. ++n_sockets_open;
  926. mark_socket_open(s);
  927. socket_accounting_unlock();
  928. }
  929. return s;
  930. }
  931. /** Return the number of sockets we currently have opened. */
  932. int
  933. get_n_open_sockets(void)
  934. {
  935. int n;
  936. socket_accounting_lock();
  937. n = n_sockets_open;
  938. socket_accounting_unlock();
  939. return n;
  940. }
  941. /** Turn <b>socket</b> into a nonblocking socket.
  942. */
  943. void
  944. set_socket_nonblocking(tor_socket_t socket)
  945. {
  946. #if defined(MS_WINDOWS)
  947. unsigned long nonblocking = 1;
  948. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  949. #else
  950. fcntl(socket, F_SETFL, O_NONBLOCK);
  951. #endif
  952. }
  953. /**
  954. * Allocate a pair of connected sockets. (Like socketpair(family,
  955. * type,protocol,fd), but works on systems that don't have
  956. * socketpair.)
  957. *
  958. * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported.
  959. *
  960. * Note that on systems without socketpair, this call will fail if
  961. * localhost is inaccessible (for example, if the networking
  962. * stack is down). And even if it succeeds, the socket pair will not
  963. * be able to read while localhost is down later (the socket pair may
  964. * even close, depending on OS-specific timeouts).
  965. *
  966. * Returns 0 on success and -errno on failure; do not rely on the value
  967. * of errno or WSAGetLastError().
  968. **/
  969. /* It would be nicer just to set errno, but that won't work for windows. */
  970. int
  971. tor_socketpair(int family, int type, int protocol, tor_socket_t fd[2])
  972. {
  973. //don't use win32 socketpairs (they are always bad)
  974. #if defined(HAVE_SOCKETPAIR) && !defined(MS_WINDOWS)
  975. int r;
  976. #ifdef SOCK_CLOEXEC
  977. type |= SOCK_CLOEXEC;
  978. #endif
  979. r = socketpair(family, type, protocol, fd);
  980. if (r == 0) {
  981. #if !defined(SOCK_CLOEXEC) && defined(FD_CLOEXEC)
  982. if (fd[0] >= 0)
  983. fcntl(fd[0], F_SETFD, FD_CLOEXEC);
  984. if (fd[1] >= 0)
  985. fcntl(fd[1], F_SETFD, FD_CLOEXEC);
  986. #endif
  987. socket_accounting_lock();
  988. if (fd[0] >= 0) {
  989. ++n_sockets_open;
  990. mark_socket_open(fd[0]);
  991. }
  992. if (fd[1] >= 0) {
  993. ++n_sockets_open;
  994. mark_socket_open(fd[1]);
  995. }
  996. socket_accounting_unlock();
  997. }
  998. return r < 0 ? -errno : r;
  999. #else
  1000. /* This socketpair does not work when localhost is down. So
  1001. * it's really not the same thing at all. But it's close enough
  1002. * for now, and really, when localhost is down sometimes, we
  1003. * have other problems too.
  1004. */
  1005. tor_socket_t listener = -1;
  1006. tor_socket_t connector = -1;
  1007. tor_socket_t acceptor = -1;
  1008. struct sockaddr_in listen_addr;
  1009. struct sockaddr_in connect_addr;
  1010. int size;
  1011. int saved_errno = -1;
  1012. if (protocol
  1013. #ifdef AF_UNIX
  1014. || family != AF_UNIX
  1015. #endif
  1016. ) {
  1017. #ifdef MS_WINDOWS
  1018. return -WSAEAFNOSUPPORT;
  1019. #else
  1020. return -EAFNOSUPPORT;
  1021. #endif
  1022. }
  1023. if (!fd) {
  1024. return -EINVAL;
  1025. }
  1026. listener = tor_open_socket(AF_INET, type, 0);
  1027. if (listener < 0)
  1028. return -tor_socket_errno(-1);
  1029. memset(&listen_addr, 0, sizeof(listen_addr));
  1030. listen_addr.sin_family = AF_INET;
  1031. listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  1032. listen_addr.sin_port = 0; /* kernel chooses port. */
  1033. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  1034. == -1)
  1035. goto tidy_up_and_fail;
  1036. if (listen(listener, 1) == -1)
  1037. goto tidy_up_and_fail;
  1038. connector = tor_open_socket(AF_INET, type, 0);
  1039. if (connector < 0)
  1040. goto tidy_up_and_fail;
  1041. /* We want to find out the port number to connect to. */
  1042. size = sizeof(connect_addr);
  1043. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  1044. goto tidy_up_and_fail;
  1045. if (size != sizeof (connect_addr))
  1046. goto abort_tidy_up_and_fail;
  1047. if (connect(connector, (struct sockaddr *) &connect_addr,
  1048. sizeof(connect_addr)) == -1)
  1049. goto tidy_up_and_fail;
  1050. size = sizeof(listen_addr);
  1051. acceptor = tor_accept_socket(listener,
  1052. (struct sockaddr *) &listen_addr, &size);
  1053. if (acceptor < 0)
  1054. goto tidy_up_and_fail;
  1055. if (size != sizeof(listen_addr))
  1056. goto abort_tidy_up_and_fail;
  1057. tor_close_socket(listener);
  1058. /* Now check we are talking to ourself by matching port and host on the
  1059. two sockets. */
  1060. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  1061. goto tidy_up_and_fail;
  1062. if (size != sizeof (connect_addr)
  1063. || listen_addr.sin_family != connect_addr.sin_family
  1064. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  1065. || listen_addr.sin_port != connect_addr.sin_port) {
  1066. goto abort_tidy_up_and_fail;
  1067. }
  1068. fd[0] = connector;
  1069. fd[1] = acceptor;
  1070. return 0;
  1071. abort_tidy_up_and_fail:
  1072. #ifdef MS_WINDOWS
  1073. saved_errno = WSAECONNABORTED;
  1074. #else
  1075. saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  1076. #endif
  1077. tidy_up_and_fail:
  1078. if (saved_errno < 0)
  1079. saved_errno = errno;
  1080. if (listener != -1)
  1081. tor_close_socket(listener);
  1082. if (connector != -1)
  1083. tor_close_socket(connector);
  1084. if (acceptor != -1)
  1085. tor_close_socket(acceptor);
  1086. return -saved_errno;
  1087. #endif
  1088. }
  1089. /** Number of extra file descriptors to keep in reserve beyond those that we
  1090. * tell Tor it's allowed to use. */
  1091. #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond _ConnLimit */
  1092. /** Learn the maximum allowed number of file descriptors. (Some systems
  1093. * have a low soft limit.
  1094. *
  1095. * We compute this by finding the largest number that we can use.
  1096. * If we can't find a number greater than or equal to <b>limit</b>,
  1097. * then we fail: return -1.
  1098. *
  1099. * Otherwise, return 0 and store the maximum we found inside <b>max_out</b>.*/
  1100. int
  1101. set_max_file_descriptors(rlim_t limit, int *max_out)
  1102. {
  1103. /* Define some maximum connections values for systems where we cannot
  1104. * automatically determine a limit. Re Cygwin, see
  1105. * http://archives.seul.org/or/talk/Aug-2006/msg00210.html
  1106. * For an iPhone, 9999 should work. For Windows and all other unknown
  1107. * systems we use 15000 as the default. */
  1108. #ifndef HAVE_GETRLIMIT
  1109. #if defined(CYGWIN) || defined(__CYGWIN__)
  1110. const char *platform = "Cygwin";
  1111. const unsigned long MAX_CONNECTIONS = 3200;
  1112. #elif defined(MS_WINDOWS)
  1113. const char *platform = "Windows";
  1114. const unsigned long MAX_CONNECTIONS = 15000;
  1115. #else
  1116. const char *platform = "unknown platforms with no getrlimit()";
  1117. const unsigned long MAX_CONNECTIONS = 15000;
  1118. #endif
  1119. log_fn(LOG_INFO, LD_NET,
  1120. "This platform is missing getrlimit(). Proceeding.");
  1121. if (limit > MAX_CONNECTIONS) {
  1122. log_warn(LD_CONFIG,
  1123. "We do not support more than %lu file descriptors "
  1124. "on %s. Tried to raise to %lu.",
  1125. (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit);
  1126. return -1;
  1127. }
  1128. limit = MAX_CONNECTIONS;
  1129. #else /* HAVE_GETRLIMIT */
  1130. struct rlimit rlim;
  1131. tor_assert(limit > 0);
  1132. if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  1133. log_warn(LD_NET, "Could not get maximum number of file descriptors: %s",
  1134. strerror(errno));
  1135. return -1;
  1136. }
  1137. if (rlim.rlim_max < limit) {
  1138. log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're "
  1139. "limited to %lu. Please change your ulimit -n.",
  1140. (unsigned long)limit, (unsigned long)rlim.rlim_max);
  1141. return -1;
  1142. }
  1143. if (rlim.rlim_max > rlim.rlim_cur) {
  1144. log_info(LD_NET,"Raising max file descriptors from %lu to %lu.",
  1145. (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max);
  1146. }
  1147. rlim.rlim_cur = rlim.rlim_max;
  1148. if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
  1149. int bad = 1;
  1150. #ifdef OPEN_MAX
  1151. if (errno == EINVAL && OPEN_MAX < rlim.rlim_cur) {
  1152. /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is
  1153. * full of nasty lies. I'm looking at you, OSX 10.5.... */
  1154. rlim.rlim_cur = OPEN_MAX;
  1155. if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) {
  1156. if (rlim.rlim_cur < (rlim_t)limit) {
  1157. log_warn(LD_CONFIG, "We are limited to %lu file descriptors by "
  1158. "OPEN_MAX, and ConnLimit is %lu. Changing ConnLimit; sorry.",
  1159. (unsigned long)OPEN_MAX, (unsigned long)limit);
  1160. } else {
  1161. log_info(LD_CONFIG, "Dropped connection limit to OPEN_MAX (%lu); "
  1162. "Apparently, %lu was too high and rlimit lied to us.",
  1163. (unsigned long)OPEN_MAX, (unsigned long)rlim.rlim_max);
  1164. }
  1165. bad = 0;
  1166. }
  1167. }
  1168. #endif /* OPEN_MAX */
  1169. if (bad) {
  1170. log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s",
  1171. strerror(errno));
  1172. return -1;
  1173. }
  1174. }
  1175. /* leave some overhead for logs, etc, */
  1176. limit = rlim.rlim_cur;
  1177. #endif /* HAVE_GETRLIMIT */
  1178. if (limit < ULIMIT_BUFFER) {
  1179. log_warn(LD_CONFIG,
  1180. "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER);
  1181. return -1;
  1182. }
  1183. if (limit > INT_MAX)
  1184. limit = INT_MAX;
  1185. tor_assert(max_out);
  1186. *max_out = (int)limit - ULIMIT_BUFFER;
  1187. return 0;
  1188. }
  1189. #ifndef MS_WINDOWS
  1190. /** Log details of current user and group credentials. Return 0 on
  1191. * success. Logs and return -1 on failure.
  1192. */
  1193. static int
  1194. log_credential_status(void)
  1195. {
  1196. /** Log level to use when describing non-error UID/GID status. */
  1197. #define CREDENTIAL_LOG_LEVEL LOG_INFO
  1198. /* Real, effective and saved UIDs */
  1199. uid_t ruid, euid, suid;
  1200. /* Read, effective and saved GIDs */
  1201. gid_t rgid, egid, sgid;
  1202. /* Supplementary groups */
  1203. gid_t *sup_gids = NULL;
  1204. int sup_gids_size;
  1205. /* Number of supplementary groups */
  1206. int ngids;
  1207. /* log UIDs */
  1208. #ifdef HAVE_GETRESUID
  1209. if (getresuid(&ruid, &euid, &suid) != 0 ) {
  1210. log_warn(LD_GENERAL, "Error getting changed UIDs: %s", strerror(errno));
  1211. return -1;
  1212. } else {
  1213. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1214. "UID is %u (real), %u (effective), %u (saved)",
  1215. (unsigned)ruid, (unsigned)euid, (unsigned)suid);
  1216. }
  1217. #else
  1218. /* getresuid is not present on MacOS X, so we can't get the saved (E)UID */
  1219. ruid = getuid();
  1220. euid = geteuid();
  1221. (void)suid;
  1222. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1223. "UID is %u (real), %u (effective), unknown (saved)",
  1224. (unsigned)ruid, (unsigned)euid);
  1225. #endif
  1226. /* log GIDs */
  1227. #ifdef HAVE_GETRESGID
  1228. if (getresgid(&rgid, &egid, &sgid) != 0 ) {
  1229. log_warn(LD_GENERAL, "Error getting changed GIDs: %s", strerror(errno));
  1230. return -1;
  1231. } else {
  1232. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1233. "GID is %u (real), %u (effective), %u (saved)",
  1234. (unsigned)rgid, (unsigned)egid, (unsigned)sgid);
  1235. }
  1236. #else
  1237. /* getresgid is not present on MacOS X, so we can't get the saved (E)GID */
  1238. rgid = getgid();
  1239. egid = getegid();
  1240. (void)sgid;
  1241. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL,
  1242. "GID is %u (real), %u (effective), unknown (saved)",
  1243. (unsigned)rgid, (unsigned)egid);
  1244. #endif
  1245. /* log supplementary groups */
  1246. sup_gids_size = 64;
  1247. sup_gids = tor_malloc(sizeof(gid_t) * 64);
  1248. while ((ngids = getgroups(sup_gids_size, sup_gids)) < 0 &&
  1249. errno == EINVAL &&
  1250. sup_gids_size < NGROUPS_MAX) {
  1251. sup_gids_size *= 2;
  1252. sup_gids = tor_realloc(sup_gids, sizeof(gid_t) * sup_gids_size);
  1253. }
  1254. if (ngids < 0) {
  1255. log_warn(LD_GENERAL, "Error getting supplementary GIDs: %s",
  1256. strerror(errno));
  1257. tor_free(sup_gids);
  1258. return -1;
  1259. } else {
  1260. int i, retval = 0;
  1261. char *strgid;
  1262. char *s = NULL;
  1263. smartlist_t *elts = smartlist_create();
  1264. for (i = 0; i<ngids; i++) {
  1265. strgid = tor_malloc(11);
  1266. if (tor_snprintf(strgid, 11, "%u", (unsigned)sup_gids[i]) < 0) {
  1267. log_warn(LD_GENERAL, "Error printing supplementary GIDs");
  1268. tor_free(strgid);
  1269. retval = -1;
  1270. goto error;
  1271. }
  1272. smartlist_add(elts, strgid);
  1273. }
  1274. s = smartlist_join_strings(elts, " ", 0, NULL);
  1275. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Supplementary groups are: %s",s);
  1276. error:
  1277. tor_free(s);
  1278. SMARTLIST_FOREACH(elts, char *, cp,
  1279. {
  1280. tor_free(cp);
  1281. });
  1282. smartlist_free(elts);
  1283. tor_free(sup_gids);
  1284. return retval;
  1285. }
  1286. return 0;
  1287. }
  1288. #endif
  1289. /** Call setuid and setgid to run as <b>user</b> and switch to their
  1290. * primary group. Return 0 on success. On failure, log and return -1.
  1291. */
  1292. int
  1293. switch_id(const char *user)
  1294. {
  1295. #ifndef MS_WINDOWS
  1296. struct passwd *pw = NULL;
  1297. uid_t old_uid;
  1298. gid_t old_gid;
  1299. static int have_already_switched_id = 0;
  1300. tor_assert(user);
  1301. if (have_already_switched_id)
  1302. return 0;
  1303. /* Log the initial credential state */
  1304. if (log_credential_status())
  1305. return -1;
  1306. log_fn(CREDENTIAL_LOG_LEVEL, LD_GENERAL, "Changing user and groups");
  1307. /* Get old UID/GID to check if we changed correctly */
  1308. old_uid = getuid();
  1309. old_gid = getgid();
  1310. /* Lookup the user and group information, if we have a problem, bail out. */
  1311. pw = getpwnam(user);
  1312. if (pw == NULL) {
  1313. log_warn(LD_CONFIG, "Error setting configured user: %s not found", user);
  1314. return -1;
  1315. }
  1316. /* Properly switch egid,gid,euid,uid here or bail out */
  1317. if (setgroups(1, &pw->pw_gid)) {
  1318. log_warn(LD_GENERAL, "Error setting groups to gid %d: \"%s\".",
  1319. (int)pw->pw_gid, strerror(errno));
  1320. if (old_uid == pw->pw_uid) {
  1321. log_warn(LD_GENERAL, "Tor is already running as %s. You do not need "
  1322. "the \"User\" option if you are already running as the user "
  1323. "you want to be. (If you did not set the User option in your "
  1324. "torrc, check whether it was specified on the command line "
  1325. "by a startup script.)", user);
  1326. } else {
  1327. log_warn(LD_GENERAL, "If you set the \"User\" option, you must start Tor"
  1328. " as root.");
  1329. }
  1330. return -1;
  1331. }
  1332. if (setegid(pw->pw_gid)) {
  1333. log_warn(LD_GENERAL, "Error setting egid to %d: %s",
  1334. (int)pw->pw_gid, strerror(errno));
  1335. return -1;
  1336. }
  1337. if (setgid(pw->pw_gid)) {
  1338. log_warn(LD_GENERAL, "Error setting gid to %d: %s",
  1339. (int)pw->pw_gid, strerror(errno));
  1340. return -1;
  1341. }
  1342. if (setuid(pw->pw_uid)) {
  1343. log_warn(LD_GENERAL, "Error setting configured uid to %s (%d): %s",
  1344. user, (int)pw->pw_uid, strerror(errno));
  1345. return -1;
  1346. }
  1347. if (seteuid(pw->pw_uid)) {
  1348. log_warn(LD_GENERAL, "Error setting configured euid to %s (%d): %s",
  1349. user, (int)pw->pw_uid, strerror(errno));
  1350. return -1;
  1351. }
  1352. /* This is how OpenBSD rolls:
  1353. if (setgroups(1, &pw->pw_gid) || setegid(pw->pw_gid) ||
  1354. setgid(pw->pw_gid) || setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
  1355. setgid(pw->pw_gid) || seteuid(pw->pw_uid) || setuid(pw->pw_uid)) {
  1356. log_warn(LD_GENERAL, "Error setting configured UID/GID: %s",
  1357. strerror(errno));
  1358. return -1;
  1359. }
  1360. */
  1361. /* We've properly switched egid, gid, euid, uid, and supplementary groups if
  1362. * we're here. */
  1363. #if !defined(CYGWIN) && !defined(__CYGWIN__)
  1364. /* If we tried to drop privilege to a group/user other than root, attempt to
  1365. * restore root (E)(U|G)ID, and abort if the operation succeeds */
  1366. /* Only check for privilege dropping if we were asked to be non-root */
  1367. if (pw->pw_uid) {
  1368. /* Try changing GID/EGID */
  1369. if (pw->pw_gid != old_gid &&
  1370. (setgid(old_gid) != -1 || setegid(old_gid) != -1)) {
  1371. log_warn(LD_GENERAL, "Was able to restore group credentials even after "
  1372. "switching GID: this means that the setgid code didn't work.");
  1373. return -1;
  1374. }
  1375. /* Try changing UID/EUID */
  1376. if (pw->pw_uid != old_uid &&
  1377. (setuid(old_uid) != -1 || seteuid(old_uid) != -1)) {
  1378. log_warn(LD_GENERAL, "Was able to restore user credentials even after "
  1379. "switching UID: this means that the setuid code didn't work.");
  1380. return -1;
  1381. }
  1382. }
  1383. #endif
  1384. /* Check what really happened */
  1385. if (log_credential_status()) {
  1386. return -1;
  1387. }
  1388. have_already_switched_id = 1; /* mark success so we never try again */
  1389. #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) && defined(HAVE_PRCTL)
  1390. #ifdef PR_SET_DUMPABLE
  1391. if (pw->pw_uid) {
  1392. /* Re-enable core dumps if we're not running as root. */
  1393. log_info(LD_CONFIG, "Re-enabling coredumps");
  1394. if (prctl(PR_SET_DUMPABLE, 1)) {
  1395. log_warn(LD_CONFIG, "Unable to re-enable coredumps: %s",strerror(errno));
  1396. }
  1397. }
  1398. #endif
  1399. #endif
  1400. return 0;
  1401. #else
  1402. (void)user;
  1403. log_warn(LD_CONFIG,
  1404. "User specified but switching users is unsupported on your OS.");
  1405. return -1;
  1406. #endif
  1407. }
  1408. #ifdef HAVE_PWD_H
  1409. /** Allocate and return a string containing the home directory for the
  1410. * user <b>username</b>. Only works on posix-like systems. */
  1411. char *
  1412. get_user_homedir(const char *username)
  1413. {
  1414. struct passwd *pw;
  1415. tor_assert(username);
  1416. if (!(pw = getpwnam(username))) {
  1417. log_err(LD_CONFIG,"User \"%s\" not found.", username);
  1418. return NULL;
  1419. }
  1420. return tor_strdup(pw->pw_dir);
  1421. }
  1422. #endif
  1423. /** Modify <b>fname</b> to contain the name of the directory */
  1424. int
  1425. get_parent_directory(char *fname)
  1426. {
  1427. char *cp;
  1428. int at_end = 1;
  1429. tor_assert(fname);
  1430. #ifdef MS_WINDOWS
  1431. /* If we start with, say, c:, then don't consider that the start of the path
  1432. */
  1433. if (fname[0] && fname[1] == ':') {
  1434. fname += 2;
  1435. }
  1436. #endif
  1437. /* Now we want to remove all path-separators at the end of the string,
  1438. * and to remove the end of the string starting with the path separator
  1439. * before the last non-path-separator. In perl, this would be
  1440. * s#[/]*$##; s#/[^/]*$##;
  1441. * on a unixy platform.
  1442. */
  1443. cp = fname + strlen(fname);
  1444. at_end = 1;
  1445. while (--cp > fname) {
  1446. int is_sep = (*cp == '/'
  1447. #ifdef MS_WINDOWS
  1448. || *cp == '\\'
  1449. #endif
  1450. );
  1451. if (is_sep) {
  1452. *cp = '\0';
  1453. if (! at_end)
  1454. return 0;
  1455. } else {
  1456. at_end = 0;
  1457. }
  1458. }
  1459. return -1;
  1460. }
  1461. /** Set *addr to the IP address (in dotted-quad notation) stored in c.
  1462. * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
  1463. * but works on Windows and Solaris.)
  1464. */
  1465. int
  1466. tor_inet_aton(const char *str, struct in_addr* addr)
  1467. {
  1468. unsigned a,b,c,d;
  1469. char more;
  1470. if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
  1471. return 0;
  1472. if (a > 255) return 0;
  1473. if (b > 255) return 0;
  1474. if (c > 255) return 0;
  1475. if (d > 255) return 0;
  1476. addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
  1477. return 1;
  1478. }
  1479. /** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or
  1480. * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the
  1481. * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns
  1482. * <b>dst</b> on success, NULL on failure.
  1483. *
  1484. * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it:
  1485. * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6
  1486. * support.) */
  1487. const char *
  1488. tor_inet_ntop(int af, const void *src, char *dst, size_t len)
  1489. {
  1490. if (af == AF_INET) {
  1491. if (tor_inet_ntoa(src, dst, len) < 0)
  1492. return NULL;
  1493. else
  1494. return dst;
  1495. } else if (af == AF_INET6) {
  1496. const struct in6_addr *addr = src;
  1497. char buf[64], *cp;
  1498. int longestGapLen = 0, longestGapPos = -1, i,
  1499. curGapPos = -1, curGapLen = 0;
  1500. uint16_t words[8];
  1501. for (i = 0; i < 8; ++i) {
  1502. words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
  1503. }
  1504. if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
  1505. words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
  1506. (words[5] == 0xffff))) {
  1507. /* This is an IPv4 address. */
  1508. if (words[5] == 0) {
  1509. tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
  1510. addr->s6_addr[12], addr->s6_addr[13],
  1511. addr->s6_addr[14], addr->s6_addr[15]);
  1512. } else {
  1513. tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
  1514. addr->s6_addr[12], addr->s6_addr[13],
  1515. addr->s6_addr[14], addr->s6_addr[15]);
  1516. }
  1517. if (strlen(buf) > len)
  1518. return NULL;
  1519. strlcpy(dst, buf, len);
  1520. return dst;
  1521. }
  1522. i = 0;
  1523. while (i < 8) {
  1524. if (words[i] == 0) {
  1525. curGapPos = i++;
  1526. curGapLen = 1;
  1527. while (i<8 && words[i] == 0) {
  1528. ++i; ++curGapLen;
  1529. }
  1530. if (curGapLen > longestGapLen) {
  1531. longestGapPos = curGapPos;
  1532. longestGapLen = curGapLen;
  1533. }
  1534. } else {
  1535. ++i;
  1536. }
  1537. }
  1538. if (longestGapLen<=1)
  1539. longestGapPos = -1;
  1540. cp = buf;
  1541. for (i = 0; i < 8; ++i) {
  1542. if (words[i] == 0 && longestGapPos == i) {
  1543. if (i == 0)
  1544. *cp++ = ':';
  1545. *cp++ = ':';
  1546. while (i < 8 && words[i] == 0)
  1547. ++i;
  1548. --i; /* to compensate for loop increment. */
  1549. } else {
  1550. tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
  1551. cp += strlen(cp);
  1552. if (i != 7)
  1553. *cp++ = ':';
  1554. }
  1555. }
  1556. *cp = '\0';
  1557. if (strlen(buf) > len)
  1558. return NULL;
  1559. strlcpy(dst, buf, len);
  1560. return dst;
  1561. } else {
  1562. return NULL;
  1563. }
  1564. }
  1565. /** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b>
  1566. * encoding an IPv4 address or IPv6 address correspondingly, try to parse the
  1567. * address and store the result in <b>dst</b> (which must have space for a
  1568. * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success,
  1569. * 0 on a bad parse, and -1 on a bad <b>af</b>.
  1570. *
  1571. * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor
  1572. * sometimes needs to format ipv6 addresses even on platforms without ipv6
  1573. * support.) */
  1574. int
  1575. tor_inet_pton(int af, const char *src, void *dst)
  1576. {
  1577. if (af == AF_INET) {
  1578. return tor_inet_aton(src, dst);
  1579. } else if (af == AF_INET6) {
  1580. struct in6_addr *out = dst;
  1581. uint16_t words[8];
  1582. int gapPos = -1, i, setWords=0;
  1583. const char *dot = strchr(src, '.');
  1584. const char *eow; /* end of words. */
  1585. if (dot == src)
  1586. return 0;
  1587. else if (!dot)
  1588. eow = src+strlen(src);
  1589. else {
  1590. unsigned byte1,byte2,byte3,byte4;
  1591. char more;
  1592. for (eow = dot-1; eow >= src && TOR_ISDIGIT(*eow); --eow)
  1593. ;
  1594. ++eow;
  1595. /* We use "scanf" because some platform inet_aton()s are too lax
  1596. * about IPv4 addresses of the form "1.2.3" */
  1597. if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c",
  1598. &byte1,&byte2,&byte3,&byte4,&more) != 4)
  1599. return 0;
  1600. if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255)
  1601. return 0;
  1602. words[6] = (byte1<<8) | byte2;
  1603. words[7] = (byte3<<8) | byte4;
  1604. setWords += 2;
  1605. }
  1606. i = 0;
  1607. while (src < eow) {
  1608. if (i > 7)
  1609. return 0;
  1610. if (TOR_ISXDIGIT(*src)) {
  1611. char *next;
  1612. long r = strtol(src, &next, 16);
  1613. if (next > 4+src)
  1614. return 0;
  1615. if (next == src)
  1616. return 0;
  1617. if (r<0 || r>65536)
  1618. return 0;
  1619. words[i++] = (uint16_t)r;
  1620. setWords++;
  1621. src = next;
  1622. if (*src != ':' && src != eow)
  1623. return 0;
  1624. ++src;
  1625. } else if (*src == ':' && i > 0 && gapPos==-1) {
  1626. gapPos = i;
  1627. ++src;
  1628. } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
  1629. gapPos = i;
  1630. src += 2;
  1631. } else {
  1632. return 0;
  1633. }
  1634. }
  1635. if (setWords > 8 ||
  1636. (setWords == 8 && gapPos != -1) ||
  1637. (setWords < 8 && gapPos == -1))
  1638. return 0;
  1639. if (gapPos >= 0) {
  1640. int nToMove = setWords - (dot ? 2 : 0) - gapPos;
  1641. int gapLen = 8 - setWords;
  1642. tor_assert(nToMove >= 0);
  1643. memmove(&words[gapPos+gapLen], &words[gapPos],
  1644. sizeof(uint16_t)*nToMove);
  1645. memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen);
  1646. }
  1647. for (i = 0; i < 8; ++i) {
  1648. out->s6_addr[2*i ] = words[i] >> 8;
  1649. out->s6_addr[2*i+1] = words[i] & 0xff;
  1650. }
  1651. return 1;
  1652. } else {
  1653. return -1;
  1654. }
  1655. }
  1656. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  1657. * *<b>addr</b> to the proper IP address, in host byte order. Returns 0
  1658. * on success, -1 on failure; 1 on transient failure.
  1659. *
  1660. * (This function exists because standard windows gethostbyname
  1661. * doesn't treat raw IP addresses properly.)
  1662. */
  1663. int
  1664. tor_lookup_hostname(const char *name, uint32_t *addr)
  1665. {
  1666. tor_addr_t myaddr;
  1667. int ret;
  1668. if ((ret = tor_addr_lookup(name, AF_INET, &myaddr)))
  1669. return ret;
  1670. if (tor_addr_family(&myaddr) == AF_INET) {
  1671. *addr = tor_addr_to_ipv4h(&myaddr);
  1672. return ret;
  1673. }
  1674. return -1;
  1675. }
  1676. /** Initialize the insecure libc RNG. */
  1677. void
  1678. tor_init_weak_random(unsigned seed)
  1679. {
  1680. #ifdef MS_WINDOWS
  1681. srand(seed);
  1682. #else
  1683. srandom(seed);
  1684. #endif
  1685. }
  1686. /** Return a randomly chosen value in the range 0..TOR_RAND_MAX. This
  1687. * entropy will not be cryptographically strong; do not rely on it
  1688. * for anything an adversary should not be able to predict. */
  1689. long
  1690. tor_weak_random(void)
  1691. {
  1692. #ifdef MS_WINDOWS
  1693. return rand();
  1694. #else
  1695. return random();
  1696. #endif
  1697. }
  1698. /** Hold the result of our call to <b>uname</b>. */
  1699. static char uname_result[256];
  1700. /** True iff uname_result is set. */
  1701. static int uname_result_is_set = 0;
  1702. /** Return a pointer to a description of our platform.
  1703. */
  1704. const char *
  1705. get_uname(void)
  1706. {
  1707. #ifdef HAVE_UNAME
  1708. struct utsname u;
  1709. #endif
  1710. if (!uname_result_is_set) {
  1711. #ifdef HAVE_UNAME
  1712. if (uname(&u) != -1) {
  1713. /* (Linux says 0 is success, Solaris says 1 is success) */
  1714. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  1715. u.sysname, u.machine);
  1716. } else
  1717. #endif
  1718. {
  1719. #ifdef MS_WINDOWS
  1720. OSVERSIONINFOEX info;
  1721. int i;
  1722. const char *plat = NULL;
  1723. const char *extra = NULL;
  1724. char acsd[MAX_PATH] = {0};
  1725. static struct {
  1726. unsigned major; unsigned minor; const char *version;
  1727. } win_version_table[] = {
  1728. { 6, 1, "Windows 7" },
  1729. { 6, 0, "Windows Vista" },
  1730. { 5, 2, "Windows Server 2003" },
  1731. { 5, 1, "Windows XP" },
  1732. { 5, 0, "Windows 2000" },
  1733. /* { 4, 0, "Windows NT 4.0" }, */
  1734. { 4, 90, "Windows Me" },
  1735. { 4, 10, "Windows 98" },
  1736. /* { 4, 0, "Windows 95" } */
  1737. { 3, 51, "Windows NT 3.51" },
  1738. { 0, 0, NULL }
  1739. };
  1740. memset(&info, 0, sizeof(info));
  1741. info.dwOSVersionInfoSize = sizeof(info);
  1742. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  1743. strlcpy(uname_result, "Bizarre version of Windows where GetVersionEx"
  1744. " doesn't work.", sizeof(uname_result));
  1745. uname_result_is_set = 1;
  1746. return uname_result;
  1747. }
  1748. #ifdef UNICODE
  1749. wcstombs(acsd, info.szCSDVersion, MAX_PATH);
  1750. #else
  1751. strlcpy(acsd, info.szCSDVersion, sizeof(acsd));
  1752. #endif
  1753. if (info.dwMajorVersion == 4 && info.dwMinorVersion == 0) {
  1754. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  1755. plat = "Windows NT 4.0";
  1756. else
  1757. plat = "Windows 95";
  1758. if (acsd[1] == 'B')
  1759. extra = "OSR2 (B)";
  1760. else if (acsd[1] == 'C')
  1761. extra = "OSR2 (C)";
  1762. } else {
  1763. for (i=0; win_version_table[i].major>0; ++i) {
  1764. if (win_version_table[i].major == info.dwMajorVersion &&
  1765. win_version_table[i].minor == info.dwMinorVersion) {
  1766. plat = win_version_table[i].version;
  1767. break;
  1768. }
  1769. }
  1770. }
  1771. if (plat && !strcmp(plat, "Windows 98")) {
  1772. if (acsd[1] == 'A')
  1773. extra = "SE (A)";
  1774. else if (acsd[1] == 'B')
  1775. extra = "SE (B)";
  1776. }
  1777. if (plat) {
  1778. if (!extra)
  1779. extra = acsd;
  1780. tor_snprintf(uname_result, sizeof(uname_result), "%s %s",
  1781. plat, extra);
  1782. } else {
  1783. if (info.dwMajorVersion > 6 ||
  1784. (info.dwMajorVersion==6 && info.dwMinorVersion>1))
  1785. tor_snprintf(uname_result, sizeof(uname_result),
  1786. "Very recent version of Windows [major=%d,minor=%d] %s",
  1787. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  1788. acsd);
  1789. else
  1790. tor_snprintf(uname_result, sizeof(uname_result),
  1791. "Unrecognized version of Windows [major=%d,minor=%d] %s",
  1792. (int)info.dwMajorVersion,(int)info.dwMinorVersion,
  1793. acsd);
  1794. }
  1795. #if !defined (WINCE)
  1796. #ifdef VER_SUITE_BACKOFFICE
  1797. if (info.wProductType == VER_NT_DOMAIN_CONTROLLER) {
  1798. strlcat(uname_result, " [domain controller]", sizeof(uname_result));
  1799. } else if (info.wProductType == VER_NT_SERVER) {
  1800. strlcat(uname_result, " [server]", sizeof(uname_result));
  1801. } else if (info.wProductType == VER_NT_WORKSTATION) {
  1802. strlcat(uname_result, " [workstation]", sizeof(uname_result));
  1803. }
  1804. #endif
  1805. #endif
  1806. #else
  1807. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  1808. #endif
  1809. }
  1810. uname_result_is_set = 1;
  1811. }
  1812. return uname_result;
  1813. }
  1814. /*
  1815. * Process control
  1816. */
  1817. #if defined(USE_PTHREADS)
  1818. /** Wraps a void (*)(void*) function and its argument so we can
  1819. * invoke them in a way pthreads would expect.
  1820. */
  1821. typedef struct tor_pthread_data_t {
  1822. void (*func)(void *);
  1823. void *data;
  1824. } tor_pthread_data_t;
  1825. /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
  1826. * and free _data. Used to make sure we can call functions the way pthread
  1827. * expects. */
  1828. static void *
  1829. tor_pthread_helper_fn(void *_data)
  1830. {
  1831. tor_pthread_data_t *data = _data;
  1832. void (*func)(void*);
  1833. void *arg;
  1834. /* mask signals to worker threads to avoid SIGPIPE, etc */
  1835. sigset_t sigs;
  1836. /* We're in a subthread; don't handle any signals here. */
  1837. sigfillset(&sigs);
  1838. pthread_sigmask(SIG_SETMASK, &sigs, NULL);
  1839. func = data->func;
  1840. arg = data->data;
  1841. tor_free(_data);
  1842. func(arg);
  1843. return NULL;
  1844. }
  1845. #endif
  1846. /** Minimalist interface to run a void function in the background. On
  1847. * Unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  1848. * func should not return, but rather should call spawn_exit.
  1849. *
  1850. * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
  1851. * since in a multithreaded environment, there is no way to be sure that
  1852. * the caller's stack will still be around when the called function is
  1853. * running.
  1854. */
  1855. int
  1856. spawn_func(void (*func)(void *), void *data)
  1857. {
  1858. #if defined(USE_WIN32_THREADS)
  1859. int rv;
  1860. rv = (int)_beginthread(func, 0, data);
  1861. if (rv == (int)-1)
  1862. return -1;
  1863. return 0;
  1864. #elif defined(USE_PTHREADS)
  1865. pthread_t thread;
  1866. tor_pthread_data_t *d;
  1867. d = tor_malloc(sizeof(tor_pthread_data_t));
  1868. d->data = data;
  1869. d->func = func;
  1870. if (pthread_create(&thread,NULL,tor_pthread_helper_fn,d))
  1871. return -1;
  1872. if (pthread_detach(thread))
  1873. return -1;
  1874. return 0;
  1875. #else
  1876. pid_t pid;
  1877. pid = fork();
  1878. if (pid<0)
  1879. return -1;
  1880. if (pid==0) {
  1881. /* Child */
  1882. func(data);
  1883. tor_assert(0); /* Should never reach here. */
  1884. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  1885. } else {
  1886. /* Parent */
  1887. return 0;
  1888. }
  1889. #endif
  1890. }
  1891. /** End the current thread/process.
  1892. */
  1893. void
  1894. spawn_exit(void)
  1895. {
  1896. #if defined(USE_WIN32_THREADS)
  1897. _endthread();
  1898. //we should never get here. my compiler thinks that _endthread returns, this
  1899. //is an attempt to fool it.
  1900. tor_assert(0);
  1901. _exit(0);
  1902. #elif defined(USE_PTHREADS)
  1903. pthread_exit(NULL);
  1904. #else
  1905. /* http://www.erlenstar.demon.co.uk/unix/faq_2.html says we should
  1906. * call _exit, not exit, from child processes. */
  1907. _exit(0);
  1908. #endif
  1909. }
  1910. /** Implementation logic for compute_num_cpus(). */
  1911. static int
  1912. compute_num_cpus_impl(void)
  1913. {
  1914. #ifdef MS_WINDOWS
  1915. SYSTEM_INFO info;
  1916. memset(&info, 0, sizeof(info));
  1917. GetSystemInfo(&info);
  1918. if (info.dwNumberOfProcessors >= 1 && info.dwNumberOfProcessors < INT_MAX)
  1919. return (int)info.dwNumberOfProcessors;
  1920. else
  1921. return -1;
  1922. #elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_CONF)
  1923. long cpus = sysconf(_SC_NPROCESSORS_CONF);
  1924. if (cpus >= 1 && cpus < INT_MAX)
  1925. return (int)cpus;
  1926. else
  1927. return -1;
  1928. #else
  1929. return -1;
  1930. #endif
  1931. }
  1932. #define MAX_DETECTABLE_CPUS 16
  1933. /** Return how many CPUs we are running with. We assume that nobody is
  1934. * using hot-swappable CPUs, so we don't recompute this after the first
  1935. * time. Return -1 if we don't know how to tell the number of CPUs on this
  1936. * system.
  1937. */
  1938. int
  1939. compute_num_cpus(void)
  1940. {
  1941. static int num_cpus = -2;
  1942. if (num_cpus == -2) {
  1943. num_cpus = compute_num_cpus_impl();
  1944. tor_assert(num_cpus != -2);
  1945. if (num_cpus > MAX_DETECTABLE_CPUS)
  1946. log_notice(LD_GENERAL, "Wow! I detected that you have %d CPUs. I "
  1947. "will not autodetect any more than %d, though. If you "
  1948. "want to configure more, set NumCPUs in your torrc",
  1949. num_cpus, MAX_DETECTABLE_CPUS);
  1950. }
  1951. return num_cpus;
  1952. }
  1953. /** Set *timeval to the current time of day. On error, log and terminate.
  1954. * (Same as gettimeofday(timeval,NULL), but never returns -1.)
  1955. */
  1956. void
  1957. tor_gettimeofday(struct timeval *timeval)
  1958. {
  1959. #ifdef MS_WINDOWS
  1960. /* Epoch bias copied from perl: number of units between windows epoch and
  1961. * Unix epoch. */
  1962. #define EPOCH_BIAS U64_LITERAL(116444736000000000)
  1963. #define UNITS_PER_SEC U64_LITERAL(10000000)
  1964. #define USEC_PER_SEC U64_LITERAL(1000000)
  1965. #define UNITS_PER_USEC U64_LITERAL(10)
  1966. union {
  1967. uint64_t ft_64;
  1968. FILETIME ft_ft;
  1969. } ft;
  1970. #if defined (WINCE)
  1971. /* wince do not have GetSystemTimeAsFileTime */
  1972. SYSTEMTIME stime;
  1973. GetSystemTime(&stime);
  1974. SystemTimeToFileTime(&stime,&ft.ft_ft);
  1975. #else
  1976. /* number of 100-nsec units since Jan 1, 1601 */
  1977. GetSystemTimeAsFileTime(&ft.ft_ft);
  1978. #endif
  1979. if (ft.ft_64 < EPOCH_BIAS) {
  1980. log_err(LD_GENERAL,"System time is before 1970; failing.");
  1981. exit(1);
  1982. }
  1983. ft.ft_64 -= EPOCH_BIAS;
  1984. timeval->tv_sec = (unsigned) (ft.ft_64 / UNITS_PER_SEC);
  1985. timeval->tv_usec = (unsigned) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
  1986. #elif defined(HAVE_GETTIMEOFDAY)
  1987. if (gettimeofday(timeval, NULL)) {
  1988. log_err(LD_GENERAL,"gettimeofday failed.");
  1989. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  1990. or segfaulted.*/
  1991. exit(1);
  1992. }
  1993. #elif defined(HAVE_FTIME)
  1994. struct timeb tb;
  1995. ftime(&tb);
  1996. timeval->tv_sec = tb.time;
  1997. timeval->tv_usec = tb.millitm * 1000;
  1998. #else
  1999. #error "No way to get time."
  2000. #endif
  2001. return;
  2002. }
  2003. #if defined(TOR_IS_MULTITHREADED) && !defined(MS_WINDOWS)
  2004. /** Defined iff we need to add locks when defining fake versions of reentrant
  2005. * versions of time-related functions. */
  2006. #define TIME_FNS_NEED_LOCKS
  2007. #endif
  2008. static struct tm *
  2009. correct_tm(int islocal, const time_t *timep, struct tm *resultbuf,
  2010. struct tm *r)
  2011. {
  2012. const char *outcome;
  2013. if (PREDICT_LIKELY(r)) {
  2014. if (r->tm_year > 8099) { /* We can't strftime dates after 9999 CE. */
  2015. r->tm_year = 8099;
  2016. r->tm_mon = 11;
  2017. r->tm_mday = 31;
  2018. r->tm_yday = 365;
  2019. r->tm_hour = 23;
  2020. r->tm_min = 59;
  2021. r->tm_sec = 59;
  2022. }
  2023. return r;
  2024. }
  2025. /* If we get here, gmtime or localtime returned NULL. It might have done
  2026. * this because of overrun or underrun, or it might have done it because of
  2027. * some other weird issue. */
  2028. if (timep) {
  2029. if (*timep < 0) {
  2030. r = resultbuf;
  2031. r->tm_year = 70; /* 1970 CE */
  2032. r->tm_mon = 0;
  2033. r->tm_mday = 1;
  2034. r->tm_yday = 1;
  2035. r->tm_hour = 0;
  2036. r->tm_min = 0 ;
  2037. r->tm_sec = 0;
  2038. outcome = "Rounding up to 1970";
  2039. goto done;
  2040. } else if (*timep >= INT32_MAX) {
  2041. /* Rounding down to INT32_MAX isn't so great, but keep in mind that we
  2042. * only do it if gmtime/localtime tells us NULL. */
  2043. r = resultbuf;
  2044. r->tm_year = 137; /* 2037 CE */
  2045. r->tm_mon = 11;
  2046. r->tm_mday = 31;
  2047. r->tm_yday = 365;
  2048. r->tm_hour = 23;
  2049. r->tm_min = 59;
  2050. r->tm_sec = 59;
  2051. outcome = "Rounding down to 2037";
  2052. goto done;
  2053. }
  2054. }
  2055. /* If we get here, then gmtime/localtime failed without getting an extreme
  2056. * value for *timep */
  2057. tor_fragile_assert();
  2058. r = resultbuf;
  2059. memset(resultbuf, 0, sizeof(struct tm));
  2060. outcome="can't recover";
  2061. done:
  2062. log_warn(LD_BUG, "%s("I64_FORMAT") failed with error %s: %s",
  2063. islocal?"localtime":"gmtime",
  2064. timep?I64_PRINTF_ARG(*timep):0,
  2065. strerror(errno),
  2066. outcome);
  2067. return r;
  2068. }
  2069. /** @{ */
  2070. /** As localtime_r, but defined for platforms that don't have it:
  2071. *
  2072. * Convert *<b>timep</b> to a struct tm in local time, and store the value in
  2073. * *<b>result</b>. Return the result on success, or NULL on failure.
  2074. */
  2075. #ifdef HAVE_LOCALTIME_R
  2076. struct tm *
  2077. tor_localtime_r(const time_t *timep, struct tm *result)
  2078. {
  2079. struct tm *r;
  2080. r = localtime_r(timep, result);
  2081. return correct_tm(1, timep, result, r);
  2082. }
  2083. #elif defined(TIME_FNS_NEED_LOCKS)
  2084. struct tm *
  2085. tor_localtime_r(const time_t *timep, struct tm *result)
  2086. {
  2087. struct tm *r;
  2088. static tor_mutex_t *m=NULL;
  2089. if (!m) { m=tor_mutex_new(); }
  2090. tor_assert(result);
  2091. tor_mutex_acquire(m);
  2092. r = localtime(timep);
  2093. if (r)
  2094. memcpy(result, r, sizeof(struct tm));
  2095. tor_mutex_release(m);
  2096. return correct_tm(1, timep, result, r);
  2097. }
  2098. #else
  2099. struct tm *
  2100. tor_localtime_r(const time_t *timep, struct tm *result)
  2101. {
  2102. struct tm *r;
  2103. tor_assert(result);
  2104. r = localtime(timep);
  2105. if (r)
  2106. memcpy(result, r, sizeof(struct tm));
  2107. return correct_tm(1, timep, result, r);
  2108. }
  2109. #endif
  2110. /** @} */
  2111. /** @{ */
  2112. /** As gmtimee_r, but defined for platforms that don't have it:
  2113. *
  2114. * Convert *<b>timep</b> to a struct tm in UTC, and store the value in
  2115. * *<b>result</b>. Return the result on success, or NULL on failure.
  2116. */
  2117. #ifdef HAVE_GMTIME_R
  2118. struct tm *
  2119. tor_gmtime_r(const time_t *timep, struct tm *result)
  2120. {
  2121. struct tm *r;
  2122. r = gmtime_r(timep, result);
  2123. return correct_tm(0, timep, result, r);
  2124. }
  2125. #elif defined(TIME_FNS_NEED_LOCKS)
  2126. struct tm *
  2127. tor_gmtime_r(const time_t *timep, struct tm *result)
  2128. {
  2129. struct tm *r;
  2130. static tor_mutex_t *m=NULL;
  2131. if (!m) { m=tor_mutex_new(); }
  2132. tor_assert(result);
  2133. tor_mutex_acquire(m);
  2134. r = gmtime(timep);
  2135. if (r)
  2136. memcpy(result, r, sizeof(struct tm));
  2137. tor_mutex_release(m);
  2138. return correct_tm(0, timep, result, r);
  2139. }
  2140. #else
  2141. struct tm *
  2142. tor_gmtime_r(const time_t *timep, struct tm *result)
  2143. {
  2144. struct tm *r;
  2145. tor_assert(result);
  2146. r = gmtime(timep);
  2147. if (r)
  2148. memcpy(result, r, sizeof(struct tm));
  2149. return correct_tm(0, timep, result, r);
  2150. }
  2151. #endif
  2152. #if defined(USE_WIN32_THREADS)
  2153. void
  2154. tor_mutex_init(tor_mutex_t *m)
  2155. {
  2156. InitializeCriticalSection(&m->mutex);
  2157. }
  2158. void
  2159. tor_mutex_uninit(tor_mutex_t *m)
  2160. {
  2161. DeleteCriticalSection(&m->mutex);
  2162. }
  2163. void
  2164. tor_mutex_acquire(tor_mutex_t *m)
  2165. {
  2166. tor_assert(m);
  2167. EnterCriticalSection(&m->mutex);
  2168. }
  2169. void
  2170. tor_mutex_release(tor_mutex_t *m)
  2171. {
  2172. LeaveCriticalSection(&m->mutex);
  2173. }
  2174. unsigned long
  2175. tor_get_thread_id(void)
  2176. {
  2177. return (unsigned long)GetCurrentThreadId();
  2178. }
  2179. #elif defined(USE_PTHREADS)
  2180. /** A mutex attribute that we're going to use to tell pthreads that we want
  2181. * "reentrant" mutexes (i.e., once we can re-lock if we're already holding
  2182. * them.) */
  2183. static pthread_mutexattr_t attr_reentrant;
  2184. /** True iff we've called tor_threads_init() */
  2185. static int threads_initialized = 0;
  2186. /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
  2187. * up with tor_mutex_init() or tor_mutex_new(); not both. */
  2188. void
  2189. tor_mutex_init(tor_mutex_t *mutex)
  2190. {
  2191. int err;
  2192. if (PREDICT_UNLIKELY(!threads_initialized))
  2193. tor_threads_init();
  2194. err = pthread_mutex_init(&mutex->mutex, &attr_reentrant);
  2195. if (PREDICT_UNLIKELY(err)) {
  2196. log_err(LD_GENERAL, "Error %d creating a mutex.", err);
  2197. tor_fragile_assert();
  2198. }
  2199. }
  2200. /** Wait until <b>m</b> is free, then acquire it. */
  2201. void
  2202. tor_mutex_acquire(tor_mutex_t *m)
  2203. {
  2204. int err;
  2205. tor_assert(m);
  2206. err = pthread_mutex_lock(&m->mutex);
  2207. if (PREDICT_UNLIKELY(err)) {
  2208. log_err(LD_GENERAL, "Error %d locking a mutex.", err);
  2209. tor_fragile_assert();
  2210. }
  2211. }
  2212. /** Release the lock <b>m</b> so another thread can have it. */
  2213. void
  2214. tor_mutex_release(tor_mutex_t *m)
  2215. {
  2216. int err;
  2217. tor_assert(m);
  2218. err = pthread_mutex_unlock(&m->mutex);
  2219. if (PREDICT_UNLIKELY(err)) {
  2220. log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
  2221. tor_fragile_assert();
  2222. }
  2223. }
  2224. /** Clean up the mutex <b>m</b> so that it no longer uses any system
  2225. * resources. Does not free <b>m</b>. This function must only be called on
  2226. * mutexes from tor_mutex_init(). */
  2227. void
  2228. tor_mutex_uninit(tor_mutex_t *m)
  2229. {
  2230. int err;
  2231. tor_assert(m);
  2232. err = pthread_mutex_destroy(&m->mutex);
  2233. if (PREDICT_UNLIKELY(err)) {
  2234. log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
  2235. tor_fragile_assert();
  2236. }
  2237. }
  2238. /** Return an integer representing this thread. */
  2239. unsigned long
  2240. tor_get_thread_id(void)
  2241. {
  2242. union {
  2243. pthread_t thr;
  2244. unsigned long id;
  2245. } r;
  2246. r.thr = pthread_self();
  2247. return r.id;
  2248. }
  2249. #endif
  2250. #ifdef TOR_IS_MULTITHREADED
  2251. /** Return a newly allocated, ready-for-use mutex. */
  2252. tor_mutex_t *
  2253. tor_mutex_new(void)
  2254. {
  2255. tor_mutex_t *m = tor_malloc_zero(sizeof(tor_mutex_t));
  2256. tor_mutex_init(m);
  2257. return m;
  2258. }
  2259. /** Release all storage and system resources held by <b>m</b>. */
  2260. void
  2261. tor_mutex_free(tor_mutex_t *m)
  2262. {
  2263. if (!m)
  2264. return;
  2265. tor_mutex_uninit(m);
  2266. tor_free(m);
  2267. }
  2268. #endif
  2269. /* Conditions. */
  2270. #ifdef USE_PTHREADS
  2271. #if 0
  2272. /** Cross-platform condition implementation. */
  2273. struct tor_cond_t {
  2274. pthread_cond_t cond;
  2275. };
  2276. /** Return a newly allocated condition, with nobody waiting on it. */
  2277. tor_cond_t *
  2278. tor_cond_new(void)
  2279. {
  2280. tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
  2281. if (pthread_cond_init(&cond->cond, NULL)) {
  2282. tor_free(cond);
  2283. return NULL;
  2284. }
  2285. return cond;
  2286. }
  2287. /** Release all resources held by <b>cond</b>. */
  2288. void
  2289. tor_cond_free(tor_cond_t *cond)
  2290. {
  2291. if (!cond)
  2292. return;
  2293. if (pthread_cond_destroy(&cond->cond)) {
  2294. log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
  2295. return;
  2296. }
  2297. tor_free(cond);
  2298. }
  2299. /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
  2300. * All waiters on the condition must wait holding the same <b>mutex</b>.
  2301. * Returns 0 on success, negative on failure. */
  2302. int
  2303. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
  2304. {
  2305. return pthread_cond_wait(&cond->cond, &mutex->mutex) ? -1 : 0;
  2306. }
  2307. /** Wake up one of the waiters on <b>cond</b>. */
  2308. void
  2309. tor_cond_signal_one(tor_cond_t *cond)
  2310. {
  2311. pthread_cond_signal(&cond->cond);
  2312. }
  2313. /** Wake up all of the waiters on <b>cond</b>. */
  2314. void
  2315. tor_cond_signal_all(tor_cond_t *cond)
  2316. {
  2317. pthread_cond_broadcast(&cond->cond);
  2318. }
  2319. #endif
  2320. /** Set up common structures for use by threading. */
  2321. void
  2322. tor_threads_init(void)
  2323. {
  2324. if (!threads_initialized) {
  2325. pthread_mutexattr_init(&attr_reentrant);
  2326. pthread_mutexattr_settype(&attr_reentrant, PTHREAD_MUTEX_RECURSIVE);
  2327. threads_initialized = 1;
  2328. set_main_thread();
  2329. }
  2330. }
  2331. #elif defined(USE_WIN32_THREADS)
  2332. #if 0
  2333. static DWORD cond_event_tls_index;
  2334. struct tor_cond_t {
  2335. CRITICAL_SECTION mutex;
  2336. smartlist_t *events;
  2337. };
  2338. tor_cond_t *
  2339. tor_cond_new(void)
  2340. {
  2341. tor_cond_t *cond = tor_malloc_zero(sizeof(tor_cond_t));
  2342. InitializeCriticalSection(&cond->mutex);
  2343. cond->events = smartlist_create();
  2344. return cond;
  2345. }
  2346. void
  2347. tor_cond_free(tor_cond_t *cond)
  2348. {
  2349. if (!cond)
  2350. return;
  2351. DeleteCriticalSection(&cond->mutex);
  2352. /* XXXX notify? */
  2353. smartlist_free(cond->events);
  2354. tor_free(cond);
  2355. }
  2356. int
  2357. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex)
  2358. {
  2359. HANDLE event;
  2360. int r;
  2361. tor_assert(cond);
  2362. tor_assert(mutex);
  2363. event = TlsGetValue(cond_event_tls_index);
  2364. if (!event) {
  2365. event = CreateEvent(0, FALSE, FALSE, NULL);
  2366. TlsSetValue(cond_event_tls_index, event);
  2367. }
  2368. EnterCriticalSection(&cond->mutex);
  2369. tor_assert(WaitForSingleObject(event, 0) == WAIT_TIMEOUT);
  2370. tor_assert(!smartlist_isin(cond->events, event));
  2371. smartlist_add(cond->events, event);
  2372. LeaveCriticalSection(&cond->mutex);
  2373. tor_mutex_release(mutex);
  2374. r = WaitForSingleObject(event, INFINITE);
  2375. tor_mutex_acquire(mutex);
  2376. switch (r) {
  2377. case WAIT_OBJECT_0: /* we got the mutex normally. */
  2378. break;
  2379. case WAIT_ABANDONED: /* holding thread exited. */
  2380. case WAIT_TIMEOUT: /* Should never happen. */
  2381. tor_assert(0);
  2382. break;
  2383. case WAIT_FAILED:
  2384. log_warn(LD_GENERAL, "Failed to acquire mutex: %d",(int) GetLastError());
  2385. }
  2386. return 0;
  2387. }
  2388. void
  2389. tor_cond_signal_one(tor_cond_t *cond)
  2390. {
  2391. HANDLE event;
  2392. tor_assert(cond);
  2393. EnterCriticalSection(&cond->mutex);
  2394. if ((event = smartlist_pop_last(cond->events)))
  2395. SetEvent(event);
  2396. LeaveCriticalSection(&cond->mutex);
  2397. }
  2398. void
  2399. tor_cond_signal_all(tor_cond_t *cond)
  2400. {
  2401. tor_assert(cond);
  2402. EnterCriticalSection(&cond->mutex);
  2403. SMARTLIST_FOREACH(cond->events, HANDLE, event, SetEvent(event));
  2404. smartlist_clear(cond->events);
  2405. LeaveCriticalSection(&cond->mutex);
  2406. }
  2407. #endif
  2408. void
  2409. tor_threads_init(void)
  2410. {
  2411. #if 0
  2412. cond_event_tls_index = TlsAlloc();
  2413. #endif
  2414. set_main_thread();
  2415. }
  2416. #endif
  2417. #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
  2418. /** Attempt to raise the current and max rlimit to infinity for our process.
  2419. * This only needs to be done once and can probably only be done when we have
  2420. * not already dropped privileges.
  2421. */
  2422. static int
  2423. tor_set_max_memlock(void)
  2424. {
  2425. /* Future consideration for Windows is probably SetProcessWorkingSetSize
  2426. * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK
  2427. * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx
  2428. */
  2429. struct rlimit limit;
  2430. /* RLIM_INFINITY is -1 on some platforms. */
  2431. limit.rlim_cur = RLIM_INFINITY;
  2432. limit.rlim_max = RLIM_INFINITY;
  2433. if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
  2434. if (errno == EPERM) {
  2435. log_warn(LD_GENERAL, "You appear to lack permissions to change memory "
  2436. "limits. Are you root?");
  2437. }
  2438. log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s",
  2439. strerror(errno));
  2440. return -1;
  2441. }
  2442. return 0;
  2443. }
  2444. #endif
  2445. /** Attempt to lock all current and all future memory pages.
  2446. * This should only be called once and while we're privileged.
  2447. * Like mlockall() we return 0 when we're successful and -1 when we're not.
  2448. * Unlike mlockall() we return 1 if we've already attempted to lock memory.
  2449. */
  2450. int
  2451. tor_mlockall(void)
  2452. {
  2453. static int memory_lock_attempted = 0;
  2454. if (memory_lock_attempted) {
  2455. return 1;
  2456. }
  2457. memory_lock_attempted = 1;
  2458. /*
  2459. * Future consideration for Windows may be VirtualLock
  2460. * VirtualLock appears to implement mlock() but not mlockall()
  2461. *
  2462. * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx
  2463. */
  2464. #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK)
  2465. if (tor_set_max_memlock() == 0) {
  2466. log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY.");
  2467. }
  2468. if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) {
  2469. log_info(LD_GENERAL, "Insecure OS paging is effectively disabled.");
  2470. return 0;
  2471. } else {
  2472. if (errno == ENOSYS) {
  2473. /* Apple - it's 2009! I'm looking at you. Grrr. */
  2474. log_notice(LD_GENERAL, "It appears that mlockall() is not available on "
  2475. "your platform.");
  2476. } else if (errno == EPERM) {
  2477. log_notice(LD_GENERAL, "It appears that you lack the permissions to "
  2478. "lock memory. Are you root?");
  2479. }
  2480. log_notice(LD_GENERAL, "Unable to lock all current and future memory "
  2481. "pages: %s", strerror(errno));
  2482. return -1;
  2483. }
  2484. #else
  2485. log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?");
  2486. return -1;
  2487. #endif
  2488. }
  2489. /** Identity of the "main" thread */
  2490. static unsigned long main_thread_id = -1;
  2491. /** Start considering the current thread to be the 'main thread'. This has
  2492. * no effect on anything besides in_main_thread(). */
  2493. void
  2494. set_main_thread(void)
  2495. {
  2496. main_thread_id = tor_get_thread_id();
  2497. }
  2498. /** Return true iff called from the main thread. */
  2499. int
  2500. in_main_thread(void)
  2501. {
  2502. return main_thread_id == tor_get_thread_id();
  2503. }
  2504. /**
  2505. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  2506. * you need to ask the socket for its actual errno. Also, you need to
  2507. * get your errors from WSAGetLastError, not errno. (If you supply a
  2508. * socket of -1, we check WSAGetLastError, but don't correct
  2509. * WSAEWOULDBLOCKs.)
  2510. *
  2511. * The upshot of all of this is that when a socket call fails, you
  2512. * should call tor_socket_errno <em>at most once</em> on the failing
  2513. * socket to get the error.
  2514. */
  2515. #if defined(MS_WINDOWS)
  2516. int
  2517. tor_socket_errno(tor_socket_t sock)
  2518. {
  2519. int optval, optvallen=sizeof(optval);
  2520. int err = WSAGetLastError();
  2521. if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) {
  2522. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  2523. return err;
  2524. if (optval)
  2525. return optval;
  2526. }
  2527. return err;
  2528. }
  2529. #endif
  2530. #if defined(MS_WINDOWS)
  2531. #define E(code, s) { code, (s " [" #code " ]") }
  2532. struct { int code; const char *msg; } windows_socket_errors[] = {
  2533. E(WSAEINTR, "Interrupted function call"),
  2534. E(WSAEACCES, "Permission denied"),
  2535. E(WSAEFAULT, "Bad address"),
  2536. E(WSAEINVAL, "Invalid argument"),
  2537. E(WSAEMFILE, "Too many open files"),
  2538. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  2539. E(WSAEINPROGRESS, "Operation now in progress"),
  2540. E(WSAEALREADY, "Operation already in progress"),
  2541. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  2542. E(WSAEDESTADDRREQ, "Destination address required"),
  2543. E(WSAEMSGSIZE, "Message too long"),
  2544. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  2545. E(WSAENOPROTOOPT, "Bad protocol option"),
  2546. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  2547. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  2548. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  2549. E(WSAEOPNOTSUPP, "Operation not supported"),
  2550. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  2551. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  2552. E(WSAEADDRINUSE, "Address already in use"),
  2553. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  2554. E(WSAENETDOWN, "Network is down"),
  2555. E(WSAENETUNREACH, "Network is unreachable"),
  2556. E(WSAENETRESET, "Network dropped connection on reset"),
  2557. E(WSAECONNABORTED, "Software caused connection abort"),
  2558. E(WSAECONNRESET, "Connection reset by peer"),
  2559. E(WSAENOBUFS, "No buffer space available"),
  2560. E(WSAEISCONN, "Socket is already connected"),
  2561. E(WSAENOTCONN, "Socket is not connected"),
  2562. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  2563. E(WSAETIMEDOUT, "Connection timed out"),
  2564. E(WSAECONNREFUSED, "Connection refused"),
  2565. E(WSAEHOSTDOWN, "Host is down"),
  2566. E(WSAEHOSTUNREACH, "No route to host"),
  2567. E(WSAEPROCLIM, "Too many processes"),
  2568. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  2569. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  2570. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  2571. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  2572. E(WSAEDISCON, "Graceful shutdown now in progress"),
  2573. #ifdef WSATYPE_NOT_FOUND
  2574. E(WSATYPE_NOT_FOUND, "Class type not found"),
  2575. #endif
  2576. E(WSAHOST_NOT_FOUND, "Host not found"),
  2577. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  2578. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  2579. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  2580. /* There are some more error codes whose numeric values are marked
  2581. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  2582. * reason that practitioners of some craft traditions deliberately
  2583. * introduce imperfections into their baskets and rugs "to allow the
  2584. * evil spirits to escape." If we catch them, then our binaries
  2585. * might not report consistent results across versions of Windows.
  2586. * Thus, I'm going to let them all fall through.
  2587. */
  2588. { -1, NULL },
  2589. };
  2590. /** There does not seem to be a strerror equivalent for Winsock errors.
  2591. * Naturally, we have to roll our own.
  2592. */
  2593. const char *
  2594. tor_socket_strerror(int e)
  2595. {
  2596. int i;
  2597. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  2598. if (e == windows_socket_errors[i].code)
  2599. return windows_socket_errors[i].msg;
  2600. }
  2601. return strerror(e);
  2602. }
  2603. #endif
  2604. /** Called before we make any calls to network-related functions.
  2605. * (Some operating systems require their network libraries to be
  2606. * initialized.) */
  2607. int
  2608. network_init(void)
  2609. {
  2610. #ifdef MS_WINDOWS
  2611. /* This silly exercise is necessary before windows will allow
  2612. * gethostbyname to work. */
  2613. WSADATA WSAData;
  2614. int r;
  2615. r = WSAStartup(0x101,&WSAData);
  2616. if (r) {
  2617. log_warn(LD_NET,"Error initializing windows network layer: code was %d",r);
  2618. return -1;
  2619. }
  2620. /* WSAData.iMaxSockets might show the max sockets we're allowed to use.
  2621. * We might use it to complain if we're trying to be a server but have
  2622. * too few sockets available. */
  2623. #endif
  2624. return 0;
  2625. }
  2626. #ifdef MS_WINDOWS
  2627. /** Return a newly allocated string describing the windows system error code
  2628. * <b>err</b>. Note that error codes are different from errno. Error codes
  2629. * come from GetLastError() when a winapi call fails. errno is set only when
  2630. * ANSI functions fail. Whee. */
  2631. char *
  2632. format_win32_error(DWORD err)
  2633. {
  2634. TCHAR *str = NULL;
  2635. char *result;
  2636. /* Somebody once decided that this interface was better than strerror(). */
  2637. FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  2638. FORMAT_MESSAGE_FROM_SYSTEM |
  2639. FORMAT_MESSAGE_IGNORE_INSERTS,
  2640. NULL, err,
  2641. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  2642. (LPVOID)&str,
  2643. 0, NULL);
  2644. if (str) {
  2645. #ifdef UNICODE
  2646. char abuf[1024] = {0};
  2647. wcstombs(abuf,str,1024);
  2648. result = tor_strdup(abuf);
  2649. #else
  2650. result = tor_strdup(str);
  2651. #endif
  2652. LocalFree(str); /* LocalFree != free() */
  2653. } else {
  2654. result = tor_strdup("<unformattable error>");
  2655. }
  2656. return result;
  2657. }
  2658. #endif