mount.c 66 KB

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