mount.c 67 KB

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