3
0

mount.c 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini mount implementation for busybox
  4. *
  5. * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
  6. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  7. * Copyright (C) 2005-2006 by Rob Landley <rob@landley.net>
  8. *
  9. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  10. */
  11. // Design notes: There is no spec for mount. Remind me to write one.
  12. //
  13. // mount_main() calls singlemount() which calls mount_it_now().
  14. //
  15. // mount_main() can loop through /etc/fstab for mount -a
  16. // singlemount() can loop through /etc/filesystems for fstype detection.
  17. // mount_it_now() does the actual mount.
  18. //
  19. //usage:#define mount_trivial_usage
  20. //usage: "[OPTIONS] [-o OPTS] DEVICE NODE"
  21. //usage:#define mount_full_usage "\n\n"
  22. //usage: "Mount a filesystem. Filesystem autodetection requires /proc.\n"
  23. //usage: "\n -a Mount all filesystems in fstab"
  24. //usage: IF_FEATURE_MOUNT_FAKE(
  25. //usage: IF_FEATURE_MTAB_SUPPORT(
  26. //usage: "\n -f Update /etc/mtab, but don't mount"
  27. //usage: )
  28. //usage: IF_NOT_FEATURE_MTAB_SUPPORT(
  29. //usage: "\n -f Dry run"
  30. //usage: )
  31. //usage: )
  32. //usage: IF_FEATURE_MOUNT_HELPERS(
  33. //usage: "\n -i Don't run mount helper"
  34. //usage: )
  35. //usage: IF_FEATURE_MTAB_SUPPORT(
  36. //usage: "\n -n Don't update /etc/mtab"
  37. //usage: )
  38. //usage: IF_FEATURE_MOUNT_VERBOSE(
  39. //usage: "\n -v Verbose"
  40. //usage: )
  41. ////usage: "\n -s Sloppy (ignored)"
  42. //usage: "\n -r Read-only mount"
  43. //usage: "\n -w Read-write mount (default)"
  44. //usage: "\n -t FSTYPE[,...] Filesystem type(s)"
  45. //usage: "\n -O OPT Mount only filesystems with option OPT (-a only)"
  46. //usage: "\n-o OPT:"
  47. //usage: IF_FEATURE_MOUNT_LOOP(
  48. //usage: "\n loop Ignored (loop devices are autodetected)"
  49. //usage: )
  50. //usage: IF_FEATURE_MOUNT_FLAGS(
  51. //usage: "\n [a]sync Writes are [a]synchronous"
  52. //usage: "\n [no]atime Disable/enable updates to inode access times"
  53. //usage: "\n [no]diratime Disable/enable atime updates to directories"
  54. //usage: "\n [no]relatime Disable/enable atime updates relative to modification time"
  55. //usage: "\n [no]dev (Dis)allow use of special device files"
  56. //usage: "\n [no]exec (Dis)allow use of executable files"
  57. //usage: "\n [no]suid (Dis)allow set-user-id-root programs"
  58. //usage: "\n [r]shared Convert [recursively] to a shared subtree"
  59. //usage: "\n [r]slave Convert [recursively] to a slave subtree"
  60. //usage: "\n [r]private Convert [recursively] to a private subtree"
  61. //usage: "\n [un]bindable Make mount point [un]able to be bind mounted"
  62. //usage: "\n [r]bind Bind a file or directory [recursively] to another location"
  63. //usage: "\n move Relocate an existing mount point"
  64. //usage: )
  65. //usage: "\n remount Remount a mounted filesystem, changing flags"
  66. //usage: "\n ro/rw Same as -r/-w"
  67. //usage: "\n"
  68. //usage: "\nThere are filesystem-specific -o flags."
  69. //usage:
  70. //usage:#define mount_example_usage
  71. //usage: "$ mount\n"
  72. //usage: "/dev/hda3 on / type minix (rw)\n"
  73. //usage: "proc on /proc type proc (rw)\n"
  74. //usage: "devpts on /dev/pts type devpts (rw)\n"
  75. //usage: "$ mount /dev/fd0 /mnt -t msdos -o ro\n"
  76. //usage: "$ mount /tmp/diskimage /opt -t ext2 -o loop\n"
  77. //usage: "$ mount cd_image.iso mydir\n"
  78. //usage:#define mount_notes_usage
  79. //usage: "Returns 0 for success, number of failed mounts for -a, or errno for one mount."
  80. #include <mntent.h>
  81. #include <syslog.h>
  82. #include <sys/mount.h>
  83. // Grab more as needed from util-linux's mount/mount_constants.h
  84. #ifndef MS_DIRSYNC
  85. # define MS_DIRSYNC (1 << 7) // Directory modifications are synchronous
  86. #endif
  87. #ifndef MS_UNION
  88. # define MS_UNION (1 << 8)
  89. #endif
  90. #ifndef MS_BIND
  91. # define MS_BIND (1 << 12)
  92. #endif
  93. #ifndef MS_MOVE
  94. # define MS_MOVE (1 << 13)
  95. #endif
  96. #ifndef MS_RECURSIVE
  97. # define MS_RECURSIVE (1 << 14)
  98. #endif
  99. #ifndef MS_SILENT
  100. # define MS_SILENT (1 << 15)
  101. #endif
  102. // The shared subtree stuff, which went in around 2.6.15
  103. #ifndef MS_UNBINDABLE
  104. # define MS_UNBINDABLE (1 << 17)
  105. #endif
  106. #ifndef MS_PRIVATE
  107. # define MS_PRIVATE (1 << 18)
  108. #endif
  109. #ifndef MS_SLAVE
  110. # define MS_SLAVE (1 << 19)
  111. #endif
  112. #ifndef MS_SHARED
  113. # define MS_SHARED (1 << 20)
  114. #endif
  115. #ifndef MS_RELATIME
  116. # define MS_RELATIME (1 << 21)
  117. #endif
  118. #ifndef MS_STRICTATIME
  119. # define MS_STRICTATIME (1 << 24)
  120. #endif
  121. /* Any ~MS_FOO value has this bit set: */
  122. #define BB_MS_INVERTED_VALUE (1u << 31)
  123. #include "libbb.h"
  124. #if ENABLE_FEATURE_MOUNT_LABEL
  125. # include "volume_id.h"
  126. #else
  127. # define resolve_mount_spec(fsname) ((void)0)
  128. #endif
  129. // Needed for nfs support only
  130. #include <sys/utsname.h>
  131. #undef TRUE
  132. #undef FALSE
  133. #if ENABLE_FEATURE_MOUNT_NFS
  134. /* This is just a warning of a common mistake. Possibly this should be a
  135. * uclibc faq entry rather than in busybox... */
  136. # if defined(__UCLIBC__) && ! defined(__UCLIBC_HAS_RPC__)
  137. # error "You need to build uClibc with UCLIBC_HAS_RPC for NFS support"
  138. # endif
  139. # include <rpc/rpc.h>
  140. # include <rpc/pmap_prot.h>
  141. # include <rpc/pmap_clnt.h>
  142. #endif
  143. #if defined(__dietlibc__)
  144. // 16.12.2006, Sampo Kellomaki (sampo@iki.fi)
  145. // dietlibc-0.30 does not have implementation of getmntent_r()
  146. static struct mntent *getmntent_r(FILE* stream, struct mntent* result,
  147. char* buffer UNUSED_PARAM, int bufsize UNUSED_PARAM)
  148. {
  149. struct mntent* ment = getmntent(stream);
  150. return memcpy(result, ment, sizeof(*ment));
  151. }
  152. #endif
  153. // Not real flags, but we want to be able to check for this.
  154. enum {
  155. MOUNT_USERS = (1 << 28) * ENABLE_DESKTOP,
  156. MOUNT_NOAUTO = (1 << 29),
  157. MOUNT_SWAP = (1 << 30),
  158. };
  159. #define OPTION_STR "o:t:rwanfvsiO:"
  160. enum {
  161. OPT_o = (1 << 0),
  162. OPT_t = (1 << 1),
  163. OPT_r = (1 << 2),
  164. OPT_w = (1 << 3),
  165. OPT_a = (1 << 4),
  166. OPT_n = (1 << 5),
  167. OPT_f = (1 << 6),
  168. OPT_v = (1 << 7),
  169. OPT_s = (1 << 8),
  170. OPT_i = (1 << 9),
  171. OPT_O = (1 << 10),
  172. };
  173. #if ENABLE_FEATURE_MTAB_SUPPORT
  174. #define USE_MTAB (!(option_mask32 & OPT_n))
  175. #else
  176. #define USE_MTAB 0
  177. #endif
  178. #if ENABLE_FEATURE_MOUNT_FAKE
  179. #define FAKE_IT (option_mask32 & OPT_f)
  180. #else
  181. #define FAKE_IT 0
  182. #endif
  183. #if ENABLE_FEATURE_MOUNT_HELPERS
  184. #define HELPERS_ALLOWED (!(option_mask32 & OPT_i))
  185. #else
  186. #define HELPERS_ALLOWED 0
  187. #endif
  188. // TODO: more "user" flag compatibility.
  189. // "user" option (from mount manpage):
  190. // Only the user that mounted a filesystem can unmount it again.
  191. // If any user should be able to unmount, then use users instead of user
  192. // in the fstab line. The owner option is similar to the user option,
  193. // with the restriction that the user must be the owner of the special file.
  194. // This may be useful e.g. for /dev/fd if a login script makes
  195. // the console user owner of this device.
  196. // Standard mount options (from -o options or --options),
  197. // with corresponding flags
  198. static const int32_t mount_options[] = {
  199. // MS_FLAGS set a bit. ~MS_FLAGS disable that bit. 0 flags are NOPs.
  200. IF_FEATURE_MOUNT_LOOP(
  201. /* "loop" */ 0,
  202. )
  203. IF_FEATURE_MOUNT_FSTAB(
  204. /* "defaults" */ 0,
  205. /* "quiet" 0 - do not filter out, vfat wants to see it */
  206. /* "noauto" */ MOUNT_NOAUTO,
  207. /* "sw" */ MOUNT_SWAP,
  208. /* "swap" */ MOUNT_SWAP,
  209. IF_DESKTOP(/* "user" */ MOUNT_USERS,)
  210. IF_DESKTOP(/* "users" */ MOUNT_USERS,)
  211. /* "_netdev" */ 0,
  212. IF_DESKTOP(/* "comment=" */ 0,) /* systemd uses this in fstab */
  213. )
  214. IF_FEATURE_MOUNT_FLAGS(
  215. // vfs flags
  216. /* "nosuid" */ MS_NOSUID,
  217. /* "suid" */ ~MS_NOSUID,
  218. /* "dev" */ ~MS_NODEV,
  219. /* "nodev" */ MS_NODEV,
  220. /* "exec" */ ~MS_NOEXEC,
  221. /* "noexec" */ MS_NOEXEC,
  222. /* "sync" */ MS_SYNCHRONOUS,
  223. /* "dirsync" */ MS_DIRSYNC,
  224. /* "async" */ ~MS_SYNCHRONOUS,
  225. /* "atime" */ ~MS_NOATIME,
  226. /* "noatime" */ MS_NOATIME,
  227. /* "diratime" */ ~MS_NODIRATIME,
  228. /* "nodiratime" */ MS_NODIRATIME,
  229. /* "mand" */ MS_MANDLOCK,
  230. /* "nomand" */ ~MS_MANDLOCK,
  231. /* "relatime" */ MS_RELATIME,
  232. /* "norelatime" */ ~MS_RELATIME,
  233. /* "strictatime" */ MS_STRICTATIME,
  234. /* "loud" */ ~MS_SILENT,
  235. /* "rbind" */ MS_BIND|MS_RECURSIVE,
  236. // action flags
  237. /* "union" */ MS_UNION,
  238. /* "bind" */ MS_BIND,
  239. /* "move" */ MS_MOVE,
  240. /* "shared" */ MS_SHARED,
  241. /* "slave" */ MS_SLAVE,
  242. /* "private" */ MS_PRIVATE,
  243. /* "unbindable" */ MS_UNBINDABLE,
  244. /* "rshared" */ MS_SHARED|MS_RECURSIVE,
  245. /* "rslave" */ MS_SLAVE|MS_RECURSIVE,
  246. /* "rprivate" */ MS_PRIVATE|MS_RECURSIVE,
  247. /* "runbindable" */ MS_UNBINDABLE|MS_RECURSIVE,
  248. )
  249. // Always understood.
  250. /* "ro" */ MS_RDONLY, // vfs flag
  251. /* "rw" */ ~MS_RDONLY, // vfs flag
  252. /* "remount" */ MS_REMOUNT // action flag
  253. };
  254. static const char mount_option_str[] =
  255. IF_FEATURE_MOUNT_LOOP(
  256. "loop\0"
  257. )
  258. IF_FEATURE_MOUNT_FSTAB(
  259. "defaults\0"
  260. // "quiet\0" - do not filter out, vfat wants to see it
  261. "noauto\0"
  262. "sw\0"
  263. "swap\0"
  264. IF_DESKTOP("user\0")
  265. IF_DESKTOP("users\0")
  266. "_netdev\0"
  267. IF_DESKTOP("comment=\0") /* systemd uses this in fstab */
  268. )
  269. IF_FEATURE_MOUNT_FLAGS(
  270. // vfs flags
  271. "nosuid\0"
  272. "suid\0"
  273. "dev\0"
  274. "nodev\0"
  275. "exec\0"
  276. "noexec\0"
  277. "sync\0"
  278. "dirsync\0"
  279. "async\0"
  280. "atime\0"
  281. "noatime\0"
  282. "diratime\0"
  283. "nodiratime\0"
  284. "mand\0"
  285. "nomand\0"
  286. "relatime\0"
  287. "norelatime\0"
  288. "strictatime\0"
  289. "loud\0"
  290. "rbind\0"
  291. // action flags
  292. "union\0"
  293. "bind\0"
  294. "move\0"
  295. "make-shared\0"
  296. "make-slave\0"
  297. "make-private\0"
  298. "make-unbindable\0"
  299. "make-rshared\0"
  300. "make-rslave\0"
  301. "make-rprivate\0"
  302. "make-runbindable\0"
  303. )
  304. // Always understood.
  305. "ro\0" // vfs flag
  306. "rw\0" // vfs flag
  307. "remount\0" // action flag
  308. ;
  309. struct globals {
  310. #if ENABLE_FEATURE_MOUNT_NFS
  311. smalluint nfs_mount_version;
  312. #endif
  313. #if ENABLE_FEATURE_MOUNT_VERBOSE
  314. unsigned verbose;
  315. #endif
  316. llist_t *fslist;
  317. char getmntent_buf[1];
  318. } FIX_ALIASING;
  319. enum { GETMNTENT_BUFSIZE = COMMON_BUFSIZE - offsetof(struct globals, getmntent_buf) };
  320. #define G (*(struct globals*)&bb_common_bufsiz1)
  321. #define nfs_mount_version (G.nfs_mount_version)
  322. #if ENABLE_FEATURE_MOUNT_VERBOSE
  323. #define verbose (G.verbose )
  324. #else
  325. #define verbose 0
  326. #endif
  327. #define fslist (G.fslist )
  328. #define getmntent_buf (G.getmntent_buf )
  329. #define INIT_G() do { } while (0)
  330. #if ENABLE_FEATURE_MTAB_SUPPORT
  331. /*
  332. * update_mtab_entry_on_move() is used to update entry in case of mount --move.
  333. * we are looking for existing entries mnt_dir which is equal to mnt_fsname of
  334. * input mntent and replace it by new one.
  335. */
  336. static void FAST_FUNC update_mtab_entry_on_move(const struct mntent *mp)
  337. {
  338. struct mntent *entries, *m;
  339. int i, count;
  340. FILE *mountTable;
  341. mountTable = setmntent(bb_path_mtab_file, "r");
  342. if (!mountTable) {
  343. bb_perror_msg(bb_path_mtab_file);
  344. return;
  345. }
  346. entries = NULL;
  347. count = 0;
  348. while ((m = getmntent(mountTable)) != NULL) {
  349. entries = xrealloc_vector(entries, 3, count);
  350. entries[count].mnt_fsname = xstrdup(m->mnt_fsname);
  351. entries[count].mnt_dir = xstrdup(m->mnt_dir);
  352. entries[count].mnt_type = xstrdup(m->mnt_type);
  353. entries[count].mnt_opts = xstrdup(m->mnt_opts);
  354. entries[count].mnt_freq = m->mnt_freq;
  355. entries[count].mnt_passno = m->mnt_passno;
  356. count++;
  357. }
  358. endmntent(mountTable);
  359. mountTable = setmntent(bb_path_mtab_file, "w");
  360. if (mountTable) {
  361. for (i = 0; i < count; i++) {
  362. if (strcmp(entries[i].mnt_dir, mp->mnt_fsname) != 0)
  363. addmntent(mountTable, &entries[i]);
  364. else
  365. addmntent(mountTable, mp);
  366. }
  367. endmntent(mountTable);
  368. } else if (errno != EROFS)
  369. bb_perror_msg(bb_path_mtab_file);
  370. if (ENABLE_FEATURE_CLEAN_UP) {
  371. for (i = 0; i < count; i++) {
  372. free(entries[i].mnt_fsname);
  373. free(entries[i].mnt_dir);
  374. free(entries[i].mnt_type);
  375. free(entries[i].mnt_opts);
  376. }
  377. free(entries);
  378. }
  379. }
  380. #endif
  381. #if ENABLE_FEATURE_MOUNT_VERBOSE
  382. static int verbose_mount(const char *source, const char *target,
  383. const char *filesystemtype,
  384. unsigned long mountflags, const void *data)
  385. {
  386. int rc;
  387. errno = 0;
  388. rc = mount(source, target, filesystemtype, mountflags, data);
  389. if (verbose >= 2)
  390. bb_perror_msg("mount('%s','%s','%s',0x%08lx,'%s'):%d",
  391. source, target, filesystemtype,
  392. mountflags, (char*)data, rc);
  393. return rc;
  394. }
  395. #else
  396. #define verbose_mount(...) mount(__VA_ARGS__)
  397. #endif
  398. // Append mount options to string
  399. static void append_mount_options(char **oldopts, const char *newopts)
  400. {
  401. if (*oldopts && **oldopts) {
  402. // Do not insert options which are already there
  403. while (newopts[0]) {
  404. char *p;
  405. int len = strlen(newopts);
  406. p = strchr(newopts, ',');
  407. if (p) len = p - newopts;
  408. p = *oldopts;
  409. while (1) {
  410. if (!strncmp(p, newopts, len)
  411. && (p[len] == ',' || p[len] == '\0'))
  412. goto skip;
  413. p = strchr(p,',');
  414. if (!p) break;
  415. p++;
  416. }
  417. p = xasprintf("%s,%.*s", *oldopts, len, newopts);
  418. free(*oldopts);
  419. *oldopts = p;
  420. skip:
  421. newopts += len;
  422. while (newopts[0] == ',') newopts++;
  423. }
  424. } else {
  425. if (ENABLE_FEATURE_CLEAN_UP) free(*oldopts);
  426. *oldopts = xstrdup(newopts);
  427. }
  428. }
  429. // Use the mount_options list to parse options into flags.
  430. // Also update list of unrecognized options if unrecognized != NULL
  431. static unsigned long parse_mount_options(char *options, char **unrecognized)
  432. {
  433. unsigned long flags = MS_SILENT;
  434. // Loop through options
  435. for (;;) {
  436. unsigned i;
  437. char *comma = strchr(options, ',');
  438. const char *option_str = mount_option_str;
  439. if (comma) *comma = '\0';
  440. // FIXME: use hasmntopt()
  441. // Find this option in mount_options
  442. for (i = 0; i < ARRAY_SIZE(mount_options); i++) {
  443. unsigned opt_len = strlen(option_str);
  444. if (strncasecmp(option_str, options, opt_len) == 0
  445. && (options[opt_len] == '\0'
  446. /* or is it "comment=" thingy in fstab? */
  447. IF_FEATURE_MOUNT_FSTAB(IF_DESKTOP( || option_str[opt_len-1] == '=' ))
  448. )
  449. ) {
  450. unsigned long fl = mount_options[i];
  451. if (fl & BB_MS_INVERTED_VALUE)
  452. flags &= fl;
  453. else
  454. flags |= fl;
  455. goto found;
  456. }
  457. option_str += opt_len + 1;
  458. }
  459. // We did not recognize this option.
  460. // If "unrecognized" is not NULL, append option there.
  461. // Note that we should not append *empty* option -
  462. // in this case we want to pass NULL, not "", to "data"
  463. // parameter of mount(2) syscall.
  464. // This is crucial for filesystems that don't accept
  465. // any arbitrary mount options, like cgroup fs:
  466. // "mount -t cgroup none /mnt"
  467. if (options[0] && unrecognized) {
  468. // Add it to strflags, to pass on to kernel
  469. char *p = *unrecognized;
  470. unsigned len = p ? strlen(p) : 0;
  471. *unrecognized = p = xrealloc(p, len + strlen(options) + 2);
  472. // Comma separated if it's not the first one
  473. if (len) p[len++] = ',';
  474. strcpy(p + len, options);
  475. }
  476. found:
  477. if (!comma)
  478. break;
  479. // Advance to next option
  480. *comma = ',';
  481. options = ++comma;
  482. }
  483. return flags;
  484. }
  485. // Return a list of all block device backed filesystems
  486. static llist_t *get_block_backed_filesystems(void)
  487. {
  488. static const char filesystems[2][sizeof("/proc/filesystems")] = {
  489. "/etc/filesystems",
  490. "/proc/filesystems",
  491. };
  492. char *fs, *buf;
  493. llist_t *list = NULL;
  494. int i;
  495. FILE *f;
  496. for (i = 0; i < 2; i++) {
  497. f = fopen_for_read(filesystems[i]);
  498. if (!f) continue;
  499. while ((buf = xmalloc_fgetline(f)) != NULL) {
  500. if (strncmp(buf, "nodev", 5) == 0 && isspace(buf[5]))
  501. goto next;
  502. fs = skip_whitespace(buf);
  503. if (*fs == '#' || *fs == '*' || !*fs)
  504. goto next;
  505. llist_add_to_end(&list, xstrdup(fs));
  506. next:
  507. free(buf);
  508. }
  509. if (ENABLE_FEATURE_CLEAN_UP) fclose(f);
  510. }
  511. return list;
  512. }
  513. #if ENABLE_FEATURE_CLEAN_UP
  514. static void delete_block_backed_filesystems(void)
  515. {
  516. llist_free(fslist, free);
  517. }
  518. #else
  519. void delete_block_backed_filesystems(void);
  520. #endif
  521. // Perform actual mount of specific filesystem at specific location.
  522. // NB: mp->xxx fields may be trashed on exit
  523. static int mount_it_now(struct mntent *mp, unsigned long vfsflags, char *filteropts)
  524. {
  525. int rc = 0;
  526. if (FAKE_IT) {
  527. if (verbose >= 2)
  528. bb_error_msg("would do mount('%s','%s','%s',0x%08lx,'%s')",
  529. mp->mnt_fsname, mp->mnt_dir, mp->mnt_type,
  530. vfsflags, filteropts);
  531. goto mtab;
  532. }
  533. // Mount, with fallback to read-only if necessary.
  534. for (;;) {
  535. errno = 0;
  536. rc = verbose_mount(mp->mnt_fsname, mp->mnt_dir, mp->mnt_type,
  537. vfsflags, filteropts);
  538. // If mount failed, try
  539. // helper program mount.<mnt_type>
  540. if (HELPERS_ALLOWED && rc && mp->mnt_type) {
  541. char *args[8];
  542. int errno_save = errno;
  543. args[0] = xasprintf("mount.%s", mp->mnt_type);
  544. rc = 1;
  545. if (FAKE_IT)
  546. args[rc++] = (char *)"-f";
  547. if (ENABLE_FEATURE_MTAB_SUPPORT && !USE_MTAB)
  548. args[rc++] = (char *)"-n";
  549. args[rc++] = mp->mnt_fsname;
  550. args[rc++] = mp->mnt_dir;
  551. if (filteropts) {
  552. args[rc++] = (char *)"-o";
  553. args[rc++] = filteropts;
  554. }
  555. args[rc] = NULL;
  556. rc = spawn_and_wait(args);
  557. free(args[0]);
  558. if (!rc)
  559. break;
  560. errno = errno_save;
  561. }
  562. if (!rc || (vfsflags & MS_RDONLY) || (errno != EACCES && errno != EROFS))
  563. break;
  564. if (!(vfsflags & MS_SILENT))
  565. bb_error_msg("%s is write-protected, mounting read-only",
  566. mp->mnt_fsname);
  567. vfsflags |= MS_RDONLY;
  568. }
  569. // Abort entirely if permission denied.
  570. if (rc && errno == EPERM)
  571. bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
  572. // If the mount was successful, and we're maintaining an old-style
  573. // mtab file by hand, add the new entry to it now.
  574. mtab:
  575. if (USE_MTAB && !rc && !(vfsflags & MS_REMOUNT)) {
  576. char *fsname;
  577. FILE *mountTable = setmntent(bb_path_mtab_file, "a+");
  578. const char *option_str = mount_option_str;
  579. int i;
  580. if (!mountTable) {
  581. bb_perror_msg(bb_path_mtab_file);
  582. goto ret;
  583. }
  584. // Add vfs string flags
  585. for (i = 0; mount_options[i] != MS_REMOUNT; i++) {
  586. if (mount_options[i] > 0 && (mount_options[i] & vfsflags))
  587. append_mount_options(&(mp->mnt_opts), option_str);
  588. option_str += strlen(option_str) + 1;
  589. }
  590. // Remove trailing / (if any) from directory we mounted on
  591. i = strlen(mp->mnt_dir) - 1;
  592. while (i > 0 && mp->mnt_dir[i] == '/')
  593. mp->mnt_dir[i--] = '\0';
  594. // Convert to canonical pathnames as needed
  595. mp->mnt_dir = bb_simplify_path(mp->mnt_dir);
  596. fsname = NULL;
  597. if (!mp->mnt_type || !*mp->mnt_type) { // bind mount
  598. mp->mnt_fsname = fsname = bb_simplify_path(mp->mnt_fsname);
  599. mp->mnt_type = (char*)"bind";
  600. }
  601. mp->mnt_freq = mp->mnt_passno = 0;
  602. // Write and close
  603. #if ENABLE_FEATURE_MTAB_SUPPORT
  604. if (vfsflags & MS_MOVE)
  605. update_mtab_entry_on_move(mp);
  606. else
  607. #endif
  608. addmntent(mountTable, mp);
  609. endmntent(mountTable);
  610. if (ENABLE_FEATURE_CLEAN_UP) {
  611. free(mp->mnt_dir);
  612. free(fsname);
  613. }
  614. }
  615. ret:
  616. return rc;
  617. }
  618. #if ENABLE_FEATURE_MOUNT_NFS
  619. /*
  620. * Linux NFS mount
  621. * Copyright (C) 1993 Rick Sladkey <jrs@world.std.com>
  622. *
  623. * Licensed under GPLv2, see file LICENSE in this source tree.
  624. *
  625. * Wed Feb 8 12:51:48 1995, biro@yggdrasil.com (Ross Biro): allow all port
  626. * numbers to be specified on the command line.
  627. *
  628. * Fri, 8 Mar 1996 18:01:39, Swen Thuemmler <swen@uni-paderborn.de>:
  629. * Omit the call to connect() for Linux version 1.3.11 or later.
  630. *
  631. * Wed Oct 1 23:55:28 1997: Dick Streefland <dick_streefland@tasking.com>
  632. * Implemented the "bg", "fg" and "retry" mount options for NFS.
  633. *
  634. * 1999-02-22 Arkadiusz Mickiewicz <misiek@misiek.eu.org>
  635. * - added Native Language Support
  636. *
  637. * Modified by Olaf Kirch and Trond Myklebust for new NFS code,
  638. * plus NFSv3 stuff.
  639. */
  640. #define MOUNTPORT 635
  641. #define MNTPATHLEN 1024
  642. #define MNTNAMLEN 255
  643. #define FHSIZE 32
  644. #define FHSIZE3 64
  645. typedef char fhandle[FHSIZE];
  646. typedef struct {
  647. unsigned int fhandle3_len;
  648. char *fhandle3_val;
  649. } fhandle3;
  650. enum mountstat3 {
  651. MNT_OK = 0,
  652. MNT3ERR_PERM = 1,
  653. MNT3ERR_NOENT = 2,
  654. MNT3ERR_IO = 5,
  655. MNT3ERR_ACCES = 13,
  656. MNT3ERR_NOTDIR = 20,
  657. MNT3ERR_INVAL = 22,
  658. MNT3ERR_NAMETOOLONG = 63,
  659. MNT3ERR_NOTSUPP = 10004,
  660. MNT3ERR_SERVERFAULT = 10006,
  661. };
  662. typedef enum mountstat3 mountstat3;
  663. struct fhstatus {
  664. unsigned int fhs_status;
  665. union {
  666. fhandle fhs_fhandle;
  667. } fhstatus_u;
  668. };
  669. typedef struct fhstatus fhstatus;
  670. struct mountres3_ok {
  671. fhandle3 fhandle;
  672. struct {
  673. unsigned int auth_flavours_len;
  674. char *auth_flavours_val;
  675. } auth_flavours;
  676. };
  677. typedef struct mountres3_ok mountres3_ok;
  678. struct mountres3 {
  679. mountstat3 fhs_status;
  680. union {
  681. mountres3_ok mountinfo;
  682. } mountres3_u;
  683. };
  684. typedef struct mountres3 mountres3;
  685. typedef char *dirpath;
  686. typedef char *name;
  687. typedef struct mountbody *mountlist;
  688. struct mountbody {
  689. name ml_hostname;
  690. dirpath ml_directory;
  691. mountlist ml_next;
  692. };
  693. typedef struct mountbody mountbody;
  694. typedef struct groupnode *groups;
  695. struct groupnode {
  696. name gr_name;
  697. groups gr_next;
  698. };
  699. typedef struct groupnode groupnode;
  700. typedef struct exportnode *exports;
  701. struct exportnode {
  702. dirpath ex_dir;
  703. groups ex_groups;
  704. exports ex_next;
  705. };
  706. typedef struct exportnode exportnode;
  707. struct ppathcnf {
  708. int pc_link_max;
  709. short pc_max_canon;
  710. short pc_max_input;
  711. short pc_name_max;
  712. short pc_path_max;
  713. short pc_pipe_buf;
  714. uint8_t pc_vdisable;
  715. char pc_xxx;
  716. short pc_mask[2];
  717. };
  718. typedef struct ppathcnf ppathcnf;
  719. #define MOUNTPROG 100005
  720. #define MOUNTVERS 1
  721. #define MOUNTPROC_NULL 0
  722. #define MOUNTPROC_MNT 1
  723. #define MOUNTPROC_DUMP 2
  724. #define MOUNTPROC_UMNT 3
  725. #define MOUNTPROC_UMNTALL 4
  726. #define MOUNTPROC_EXPORT 5
  727. #define MOUNTPROC_EXPORTALL 6
  728. #define MOUNTVERS_POSIX 2
  729. #define MOUNTPROC_PATHCONF 7
  730. #define MOUNT_V3 3
  731. #define MOUNTPROC3_NULL 0
  732. #define MOUNTPROC3_MNT 1
  733. #define MOUNTPROC3_DUMP 2
  734. #define MOUNTPROC3_UMNT 3
  735. #define MOUNTPROC3_UMNTALL 4
  736. #define MOUNTPROC3_EXPORT 5
  737. enum {
  738. #ifndef NFS_FHSIZE
  739. NFS_FHSIZE = 32,
  740. #endif
  741. #ifndef NFS_PORT
  742. NFS_PORT = 2049
  743. #endif
  744. };
  745. /*
  746. * We want to be able to compile mount on old kernels in such a way
  747. * that the binary will work well on more recent kernels.
  748. * Thus, if necessary we teach nfsmount.c the structure of new fields
  749. * that will come later.
  750. *
  751. * Moreover, the new kernel includes conflict with glibc includes
  752. * so it is easiest to ignore the kernel altogether (at compile time).
  753. */
  754. struct nfs2_fh {
  755. char data[32];
  756. };
  757. struct nfs3_fh {
  758. unsigned short size;
  759. unsigned char data[64];
  760. };
  761. struct nfs_mount_data {
  762. int version; /* 1 */
  763. int fd; /* 1 */
  764. struct nfs2_fh old_root; /* 1 */
  765. int flags; /* 1 */
  766. int rsize; /* 1 */
  767. int wsize; /* 1 */
  768. int timeo; /* 1 */
  769. int retrans; /* 1 */
  770. int acregmin; /* 1 */
  771. int acregmax; /* 1 */
  772. int acdirmin; /* 1 */
  773. int acdirmax; /* 1 */
  774. struct sockaddr_in addr; /* 1 */
  775. char hostname[256]; /* 1 */
  776. int namlen; /* 2 */
  777. unsigned int bsize; /* 3 */
  778. struct nfs3_fh root; /* 4 */
  779. };
  780. /* bits in the flags field */
  781. enum {
  782. NFS_MOUNT_SOFT = 0x0001, /* 1 */
  783. NFS_MOUNT_INTR = 0x0002, /* 1 */
  784. NFS_MOUNT_SECURE = 0x0004, /* 1 */
  785. NFS_MOUNT_POSIX = 0x0008, /* 1 */
  786. NFS_MOUNT_NOCTO = 0x0010, /* 1 */
  787. NFS_MOUNT_NOAC = 0x0020, /* 1 */
  788. NFS_MOUNT_TCP = 0x0040, /* 2 */
  789. NFS_MOUNT_VER3 = 0x0080, /* 3 */
  790. NFS_MOUNT_KERBEROS = 0x0100, /* 3 */
  791. NFS_MOUNT_NONLM = 0x0200, /* 3 */
  792. NFS_MOUNT_NOACL = 0x0800, /* 4 */
  793. NFS_MOUNT_NORDIRPLUS = 0x4000
  794. };
  795. /*
  796. * We need to translate between nfs status return values and
  797. * the local errno values which may not be the same.
  798. *
  799. * Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>: change errno:
  800. * "after #include <errno.h> the symbol errno is reserved for any use,
  801. * it cannot even be used as a struct tag or field name".
  802. */
  803. #ifndef EDQUOT
  804. # define EDQUOT ENOSPC
  805. #endif
  806. /* Convert each NFSERR_BLAH into EBLAH */
  807. static const uint8_t nfs_err_stat[] = {
  808. 1, 2, 5, 6, 13, 17,
  809. 19, 20, 21, 22, 27, 28,
  810. 30, 63, 66, 69, 70, 71
  811. };
  812. #if ( \
  813. EPERM | ENOENT | EIO | ENXIO | EACCES| EEXIST | \
  814. ENODEV| ENOTDIR | EISDIR | EINVAL| EFBIG | ENOSPC | \
  815. EROFS | ENAMETOOLONG| ENOTEMPTY| EDQUOT| ESTALE| EREMOTE) < 256
  816. typedef uint8_t nfs_err_type;
  817. #else
  818. typedef uint16_t nfs_err_type;
  819. #endif
  820. static const nfs_err_type nfs_err_errnum[] = {
  821. EPERM , ENOENT , EIO , ENXIO , EACCES, EEXIST,
  822. ENODEV, ENOTDIR , EISDIR , EINVAL, EFBIG , ENOSPC,
  823. EROFS , ENAMETOOLONG, ENOTEMPTY, EDQUOT, ESTALE, EREMOTE
  824. };
  825. static char *nfs_strerror(int status)
  826. {
  827. int i;
  828. for (i = 0; i < ARRAY_SIZE(nfs_err_stat); i++) {
  829. if (nfs_err_stat[i] == status)
  830. return strerror(nfs_err_errnum[i]);
  831. }
  832. return xasprintf("unknown nfs status return value: %d", status);
  833. }
  834. static bool_t xdr_fhandle(XDR *xdrs, fhandle objp)
  835. {
  836. return xdr_opaque(xdrs, objp, FHSIZE);
  837. }
  838. static bool_t xdr_fhstatus(XDR *xdrs, fhstatus *objp)
  839. {
  840. if (!xdr_u_int(xdrs, &objp->fhs_status))
  841. return FALSE;
  842. if (objp->fhs_status == 0)
  843. return xdr_fhandle(xdrs, objp->fhstatus_u.fhs_fhandle);
  844. return TRUE;
  845. }
  846. static bool_t xdr_dirpath(XDR *xdrs, dirpath *objp)
  847. {
  848. return xdr_string(xdrs, objp, MNTPATHLEN);
  849. }
  850. static bool_t xdr_fhandle3(XDR *xdrs, fhandle3 *objp)
  851. {
  852. return xdr_bytes(xdrs, (char **)&objp->fhandle3_val,
  853. (unsigned int *) &objp->fhandle3_len,
  854. FHSIZE3);
  855. }
  856. static bool_t xdr_mountres3_ok(XDR *xdrs, mountres3_ok *objp)
  857. {
  858. if (!xdr_fhandle3(xdrs, &objp->fhandle))
  859. return FALSE;
  860. return xdr_array(xdrs, &(objp->auth_flavours.auth_flavours_val),
  861. &(objp->auth_flavours.auth_flavours_len),
  862. ~0,
  863. sizeof(int),
  864. (xdrproc_t) xdr_int);
  865. }
  866. static bool_t xdr_mountstat3(XDR *xdrs, mountstat3 *objp)
  867. {
  868. return xdr_enum(xdrs, (enum_t *) objp);
  869. }
  870. static bool_t xdr_mountres3(XDR *xdrs, mountres3 *objp)
  871. {
  872. if (!xdr_mountstat3(xdrs, &objp->fhs_status))
  873. return FALSE;
  874. if (objp->fhs_status == MNT_OK)
  875. return xdr_mountres3_ok(xdrs, &objp->mountres3_u.mountinfo);
  876. return TRUE;
  877. }
  878. #define MAX_NFSPROT ((nfs_mount_version >= 4) ? 3 : 2)
  879. /*
  880. * Unfortunately, the kernel prints annoying console messages
  881. * in case of an unexpected nfs mount version (instead of
  882. * just returning some error). Therefore we'll have to try
  883. * and figure out what version the kernel expects.
  884. *
  885. * Variables:
  886. * KERNEL_NFS_MOUNT_VERSION: kernel sources at compile time
  887. * NFS_MOUNT_VERSION: these nfsmount sources at compile time
  888. * nfs_mount_version: version this source and running kernel can handle
  889. */
  890. static void
  891. find_kernel_nfs_mount_version(void)
  892. {
  893. int kernel_version;
  894. if (nfs_mount_version)
  895. return;
  896. nfs_mount_version = 4; /* default */
  897. kernel_version = get_linux_version_code();
  898. if (kernel_version) {
  899. if (kernel_version < KERNEL_VERSION(2,2,18))
  900. nfs_mount_version = 3;
  901. /* else v4 since 2.3.99pre4 */
  902. }
  903. }
  904. static void
  905. get_mountport(struct pmap *pm_mnt,
  906. struct sockaddr_in *server_addr,
  907. long unsigned prog,
  908. long unsigned version,
  909. long unsigned proto,
  910. long unsigned port)
  911. {
  912. struct pmaplist *pmap;
  913. server_addr->sin_port = PMAPPORT;
  914. /* glibc 2.4 (still) has pmap_getmaps(struct sockaddr_in *).
  915. * I understand it like "IPv6 for this is not 100% ready" */
  916. pmap = pmap_getmaps(server_addr);
  917. if (version > MAX_NFSPROT)
  918. version = MAX_NFSPROT;
  919. if (!prog)
  920. prog = MOUNTPROG;
  921. pm_mnt->pm_prog = prog;
  922. pm_mnt->pm_vers = version;
  923. pm_mnt->pm_prot = proto;
  924. pm_mnt->pm_port = port;
  925. while (pmap) {
  926. if (pmap->pml_map.pm_prog != prog)
  927. goto next;
  928. if (!version && pm_mnt->pm_vers > pmap->pml_map.pm_vers)
  929. goto next;
  930. if (version > 2 && pmap->pml_map.pm_vers != version)
  931. goto next;
  932. if (version && version <= 2 && pmap->pml_map.pm_vers > 2)
  933. goto next;
  934. if (pmap->pml_map.pm_vers > MAX_NFSPROT
  935. || (proto && pm_mnt->pm_prot && pmap->pml_map.pm_prot != proto)
  936. || (port && pmap->pml_map.pm_port != port)
  937. ) {
  938. goto next;
  939. }
  940. memcpy(pm_mnt, &pmap->pml_map, sizeof(*pm_mnt));
  941. next:
  942. pmap = pmap->pml_next;
  943. }
  944. if (!pm_mnt->pm_vers)
  945. pm_mnt->pm_vers = MOUNTVERS;
  946. if (!pm_mnt->pm_port)
  947. pm_mnt->pm_port = MOUNTPORT;
  948. if (!pm_mnt->pm_prot)
  949. pm_mnt->pm_prot = IPPROTO_TCP;
  950. }
  951. #if BB_MMU
  952. static int daemonize(void)
  953. {
  954. int pid = fork();
  955. if (pid < 0) /* error */
  956. return -errno;
  957. if (pid > 0) /* parent */
  958. return 0;
  959. /* child */
  960. close(0);
  961. xopen(bb_dev_null, O_RDWR);
  962. xdup2(0, 1);
  963. xdup2(0, 2);
  964. setsid();
  965. openlog(applet_name, LOG_PID, LOG_DAEMON);
  966. logmode = LOGMODE_SYSLOG;
  967. return 1;
  968. }
  969. #else
  970. static inline int daemonize(void) { return -ENOSYS; }
  971. #endif
  972. /* TODO */
  973. static inline int we_saw_this_host_before(const char *hostname UNUSED_PARAM)
  974. {
  975. return 0;
  976. }
  977. /* RPC strerror analogs are terminally idiotic:
  978. * *mandatory* prefix and \n at end.
  979. * This hopefully helps. Usage:
  980. * error_msg_rpc(clnt_*error*(" ")) */
  981. static void error_msg_rpc(const char *msg)
  982. {
  983. int len;
  984. while (msg[0] == ' ' || msg[0] == ':') msg++;
  985. len = strlen(msg);
  986. while (len && msg[len-1] == '\n') len--;
  987. bb_error_msg("%.*s", len, msg);
  988. }
  989. /* NB: mp->xxx fields may be trashed on exit */
  990. static NOINLINE int nfsmount(struct mntent *mp, unsigned long vfsflags, char *filteropts)
  991. {
  992. CLIENT *mclient;
  993. char *hostname;
  994. char *pathname;
  995. char *mounthost;
  996. /* prior to 2.6.23, kernel took NFS options in a form of this struct
  997. * only. 2.6.23+ looks at data->version, and if it's not 1..6,
  998. * then data pointer is interpreted as a string. */
  999. struct nfs_mount_data data;
  1000. char *opt;
  1001. struct hostent *hp;
  1002. struct sockaddr_in server_addr;
  1003. struct sockaddr_in mount_server_addr;
  1004. int msock, fsock;
  1005. union {
  1006. struct fhstatus nfsv2;
  1007. struct mountres3 nfsv3;
  1008. } status;
  1009. int daemonized;
  1010. char *s;
  1011. int port;
  1012. int mountport;
  1013. int proto;
  1014. #if BB_MMU
  1015. smallint bg = 0;
  1016. #else
  1017. enum { bg = 0 };
  1018. #endif
  1019. int retry;
  1020. int mountprog;
  1021. int mountvers;
  1022. int nfsprog;
  1023. int nfsvers;
  1024. int retval;
  1025. /* these all are one-bit really. gcc 4.3.1 likes this combination: */
  1026. smallint tcp;
  1027. smallint soft;
  1028. int intr;
  1029. int posix;
  1030. int nocto;
  1031. int noac;
  1032. int nordirplus;
  1033. int nolock;
  1034. int noacl;
  1035. find_kernel_nfs_mount_version();
  1036. daemonized = 0;
  1037. mounthost = NULL;
  1038. retval = ETIMEDOUT;
  1039. msock = fsock = -1;
  1040. mclient = NULL;
  1041. /* NB: hostname, mounthost, filteropts must be free()d prior to return */
  1042. filteropts = xstrdup(filteropts); /* going to trash it later... */
  1043. hostname = xstrdup(mp->mnt_fsname);
  1044. /* mount_main() guarantees that ':' is there */
  1045. s = strchr(hostname, ':');
  1046. pathname = s + 1;
  1047. *s = '\0';
  1048. /* Ignore all but first hostname in replicated mounts
  1049. * until they can be fully supported. (mack@sgi.com) */
  1050. s = strchr(hostname, ',');
  1051. if (s) {
  1052. *s = '\0';
  1053. bb_error_msg("warning: multiple hostnames not supported");
  1054. }
  1055. server_addr.sin_family = AF_INET;
  1056. if (!inet_aton(hostname, &server_addr.sin_addr)) {
  1057. hp = gethostbyname(hostname);
  1058. if (hp == NULL) {
  1059. bb_herror_msg("%s", hostname);
  1060. goto fail;
  1061. }
  1062. if (hp->h_length != (int)sizeof(struct in_addr)) {
  1063. bb_error_msg_and_die("only IPv4 is supported");
  1064. }
  1065. memcpy(&server_addr.sin_addr, hp->h_addr_list[0], sizeof(struct in_addr));
  1066. }
  1067. memcpy(&mount_server_addr, &server_addr, sizeof(mount_server_addr));
  1068. /* add IP address to mtab options for use when unmounting */
  1069. if (!mp->mnt_opts) { /* TODO: actually mp->mnt_opts is never NULL */
  1070. mp->mnt_opts = xasprintf("addr=%s", inet_ntoa(server_addr.sin_addr));
  1071. } else {
  1072. char *tmp = xasprintf("%s%saddr=%s", mp->mnt_opts,
  1073. mp->mnt_opts[0] ? "," : "",
  1074. inet_ntoa(server_addr.sin_addr));
  1075. free(mp->mnt_opts);
  1076. mp->mnt_opts = tmp;
  1077. }
  1078. /* Set default options.
  1079. * rsize/wsize (and bsize, for ver >= 3) are left 0 in order to
  1080. * let the kernel decide.
  1081. * timeo is filled in after we know whether it'll be TCP or UDP. */
  1082. memset(&data, 0, sizeof(data));
  1083. data.retrans = 3;
  1084. data.acregmin = 3;
  1085. data.acregmax = 60;
  1086. data.acdirmin = 30;
  1087. data.acdirmax = 60;
  1088. data.namlen = NAME_MAX;
  1089. soft = 0;
  1090. intr = 0;
  1091. posix = 0;
  1092. nocto = 0;
  1093. nolock = 0;
  1094. noac = 0;
  1095. nordirplus = 0;
  1096. noacl = 0;
  1097. retry = 10000; /* 10000 minutes ~ 1 week */
  1098. tcp = 1; /* nfs-utils uses tcp per default */
  1099. mountprog = MOUNTPROG;
  1100. mountvers = 0;
  1101. port = 0;
  1102. mountport = 0;
  1103. nfsprog = 100003;
  1104. nfsvers = 0;
  1105. /* parse options */
  1106. if (filteropts) for (opt = strtok(filteropts, ","); opt; opt = strtok(NULL, ",")) {
  1107. char *opteq = strchr(opt, '=');
  1108. if (opteq) {
  1109. int val, idx;
  1110. static const char options[] ALIGN1 =
  1111. /* 0 */ "rsize\0"
  1112. /* 1 */ "wsize\0"
  1113. /* 2 */ "timeo\0"
  1114. /* 3 */ "retrans\0"
  1115. /* 4 */ "acregmin\0"
  1116. /* 5 */ "acregmax\0"
  1117. /* 6 */ "acdirmin\0"
  1118. /* 7 */ "acdirmax\0"
  1119. /* 8 */ "actimeo\0"
  1120. /* 9 */ "retry\0"
  1121. /* 10 */ "port\0"
  1122. /* 11 */ "mountport\0"
  1123. /* 12 */ "mounthost\0"
  1124. /* 13 */ "mountprog\0"
  1125. /* 14 */ "mountvers\0"
  1126. /* 15 */ "nfsprog\0"
  1127. /* 16 */ "nfsvers\0"
  1128. /* 17 */ "vers\0"
  1129. /* 18 */ "proto\0"
  1130. /* 19 */ "namlen\0"
  1131. /* 20 */ "addr\0";
  1132. *opteq++ = '\0';
  1133. idx = index_in_strings(options, opt);
  1134. switch (idx) {
  1135. case 12: // "mounthost"
  1136. mounthost = xstrndup(opteq,
  1137. strcspn(opteq, " \t\n\r,"));
  1138. continue;
  1139. case 18: // "proto"
  1140. if (!strncmp(opteq, "tcp", 3))
  1141. tcp = 1;
  1142. else if (!strncmp(opteq, "udp", 3))
  1143. tcp = 0;
  1144. else
  1145. bb_error_msg("warning: unrecognized proto= option");
  1146. continue;
  1147. case 20: // "addr" - ignore
  1148. continue;
  1149. case -1: // unknown
  1150. if (vfsflags & MS_REMOUNT)
  1151. continue;
  1152. }
  1153. val = xatoi_positive(opteq);
  1154. switch (idx) {
  1155. case 0: // "rsize"
  1156. data.rsize = val;
  1157. continue;
  1158. case 1: // "wsize"
  1159. data.wsize = val;
  1160. continue;
  1161. case 2: // "timeo"
  1162. data.timeo = val;
  1163. continue;
  1164. case 3: // "retrans"
  1165. data.retrans = val;
  1166. continue;
  1167. case 4: // "acregmin"
  1168. data.acregmin = val;
  1169. continue;
  1170. case 5: // "acregmax"
  1171. data.acregmax = val;
  1172. continue;
  1173. case 6: // "acdirmin"
  1174. data.acdirmin = val;
  1175. continue;
  1176. case 7: // "acdirmax"
  1177. data.acdirmax = val;
  1178. continue;
  1179. case 8: // "actimeo"
  1180. data.acregmin = val;
  1181. data.acregmax = val;
  1182. data.acdirmin = val;
  1183. data.acdirmax = val;
  1184. continue;
  1185. case 9: // "retry"
  1186. retry = val;
  1187. continue;
  1188. case 10: // "port"
  1189. port = val;
  1190. continue;
  1191. case 11: // "mountport"
  1192. mountport = val;
  1193. continue;
  1194. case 13: // "mountprog"
  1195. mountprog = val;
  1196. continue;
  1197. case 14: // "mountvers"
  1198. mountvers = val;
  1199. continue;
  1200. case 15: // "nfsprog"
  1201. nfsprog = val;
  1202. continue;
  1203. case 16: // "nfsvers"
  1204. case 17: // "vers"
  1205. nfsvers = val;
  1206. continue;
  1207. case 19: // "namlen"
  1208. //if (nfs_mount_version >= 2)
  1209. data.namlen = val;
  1210. //else
  1211. // bb_error_msg("warning: option namlen is not supported\n");
  1212. continue;
  1213. default:
  1214. bb_error_msg("unknown nfs mount parameter: %s=%d", opt, val);
  1215. goto fail;
  1216. }
  1217. }
  1218. else { /* not of the form opt=val */
  1219. static const char options[] ALIGN1 =
  1220. "bg\0"
  1221. "fg\0"
  1222. "soft\0"
  1223. "hard\0"
  1224. "intr\0"
  1225. "posix\0"
  1226. "cto\0"
  1227. "ac\0"
  1228. "tcp\0"
  1229. "udp\0"
  1230. "lock\0"
  1231. "rdirplus\0"
  1232. "acl\0";
  1233. int val = 1;
  1234. if (!strncmp(opt, "no", 2)) {
  1235. val = 0;
  1236. opt += 2;
  1237. }
  1238. switch (index_in_strings(options, opt)) {
  1239. case 0: // "bg"
  1240. #if BB_MMU
  1241. bg = val;
  1242. #endif
  1243. break;
  1244. case 1: // "fg"
  1245. #if BB_MMU
  1246. bg = !val;
  1247. #endif
  1248. break;
  1249. case 2: // "soft"
  1250. soft = val;
  1251. break;
  1252. case 3: // "hard"
  1253. soft = !val;
  1254. break;
  1255. case 4: // "intr"
  1256. intr = val;
  1257. break;
  1258. case 5: // "posix"
  1259. posix = val;
  1260. break;
  1261. case 6: // "cto"
  1262. nocto = !val;
  1263. break;
  1264. case 7: // "ac"
  1265. noac = !val;
  1266. break;
  1267. case 8: // "tcp"
  1268. tcp = val;
  1269. break;
  1270. case 9: // "udp"
  1271. tcp = !val;
  1272. break;
  1273. case 10: // "lock"
  1274. if (nfs_mount_version >= 3)
  1275. nolock = !val;
  1276. else
  1277. bb_error_msg("warning: option nolock is not supported");
  1278. break;
  1279. case 11: //rdirplus
  1280. nordirplus = !val;
  1281. break;
  1282. case 12: // acl
  1283. noacl = !val;
  1284. break;
  1285. default:
  1286. bb_error_msg("unknown nfs mount option: %s%s", val ? "" : "no", opt);
  1287. goto fail;
  1288. }
  1289. }
  1290. }
  1291. proto = (tcp) ? IPPROTO_TCP : IPPROTO_UDP;
  1292. data.flags = (soft ? NFS_MOUNT_SOFT : 0)
  1293. | (intr ? NFS_MOUNT_INTR : 0)
  1294. | (posix ? NFS_MOUNT_POSIX : 0)
  1295. | (nocto ? NFS_MOUNT_NOCTO : 0)
  1296. | (noac ? NFS_MOUNT_NOAC : 0)
  1297. | (nordirplus ? NFS_MOUNT_NORDIRPLUS : 0)
  1298. | (noacl ? NFS_MOUNT_NOACL : 0);
  1299. if (nfs_mount_version >= 2)
  1300. data.flags |= (tcp ? NFS_MOUNT_TCP : 0);
  1301. if (nfs_mount_version >= 3)
  1302. data.flags |= (nolock ? NFS_MOUNT_NONLM : 0);
  1303. if (nfsvers > MAX_NFSPROT || mountvers > MAX_NFSPROT) {
  1304. bb_error_msg("NFSv%d not supported", nfsvers);
  1305. goto fail;
  1306. }
  1307. if (nfsvers && !mountvers)
  1308. mountvers = (nfsvers < 3) ? 1 : nfsvers;
  1309. if (nfsvers && nfsvers < mountvers) {
  1310. mountvers = nfsvers;
  1311. }
  1312. /* Adjust options if none specified */
  1313. if (!data.timeo)
  1314. data.timeo = tcp ? 70 : 7;
  1315. data.version = nfs_mount_version;
  1316. if (vfsflags & MS_REMOUNT)
  1317. goto do_mount;
  1318. /*
  1319. * If the previous mount operation on the same host was
  1320. * backgrounded, and the "bg" for this mount is also set,
  1321. * give up immediately, to avoid the initial timeout.
  1322. */
  1323. if (bg && we_saw_this_host_before(hostname)) {
  1324. daemonized = daemonize();
  1325. if (daemonized <= 0) { /* parent or error */
  1326. retval = -daemonized;
  1327. goto ret;
  1328. }
  1329. }
  1330. /* Create mount daemon client */
  1331. /* See if the nfs host = mount host. */
  1332. if (mounthost) {
  1333. if (mounthost[0] >= '0' && mounthost[0] <= '9') {
  1334. mount_server_addr.sin_family = AF_INET;
  1335. mount_server_addr.sin_addr.s_addr = inet_addr(hostname);
  1336. } else {
  1337. hp = gethostbyname(mounthost);
  1338. if (hp == NULL) {
  1339. bb_herror_msg("%s", mounthost);
  1340. goto fail;
  1341. }
  1342. if (hp->h_length != (int)sizeof(struct in_addr)) {
  1343. bb_error_msg_and_die("only IPv4 is supported");
  1344. }
  1345. mount_server_addr.sin_family = AF_INET;
  1346. memcpy(&mount_server_addr.sin_addr, hp->h_addr_list[0], sizeof(struct in_addr));
  1347. }
  1348. }
  1349. /*
  1350. * The following loop implements the mount retries. When the mount
  1351. * times out, and the "bg" option is set, we background ourself
  1352. * and continue trying.
  1353. *
  1354. * The case where the mount point is not present and the "bg"
  1355. * option is set, is treated as a timeout. This is done to
  1356. * support nested mounts.
  1357. *
  1358. * The "retry" count specified by the user is the number of
  1359. * minutes to retry before giving up.
  1360. */
  1361. {
  1362. struct timeval total_timeout;
  1363. struct timeval retry_timeout;
  1364. struct pmap pm_mnt;
  1365. time_t t;
  1366. time_t prevt;
  1367. time_t timeout;
  1368. retry_timeout.tv_sec = 3;
  1369. retry_timeout.tv_usec = 0;
  1370. total_timeout.tv_sec = 20;
  1371. total_timeout.tv_usec = 0;
  1372. /* FIXME: use monotonic()? */
  1373. timeout = time(NULL) + 60 * retry;
  1374. prevt = 0;
  1375. t = 30;
  1376. retry:
  1377. /* Be careful not to use too many CPU cycles */
  1378. if (t - prevt < 30)
  1379. sleep(30);
  1380. get_mountport(&pm_mnt, &mount_server_addr,
  1381. mountprog,
  1382. mountvers,
  1383. proto,
  1384. mountport);
  1385. nfsvers = (pm_mnt.pm_vers < 2) ? 2 : pm_mnt.pm_vers;
  1386. /* contact the mount daemon via TCP */
  1387. mount_server_addr.sin_port = htons(pm_mnt.pm_port);
  1388. msock = RPC_ANYSOCK;
  1389. switch (pm_mnt.pm_prot) {
  1390. case IPPROTO_UDP:
  1391. mclient = clntudp_create(&mount_server_addr,
  1392. pm_mnt.pm_prog,
  1393. pm_mnt.pm_vers,
  1394. retry_timeout,
  1395. &msock);
  1396. if (mclient)
  1397. break;
  1398. mount_server_addr.sin_port = htons(pm_mnt.pm_port);
  1399. msock = RPC_ANYSOCK;
  1400. case IPPROTO_TCP:
  1401. mclient = clnttcp_create(&mount_server_addr,
  1402. pm_mnt.pm_prog,
  1403. pm_mnt.pm_vers,
  1404. &msock, 0, 0);
  1405. break;
  1406. default:
  1407. mclient = NULL;
  1408. }
  1409. if (!mclient) {
  1410. if (!daemonized && prevt == 0)
  1411. error_msg_rpc(clnt_spcreateerror(" "));
  1412. } else {
  1413. enum clnt_stat clnt_stat;
  1414. /* Try to mount hostname:pathname */
  1415. mclient->cl_auth = authunix_create_default();
  1416. /* Make pointers in xdr_mountres3 NULL so
  1417. * that xdr_array allocates memory for us
  1418. */
  1419. memset(&status, 0, sizeof(status));
  1420. if (pm_mnt.pm_vers == 3)
  1421. clnt_stat = clnt_call(mclient, MOUNTPROC3_MNT,
  1422. (xdrproc_t) xdr_dirpath,
  1423. (caddr_t) &pathname,
  1424. (xdrproc_t) xdr_mountres3,
  1425. (caddr_t) &status,
  1426. total_timeout);
  1427. else
  1428. clnt_stat = clnt_call(mclient, MOUNTPROC_MNT,
  1429. (xdrproc_t) xdr_dirpath,
  1430. (caddr_t) &pathname,
  1431. (xdrproc_t) xdr_fhstatus,
  1432. (caddr_t) &status,
  1433. total_timeout);
  1434. if (clnt_stat == RPC_SUCCESS)
  1435. goto prepare_kernel_data; /* we're done */
  1436. if (errno != ECONNREFUSED) {
  1437. error_msg_rpc(clnt_sperror(mclient, " "));
  1438. goto fail; /* don't retry */
  1439. }
  1440. /* Connection refused */
  1441. if (!daemonized && prevt == 0) /* print just once */
  1442. error_msg_rpc(clnt_sperror(mclient, " "));
  1443. auth_destroy(mclient->cl_auth);
  1444. clnt_destroy(mclient);
  1445. mclient = NULL;
  1446. close(msock);
  1447. msock = -1;
  1448. }
  1449. /* Timeout. We are going to retry... maybe */
  1450. if (!bg)
  1451. goto fail;
  1452. if (!daemonized) {
  1453. daemonized = daemonize();
  1454. if (daemonized <= 0) { /* parent or error */
  1455. retval = -daemonized;
  1456. goto ret;
  1457. }
  1458. }
  1459. prevt = t;
  1460. t = time(NULL);
  1461. if (t >= timeout)
  1462. /* TODO error message */
  1463. goto fail;
  1464. goto retry;
  1465. }
  1466. prepare_kernel_data:
  1467. if (nfsvers == 2) {
  1468. if (status.nfsv2.fhs_status != 0) {
  1469. bb_error_msg("%s:%s failed, reason given by server: %s",
  1470. hostname, pathname,
  1471. nfs_strerror(status.nfsv2.fhs_status));
  1472. goto fail;
  1473. }
  1474. memcpy(data.root.data,
  1475. (char *) status.nfsv2.fhstatus_u.fhs_fhandle,
  1476. NFS_FHSIZE);
  1477. data.root.size = NFS_FHSIZE;
  1478. memcpy(data.old_root.data,
  1479. (char *) status.nfsv2.fhstatus_u.fhs_fhandle,
  1480. NFS_FHSIZE);
  1481. } else {
  1482. fhandle3 *my_fhandle;
  1483. if (status.nfsv3.fhs_status != 0) {
  1484. bb_error_msg("%s:%s failed, reason given by server: %s",
  1485. hostname, pathname,
  1486. nfs_strerror(status.nfsv3.fhs_status));
  1487. goto fail;
  1488. }
  1489. my_fhandle = &status.nfsv3.mountres3_u.mountinfo.fhandle;
  1490. memset(data.old_root.data, 0, NFS_FHSIZE);
  1491. memset(&data.root, 0, sizeof(data.root));
  1492. data.root.size = my_fhandle->fhandle3_len;
  1493. memcpy(data.root.data,
  1494. (char *) my_fhandle->fhandle3_val,
  1495. my_fhandle->fhandle3_len);
  1496. data.flags |= NFS_MOUNT_VER3;
  1497. }
  1498. /* Create nfs socket for kernel */
  1499. if (tcp) {
  1500. if (nfs_mount_version < 3) {
  1501. bb_error_msg("NFS over TCP is not supported");
  1502. goto fail;
  1503. }
  1504. fsock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  1505. } else
  1506. fsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  1507. if (fsock < 0) {
  1508. bb_perror_msg("nfs socket");
  1509. goto fail;
  1510. }
  1511. if (bindresvport(fsock, 0) < 0) {
  1512. bb_perror_msg("nfs bindresvport");
  1513. goto fail;
  1514. }
  1515. if (port == 0) {
  1516. server_addr.sin_port = PMAPPORT;
  1517. port = pmap_getport(&server_addr, nfsprog, nfsvers,
  1518. tcp ? IPPROTO_TCP : IPPROTO_UDP);
  1519. if (port == 0)
  1520. port = NFS_PORT;
  1521. }
  1522. server_addr.sin_port = htons(port);
  1523. /* Prepare data structure for kernel */
  1524. data.fd = fsock;
  1525. memcpy((char *) &data.addr, (char *) &server_addr, sizeof(data.addr));
  1526. strncpy(data.hostname, hostname, sizeof(data.hostname));
  1527. /* Clean up */
  1528. auth_destroy(mclient->cl_auth);
  1529. clnt_destroy(mclient);
  1530. close(msock);
  1531. msock = -1;
  1532. if (bg) {
  1533. /* We must wait until mount directory is available */
  1534. struct stat statbuf;
  1535. int delay = 1;
  1536. while (stat(mp->mnt_dir, &statbuf) == -1) {
  1537. if (!daemonized) {
  1538. daemonized = daemonize();
  1539. if (daemonized <= 0) { /* parent or error */
  1540. /* FIXME: parent doesn't close fsock - ??! */
  1541. retval = -daemonized;
  1542. goto ret;
  1543. }
  1544. }
  1545. sleep(delay); /* 1, 2, 4, 8, 16, 30, ... */
  1546. delay *= 2;
  1547. if (delay > 30)
  1548. delay = 30;
  1549. }
  1550. }
  1551. /* Perform actual mount */
  1552. do_mount:
  1553. retval = mount_it_now(mp, vfsflags, (char*)&data);
  1554. goto ret;
  1555. /* Abort */
  1556. fail:
  1557. if (msock >= 0) {
  1558. if (mclient) {
  1559. auth_destroy(mclient->cl_auth);
  1560. clnt_destroy(mclient);
  1561. }
  1562. close(msock);
  1563. }
  1564. if (fsock >= 0)
  1565. close(fsock);
  1566. ret:
  1567. free(hostname);
  1568. free(mounthost);
  1569. free(filteropts);
  1570. return retval;
  1571. }
  1572. #else // !ENABLE_FEATURE_MOUNT_NFS
  1573. /* Linux 2.6.23+ supports nfs mounts with options passed as a string.
  1574. * For older kernels, you must build busybox with ENABLE_FEATURE_MOUNT_NFS.
  1575. * (However, note that then you lose any chances that NFS over IPv6 would work).
  1576. */
  1577. static int nfsmount(struct mntent *mp, unsigned long vfsflags, char *filteropts)
  1578. {
  1579. len_and_sockaddr *lsa;
  1580. char *opts;
  1581. char *end;
  1582. char *dotted;
  1583. int ret;
  1584. # if ENABLE_FEATURE_IPV6
  1585. end = strchr(mp->mnt_fsname, ']');
  1586. if (end && end[1] == ':')
  1587. end++;
  1588. else
  1589. # endif
  1590. /* mount_main() guarantees that ':' is there */
  1591. end = strchr(mp->mnt_fsname, ':');
  1592. *end = '\0';
  1593. lsa = xhost2sockaddr(mp->mnt_fsname, /*port:*/ 0);
  1594. *end = ':';
  1595. dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
  1596. if (ENABLE_FEATURE_CLEAN_UP) free(lsa);
  1597. opts = xasprintf("%s%saddr=%s",
  1598. filteropts ? filteropts : "",
  1599. filteropts ? "," : "",
  1600. dotted
  1601. );
  1602. if (ENABLE_FEATURE_CLEAN_UP) free(dotted);
  1603. ret = mount_it_now(mp, vfsflags, opts);
  1604. if (ENABLE_FEATURE_CLEAN_UP) free(opts);
  1605. return ret;
  1606. }
  1607. #endif // !ENABLE_FEATURE_MOUNT_NFS
  1608. // Mount one directory. Handles CIFS, NFS, loopback, autobind, and filesystem
  1609. // type detection. Returns 0 for success, nonzero for failure.
  1610. // NB: mp->xxx fields may be trashed on exit
  1611. static int singlemount(struct mntent *mp, int ignore_busy)
  1612. {
  1613. int rc = -1;
  1614. unsigned long vfsflags;
  1615. char *loopFile = NULL, *filteropts = NULL;
  1616. llist_t *fl = NULL;
  1617. struct stat st;
  1618. errno = 0;
  1619. vfsflags = parse_mount_options(mp->mnt_opts, &filteropts);
  1620. // Treat fstype "auto" as unspecified
  1621. if (mp->mnt_type && strcmp(mp->mnt_type, "auto") == 0)
  1622. mp->mnt_type = NULL;
  1623. // Might this be a virtual filesystem?
  1624. if (ENABLE_FEATURE_MOUNT_HELPERS && strchr(mp->mnt_fsname, '#')) {
  1625. char *args[35];
  1626. char *s;
  1627. int n;
  1628. // fsname: "cmd#arg1#arg2..."
  1629. // WARNING: allows execution of arbitrary commands!
  1630. // Try "mount 'sh#-c#sh' bogus_dir".
  1631. // It is safe ONLY because non-root
  1632. // cannot use two-argument mount command
  1633. // and using one-argument "mount 'sh#-c#sh'" doesn't work:
  1634. // "mount: can't find sh#-c#sh in /etc/fstab"
  1635. // (if /etc/fstab has it, it's ok: root sets up /etc/fstab).
  1636. s = mp->mnt_fsname;
  1637. n = 0;
  1638. args[n++] = s;
  1639. while (*s && n < 35 - 2) {
  1640. if (*s++ == '#' && *s != '#') {
  1641. s[-1] = '\0';
  1642. args[n++] = s;
  1643. }
  1644. }
  1645. args[n++] = mp->mnt_dir;
  1646. args[n] = NULL;
  1647. rc = spawn_and_wait(args);
  1648. goto report_error;
  1649. }
  1650. // Might this be an CIFS filesystem?
  1651. if (ENABLE_FEATURE_MOUNT_CIFS
  1652. && (!mp->mnt_type || strcmp(mp->mnt_type, "cifs") == 0)
  1653. && (mp->mnt_fsname[0] == '/' || mp->mnt_fsname[0] == '\\')
  1654. && mp->mnt_fsname[0] == mp->mnt_fsname[1]
  1655. ) {
  1656. int len;
  1657. char c;
  1658. char *hostname, *share;
  1659. char *dotted, *ip;
  1660. len_and_sockaddr *lsa;
  1661. // Parse mp->mnt_fsname of the form "//hostname/share[/dir1/dir2]"
  1662. hostname = mp->mnt_fsname + 2;
  1663. len = strcspn(hostname, "/\\");
  1664. share = hostname + len + 1;
  1665. if (len == 0 // 3rd char is a [back]slash (IOW: empty hostname)
  1666. || share[-1] == '\0' // no [back]slash after hostname
  1667. || share[0] == '\0' // empty share name
  1668. ) {
  1669. goto report_error;
  1670. }
  1671. c = share[-1];
  1672. share[-1] = '\0';
  1673. len = strcspn(share, "/\\");
  1674. // "unc=\\hostname\share" option is mandatory
  1675. // after CIFS option parsing was rewritten in Linux 3.4.
  1676. // Must use backslashes.
  1677. // If /dir1/dir2 is present, also add "prefixpath=dir1/dir2"
  1678. {
  1679. char *unc = xasprintf(
  1680. share[len] != '\0' /* "/dir1/dir2" exists? */
  1681. ? "unc=\\\\%s\\%.*s,prefixpath=%s"
  1682. : "unc=\\\\%s\\%.*s",
  1683. hostname,
  1684. len, share,
  1685. share + len + 1 /* "dir1/dir2" */
  1686. );
  1687. parse_mount_options(unc, &filteropts);
  1688. if (ENABLE_FEATURE_CLEAN_UP) free(unc);
  1689. }
  1690. lsa = host2sockaddr(hostname, 0);
  1691. share[-1] = c;
  1692. if (!lsa)
  1693. goto report_error;
  1694. // Insert "ip=..." option into options
  1695. dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
  1696. if (ENABLE_FEATURE_CLEAN_UP) free(lsa);
  1697. ip = xasprintf("ip=%s", dotted);
  1698. if (ENABLE_FEATURE_CLEAN_UP) free(dotted);
  1699. parse_mount_options(ip, &filteropts);
  1700. if (ENABLE_FEATURE_CLEAN_UP) free(ip);
  1701. mp->mnt_type = (char*)"cifs";
  1702. rc = mount_it_now(mp, vfsflags, filteropts);
  1703. goto report_error;
  1704. }
  1705. // Might this be an NFS filesystem?
  1706. if ((!mp->mnt_type || strncmp(mp->mnt_type, "nfs", 3) == 0)
  1707. && strchr(mp->mnt_fsname, ':') != NULL
  1708. ) {
  1709. if (!mp->mnt_type)
  1710. mp->mnt_type = (char*)"nfs";
  1711. rc = nfsmount(mp, vfsflags, filteropts);
  1712. goto report_error;
  1713. }
  1714. // Look at the file. (Not found isn't a failure for remount, or for
  1715. // a synthetic filesystem like proc or sysfs.)
  1716. // (We use stat, not lstat, in order to allow
  1717. // mount symlink_to_file_or_blkdev dir)
  1718. if (!stat(mp->mnt_fsname, &st)
  1719. && !(vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE))
  1720. ) {
  1721. // Do we need to allocate a loopback device for it?
  1722. if (ENABLE_FEATURE_MOUNT_LOOP && S_ISREG(st.st_mode)) {
  1723. loopFile = bb_simplify_path(mp->mnt_fsname);
  1724. mp->mnt_fsname = NULL; // will receive malloced loop dev name
  1725. if (set_loop(&mp->mnt_fsname, loopFile, 0, /*ro:*/ (vfsflags & MS_RDONLY)) < 0) {
  1726. if (errno == EPERM || errno == EACCES)
  1727. bb_error_msg(bb_msg_perm_denied_are_you_root);
  1728. else
  1729. bb_perror_msg("can't setup loop device");
  1730. return errno;
  1731. }
  1732. // Autodetect bind mounts
  1733. } else if (S_ISDIR(st.st_mode) && !mp->mnt_type)
  1734. vfsflags |= MS_BIND;
  1735. }
  1736. // If we know the fstype (or don't need to), jump straight
  1737. // to the actual mount.
  1738. if (mp->mnt_type || (vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE))) {
  1739. char *next;
  1740. for (;;) {
  1741. next = mp->mnt_type ? strchr(mp->mnt_type, ',') : NULL;
  1742. if (next)
  1743. *next = '\0';
  1744. rc = mount_it_now(mp, vfsflags, filteropts);
  1745. if (rc == 0 || !next)
  1746. break;
  1747. mp->mnt_type = next + 1;
  1748. }
  1749. } else {
  1750. // Loop through filesystem types until mount succeeds
  1751. // or we run out
  1752. // Initialize list of block backed filesystems.
  1753. // This has to be done here so that during "mount -a",
  1754. // mounts after /proc shows up can autodetect.
  1755. if (!fslist) {
  1756. fslist = get_block_backed_filesystems();
  1757. if (ENABLE_FEATURE_CLEAN_UP && fslist)
  1758. atexit(delete_block_backed_filesystems);
  1759. }
  1760. for (fl = fslist; fl; fl = fl->link) {
  1761. mp->mnt_type = fl->data;
  1762. rc = mount_it_now(mp, vfsflags, filteropts);
  1763. if (rc == 0)
  1764. break;
  1765. }
  1766. }
  1767. // If mount failed, clean up loop file (if any).
  1768. if (ENABLE_FEATURE_MOUNT_LOOP && rc && loopFile) {
  1769. del_loop(mp->mnt_fsname);
  1770. if (ENABLE_FEATURE_CLEAN_UP) {
  1771. free(loopFile);
  1772. free(mp->mnt_fsname);
  1773. }
  1774. }
  1775. report_error:
  1776. if (ENABLE_FEATURE_CLEAN_UP)
  1777. free(filteropts);
  1778. if (errno == EBUSY && ignore_busy)
  1779. return 0;
  1780. if (rc != 0)
  1781. bb_perror_msg("mounting %s on %s failed", mp->mnt_fsname, mp->mnt_dir);
  1782. return rc;
  1783. }
  1784. // -O support
  1785. // -O interprets a list of filter options which select whether a mount
  1786. // point will be mounted: only mounts with options matching *all* filtering
  1787. // options will be selected.
  1788. // By default each -O filter option must be present in the list of mount
  1789. // options, but if it is prefixed by "no" then it must be absent.
  1790. // For example,
  1791. // -O a,nob,c matches -o a,c but fails to match -o a,b,c
  1792. // (and also fails to match -o a because -o c is absent).
  1793. //
  1794. // It is different from -t in that each option is matched exactly; a leading
  1795. // "no" at the beginning of one option does not negate the rest.
  1796. static int match_opt(const char *fs_opt_in, const char *O_opt)
  1797. {
  1798. if (!O_opt)
  1799. return 1;
  1800. while (*O_opt) {
  1801. const char *fs_opt = fs_opt_in;
  1802. int O_len;
  1803. int match;
  1804. // If option begins with "no" then treat as an inverted match:
  1805. // matching is a failure
  1806. match = 0;
  1807. if (O_opt[0] == 'n' && O_opt[1] == 'o') {
  1808. match = 1;
  1809. O_opt += 2;
  1810. }
  1811. // Isolate the current O option
  1812. O_len = strchrnul(O_opt, ',') - O_opt;
  1813. // Check for a match against existing options
  1814. while (1) {
  1815. if (strncmp(fs_opt, O_opt, O_len) == 0
  1816. && (fs_opt[O_len] == '\0' || fs_opt[O_len] == ',')
  1817. ) {
  1818. if (match)
  1819. return 0; // "no" prefix, but option found
  1820. match = 1; // current O option found, go check next one
  1821. break;
  1822. }
  1823. fs_opt = strchr(fs_opt, ',');
  1824. if (!fs_opt)
  1825. break;
  1826. fs_opt++;
  1827. }
  1828. if (match == 0)
  1829. return 0; // match wanted but not found
  1830. if (O_opt[O_len] == '\0') // end?
  1831. break;
  1832. // Step to the next O option
  1833. O_opt += O_len + 1;
  1834. }
  1835. // If we get here then everything matched
  1836. return 1;
  1837. }
  1838. // Parse options, if necessary parse fstab/mtab, and call singlemount for
  1839. // each directory to be mounted.
  1840. int mount_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1841. int mount_main(int argc UNUSED_PARAM, char **argv)
  1842. {
  1843. char *cmdopts = xzalloc(1);
  1844. char *fstype = NULL;
  1845. char *O_optmatch = NULL;
  1846. char *storage_path;
  1847. llist_t *lst_o = NULL;
  1848. const char *fstabname;
  1849. FILE *fstab;
  1850. int i, j;
  1851. int rc = EXIT_SUCCESS;
  1852. unsigned long cmdopt_flags;
  1853. unsigned opt;
  1854. struct mntent mtpair[2], *mtcur = mtpair;
  1855. IF_NOT_DESKTOP(const int nonroot = 0;)
  1856. IF_DESKTOP(int nonroot = ) sanitize_env_if_suid();
  1857. INIT_G();
  1858. // Parse long options, like --bind and --move. Note that -o option
  1859. // and --option are synonymous. Yes, this means --remount,rw works.
  1860. for (i = j = 1; argv[i]; i++) {
  1861. if (argv[i][0] == '-' && argv[i][1] == '-')
  1862. append_mount_options(&cmdopts, argv[i] + 2);
  1863. else
  1864. argv[j++] = argv[i];
  1865. }
  1866. argv[j] = NULL;
  1867. // Parse remaining options
  1868. // Max 2 params; -o is a list, -v is a counter
  1869. opt_complementary = "?2o::" IF_FEATURE_MOUNT_VERBOSE("vv");
  1870. opt = getopt32(argv, OPTION_STR, &lst_o, &fstype, &O_optmatch
  1871. IF_FEATURE_MOUNT_VERBOSE(, &verbose));
  1872. while (lst_o) append_mount_options(&cmdopts, llist_pop(&lst_o)); // -o
  1873. if (opt & OPT_r) append_mount_options(&cmdopts, "ro"); // -r
  1874. if (opt & OPT_w) append_mount_options(&cmdopts, "rw"); // -w
  1875. argv += optind;
  1876. // If we have no arguments, show currently mounted filesystems
  1877. if (!argv[0]) {
  1878. if (!(opt & OPT_a)) {
  1879. FILE *mountTable = setmntent(bb_path_mtab_file, "r");
  1880. if (!mountTable)
  1881. bb_error_msg_and_die("no %s", bb_path_mtab_file);
  1882. while (getmntent_r(mountTable, &mtpair[0], getmntent_buf,
  1883. GETMNTENT_BUFSIZE))
  1884. {
  1885. // Don't show rootfs. FIXME: why??
  1886. // util-linux 2.12a happily shows rootfs...
  1887. //if (strcmp(mtpair->mnt_fsname, "rootfs") == 0) continue;
  1888. if (!fstype || strcmp(mtpair->mnt_type, fstype) == 0)
  1889. printf("%s on %s type %s (%s)\n", mtpair->mnt_fsname,
  1890. mtpair->mnt_dir, mtpair->mnt_type,
  1891. mtpair->mnt_opts);
  1892. }
  1893. if (ENABLE_FEATURE_CLEAN_UP)
  1894. endmntent(mountTable);
  1895. return EXIT_SUCCESS;
  1896. }
  1897. storage_path = NULL;
  1898. } else {
  1899. // When we have two arguments, the second is the directory and we can
  1900. // skip looking at fstab entirely. We can always abspath() the directory
  1901. // argument when we get it.
  1902. if (argv[1]) {
  1903. if (nonroot)
  1904. bb_error_msg_and_die(bb_msg_you_must_be_root);
  1905. mtpair->mnt_fsname = argv[0];
  1906. mtpair->mnt_dir = argv[1];
  1907. mtpair->mnt_type = fstype;
  1908. mtpair->mnt_opts = cmdopts;
  1909. resolve_mount_spec(&mtpair->mnt_fsname);
  1910. rc = singlemount(mtpair, /*ignore_busy:*/ 0);
  1911. return rc;
  1912. }
  1913. storage_path = bb_simplify_path(argv[0]); // malloced
  1914. }
  1915. // Past this point, we are handling either "mount -a [opts]"
  1916. // or "mount [opts] single_param"
  1917. cmdopt_flags = parse_mount_options(cmdopts, NULL);
  1918. if (nonroot && (cmdopt_flags & ~MS_SILENT)) // Non-root users cannot specify flags
  1919. bb_error_msg_and_die(bb_msg_you_must_be_root);
  1920. // If we have a shared subtree flag, don't worry about fstab or mtab.
  1921. if (ENABLE_FEATURE_MOUNT_FLAGS
  1922. && (cmdopt_flags & (MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE))
  1923. ) {
  1924. // verbose_mount(source, target, type, flags, data)
  1925. rc = verbose_mount("", argv[0], "", cmdopt_flags, "");
  1926. if (rc)
  1927. bb_simple_perror_msg_and_die(argv[0]);
  1928. return rc;
  1929. }
  1930. // Open either fstab or mtab
  1931. fstabname = "/etc/fstab";
  1932. if (cmdopt_flags & MS_REMOUNT) {
  1933. // WARNING. I am not sure this matches util-linux's
  1934. // behavior. It's possible util-linux does not
  1935. // take -o opts from mtab (takes only mount source).
  1936. fstabname = bb_path_mtab_file;
  1937. }
  1938. fstab = setmntent(fstabname, "r");
  1939. if (!fstab)
  1940. bb_perror_msg_and_die("can't read '%s'", fstabname);
  1941. // Loop through entries until we find what we're looking for
  1942. memset(mtpair, 0, sizeof(mtpair));
  1943. for (;;) {
  1944. struct mntent *mtother = (mtcur==mtpair ? mtpair+1 : mtpair);
  1945. // Get next fstab entry
  1946. if (!getmntent_r(fstab, mtcur, getmntent_buf
  1947. + (mtcur==mtpair ? GETMNTENT_BUFSIZE/2 : 0),
  1948. GETMNTENT_BUFSIZE/2)
  1949. ) { // End of fstab/mtab is reached
  1950. mtcur = mtother; // the thing we found last time
  1951. break;
  1952. }
  1953. // If we're trying to mount something specific and this isn't it,
  1954. // skip it. Note we must match the exact text in fstab (ala
  1955. // "proc") or a full path from root
  1956. if (argv[0]) {
  1957. // Is this what we're looking for?
  1958. if (strcmp(argv[0], mtcur->mnt_fsname) != 0
  1959. && strcmp(storage_path, mtcur->mnt_fsname) != 0
  1960. && strcmp(argv[0], mtcur->mnt_dir) != 0
  1961. && strcmp(storage_path, mtcur->mnt_dir) != 0
  1962. ) {
  1963. continue; // no
  1964. }
  1965. // Remember this entry. Something later may have
  1966. // overmounted it, and we want the _last_ match.
  1967. mtcur = mtother;
  1968. // If we're mounting all
  1969. } else {
  1970. struct mntent *mp;
  1971. // No, mount -a won't mount anything,
  1972. // even user mounts, for mere humans
  1973. if (nonroot)
  1974. bb_error_msg_and_die(bb_msg_you_must_be_root);
  1975. // Does type match? (NULL matches always)
  1976. if (!match_fstype(mtcur, fstype))
  1977. continue;
  1978. // Skip noauto and swap anyway
  1979. if ((parse_mount_options(mtcur->mnt_opts, NULL) & (MOUNT_NOAUTO | MOUNT_SWAP))
  1980. // swap is bogus "fstype", parse_mount_options can't check fstypes
  1981. || strcasecmp(mtcur->mnt_type, "swap") == 0
  1982. ) {
  1983. continue;
  1984. }
  1985. // Does (at least one) option match?
  1986. // (NULL matches always)
  1987. if (!match_opt(mtcur->mnt_opts, O_optmatch))
  1988. continue;
  1989. resolve_mount_spec(&mtcur->mnt_fsname);
  1990. // NFS mounts want this to be xrealloc-able
  1991. mtcur->mnt_opts = xstrdup(mtcur->mnt_opts);
  1992. // If nothing is mounted on this directory...
  1993. // (otherwise repeated "mount -a" mounts everything again)
  1994. mp = find_mount_point(mtcur->mnt_dir, /*subdir_too:*/ 0);
  1995. // We do not check fsname match of found mount point -
  1996. // "/" may have fsname of "/dev/root" while fstab
  1997. // says "/dev/something_else".
  1998. if (mp) {
  1999. if (verbose) {
  2000. bb_error_msg("according to %s, "
  2001. "%s is already mounted on %s",
  2002. bb_path_mtab_file,
  2003. mp->mnt_fsname, mp->mnt_dir);
  2004. }
  2005. } else {
  2006. // ...mount this thing
  2007. if (singlemount(mtcur, /*ignore_busy:*/ 1)) {
  2008. // Count number of failed mounts
  2009. rc++;
  2010. }
  2011. }
  2012. free(mtcur->mnt_opts);
  2013. }
  2014. }
  2015. // End of fstab/mtab is reached.
  2016. // Were we looking for something specific?
  2017. if (argv[0]) { // yes
  2018. unsigned long l;
  2019. // If we didn't find anything, complain
  2020. if (!mtcur->mnt_fsname)
  2021. bb_error_msg_and_die("can't find %s in %s",
  2022. argv[0], fstabname);
  2023. // What happens when we try to "mount swap_partition"?
  2024. // (fstab containts "swap_partition swap swap defaults 0 0")
  2025. // util-linux-ng 2.13.1 does this:
  2026. // stat("/sbin/mount.swap", 0x7fff62a3a350) = -1 ENOENT (No such file or directory)
  2027. // mount("swap_partition", "swap", "swap", MS_MGC_VAL, NULL) = -1 ENOENT (No such file or directory)
  2028. // lstat("swap", 0x7fff62a3a640) = -1 ENOENT (No such file or directory)
  2029. // write(2, "mount: mount point swap does not exist\n", 39) = 39
  2030. // exit_group(32) = ?
  2031. #if 0
  2032. // In case we want to simply skip swap partitions:
  2033. l = parse_mount_options(mtcur->mnt_opts, NULL);
  2034. if ((l & MOUNT_SWAP)
  2035. // swap is bogus "fstype", parse_mount_options can't check fstypes
  2036. || strcasecmp(mtcur->mnt_type, "swap") == 0
  2037. ) {
  2038. goto ret;
  2039. }
  2040. #endif
  2041. if (nonroot) {
  2042. // fstab must have "users" or "user"
  2043. l = parse_mount_options(mtcur->mnt_opts, NULL);
  2044. if (!(l & MOUNT_USERS))
  2045. bb_error_msg_and_die(bb_msg_you_must_be_root);
  2046. }
  2047. //util-linux-2.12 does not do this check.
  2048. //// If nothing is mounted on this directory...
  2049. //// (otherwise repeated "mount FOO" mounts FOO again)
  2050. //mp = find_mount_point(mtcur->mnt_dir, /*subdir_too:*/ 0);
  2051. //if (mp) {
  2052. // bb_error_msg("according to %s, "
  2053. // "%s is already mounted on %s",
  2054. // bb_path_mtab_file,
  2055. // mp->mnt_fsname, mp->mnt_dir);
  2056. //} else {
  2057. // ...mount the last thing we found
  2058. mtcur->mnt_opts = xstrdup(mtcur->mnt_opts);
  2059. append_mount_options(&(mtcur->mnt_opts), cmdopts);
  2060. resolve_mount_spec(&mtpair->mnt_fsname);
  2061. rc = singlemount(mtcur, /*ignore_busy:*/ 0);
  2062. if (ENABLE_FEATURE_CLEAN_UP)
  2063. free(mtcur->mnt_opts);
  2064. //}
  2065. }
  2066. //ret:
  2067. if (ENABLE_FEATURE_CLEAN_UP)
  2068. endmntent(fstab);
  2069. if (ENABLE_FEATURE_CLEAN_UP) {
  2070. free(storage_path);
  2071. free(cmdopts);
  2072. }
  2073. //TODO: exitcode should be ORed mask of (from "man mount"):
  2074. // 0 success
  2075. // 1 incorrect invocation or permissions
  2076. // 2 system error (out of memory, cannot fork, no more loop devices)
  2077. // 4 internal mount bug or missing nfs support in mount
  2078. // 8 user interrupt
  2079. //16 problems writing or locking /etc/mtab
  2080. //32 mount failure
  2081. //64 some mount succeeded
  2082. return rc;
  2083. }