-
Notifications
You must be signed in to change notification settings - Fork 6
/
automount.sh
executable file
·1036 lines (982 loc) · 30.7 KB
/
automount.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# CONSTANTS
declare -r SCRIPTLASTMOD="2017-03-19"
declare -r SCRIPTVERSION="0.90.26"
declare -r DEBUG="false"
if [ "${DEBUG}" = "false" ]; then
set +xv
EXPECTDEBUG="log_user 0"
else
PS4='+(${BASH_SOURCE:-}:${LINENO:-}): ${FUNCNAME[0]:+${FUNCNAME[0]:-}(): }'
set -xv
EXPECTDEBUG="log_user 1"
fi
declare -r EXPECTDEBUG
#security add-internet-password \
# -a ACCOUNT \
# -l LABEL (same as SERVER) \
# -D DESCRIPTION (eg. Networkpassword) \
# -j COMMENT (${SCRIPTNAME}) \
# -r PROTOCOL ("afp "/"cifs"/"ftp "/"http"/"htps"/"smb ") \
# -s SERVER \
# -w PASSWORD \
# -U \
# -T /usr/bin/security \
# -T /System/Library/Extensions/webdav_fs.kext/Contents/Resources/webdavfs_agent \
# -T /System/Library/CoreServices/NetAuthAgent.app/Contents/MacOS/NetAuthSysAgent \
# -T /System/Library/CoreServices/NetAuthAgent.app \
# -T group://NetAuth \
# ${LOGINHOME}/Library/Keychains/login.keychain
#Server="SERVER"; Label="${Server}"; Description="DESCRIPTION"; Protocol="PROTOCOL"; Account="$(id -p | awk '/^login/ { print $2; exit } /^uid/ { print $2 }')"; UserHomeDirectory="$(dscl . read /Users/${Account} NFSHomeDirectory | cut -d' ' -f2-)"; security add-internet-password -a "${Account}" -l "${Label}" -D "${Description:-Netzwerkpasswort}" -j "automount" -r "$(printf "%-4s" ${Protocol})" -s "${Server}" -w "$(read -p "Password: " -s && echo "${REPLY}")" -U -T /usr/bin/security -T /System/Library/CoreServices/NetAuthAgent.app/Contents/MacOS/NetAuthSysAgent -T /System/Library/CoreServices/NetAuthAgent.app -T group://NetAuth ${UserHomeDirectory}/Library/Keychains/login.keychain
# when error "User interaction is not allowed." occurs, unlock keychain
# RC=36 (security error 36 -> Error: 0x00000024 36 CSSM_ERRCODE_OBJECT_ACL_REQUIRED)
#security unlock-keychain -p "LOGINNAME_PASSWORD" ${LOGINHOME}/Library/Keychains/login.keychain
#/usr/local/bin/automount.sh
#chown root:admin /usr/local/bin/automount.sh
#chmod 755 /usr/local/bin/automount.sh
declare -ri YES=0
declare -ri SUCCESS=${YES}
declare -ri TRUE=${YES}
declare -ri FOUND=${YES}
declare -ri NO=1
declare -ri ERROR=${NO}
declare -ri FALSE=${NO}
declare -ri MISSING=${NO}
# os x version array major minor patch
declare -air OSVERSION=( $(sw_vers | awk -F'[: |.]' '/ProductVersion/ { printf("%d %d %d", $2, $3, $4) }') )
# os x version as integer
declare -ir OSVERSION_INTEGER=10#$(printf '%02d%02d%02d' "${OSVERSION[0]}" "${OSVERSION[1]}" "${OSVERSION[2]}")
# script path name
SCRIPT_PN="${0%/*}"
if [ "${SCRIPT_PN}" = "." ]; then
SCRIPT_PN="${PWD}"
elif [ "${SCRIPT_PN:0:1}" != "/" ]; then
SCRIPT_PN="$(which ${0})"
fi
# script filename
declare -r SCRIPT_FN="${0##*/}"
# script name
SCRIPTNAME="${SCRIPT_FN%.*}"
# script filename extension
SCRIPTEXTENSION=${SCRIPT_FN##*.}
if [ "${SCRIPTNAME}" = "" ]; then
SCRIPTNAME=".${SCRIPTEXTENSION}"
SCRIPTEXTENSION=""
fi
declare -r SCRIPT_PN SCRIPTNAME SCRIPTEXTENSION
# function for getting values from Directory Service via dscl
function readDS {
local _Account _DSKey _DSValue
local _FS=":"
while :; do
case ${1} in
-a|--account)
if [[ -n "${2}" && "${2:0:2}" != "--" && "${2:0:1}" != "-" ]]; then
_Account="${2}"
shift
else
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
return ${ERROR}
fi
;;
--account=?*)
_Account=${1#*=} # Delete everything up to "=" and assign the remainder.
;;
--account=) # Handle the case of an empty --account=
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
return ${ERROR}
;;
-k|--key)
if [[ -n "${2}" && "${2:0:2}" != "--" && "${2:0:1}" != "-" ]]; then
_DSKey="${2}"
shift
else
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
return ${ERROR}
fi
;;
--key=?*)
_DSKey=${1#*=} # Delete everything up to "=" and assign the remainder.
;;
--key=) # Handle the case of an empty --key=
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
return ${ERROR}
;;
--) # End of all options.
shift
break
;;
-?*)
printf 'WARN: Unknown option (ignored): %s\n' "${1}" >&2
;;
*) # Default case: If no more options then break out of the loop.
break
esac
shift
done
if [ -n "${_Account}" ] && [ -n "${_DSKey}" ] && _DSValue="$(dscl . read /Users/"${_Account}" "${_DSKey}" |\
awk -F"${_FS}" \
-v DSKey="${_DSKey}" \
'BEGIN {
DSValue=""
DSKeyFound=0
}
function getValuesFromPosition(StartPosition) {
for(FieldNr=StartPosition; FieldNr <= NF; FieldNr++) {
DSValue = (DSValue == "" ? "" : DSValue FS) $FieldNr
}
}
DSKeyFound == 1 {
getValuesFromPosition(1)
DSKeyFound=0
}
$1 == DSKey {
if(NF > 1) {
getValuesFromPosition(2)
} else {
DSKeyFound=1
next
}
}
END {
# trim leading space
gsub(/^[[:space:]]+/, "", DSValue)
printf("%s", DSValue)
}')"; then
echo "${_DSValue}"
return ${SUCCESS}
else
return ${ERROR}
fi
}
# user name
declare -r USERNAME="$(id -p | awk -F' ' '/^uid/ { print $2 }')"
# user id
declare -ir USERID="$(readDS --account="${USERNAME}" --key="UniqueID")"
# user primary group id
declare -ir USERPRIMARYGROUPID="$(readDS --account="${USERNAME}" --key="PrimaryGroupID")"
# user home
declare -r USERHOME="$(readDS --account="${USERNAME}" --key="NFSHomeDirectory")"
# login name
LOGINNAME="$(id -p | awk -F' ' '/^login/ { print $2 }')"
if [ -z "${LOGINNAME}" ]; then
LOGINNAME="${USERNAME}"
# login id
declare -i LOGINID="${USERID}"
# login primary group id
declare -i LOGINPRIMARYGROUPID=${USERPRIMARYGROUPID}
# login home
LOGINHOME="${USERHOME}"
# launch as user
LAUNCHASUSER=""
else
declare -i LOGINID="$(readDS --account="${LOGINNAME}" --key="UniqueID")"
declare -i LOGINPRIMARYGROUPID="$(readDS --account="${LOGINNAME}" --key="PrimaryGroupID")"
LOGINHOME="$(readDS --account="${LOGINNAME}" --key="NFSHomeDirectory")"
if [[ ${OSVERSION_INTEGER} -ge 101000 ]]; then
LAUNCHASUSER="launchctl asuser ${LOGINID} chroot -u ${LOGINID} -g ${LOGINPRIMARYGROUPID} /"
elif [[ ${OSVERSION_INTEGER} -le 100900 ]]; then
LAUNCHASUSER="launchctl bsexec ${LOGINID} chroot -u ${LOGINID} -g ${LOGINPRIMARYGROUPID} /"
fi
fi
declare -r LOGINNAME LOGINID LOGINPRIMARYGROUPID LOGINHOME LAUNCHASUSER
# case $(ps -o state= -p ${$}) in
if [ -t 0 ]; then
# interactive shell (not started from launch daemon)
declare -ri BACKGROUND=${NO}
else
# background shell
declare -ri BACKGROUND=${YES}
fi
# ps -a -x -ww -p ${$} -o ppid= -o pid= -o tt= -o flags= -o state= -o logname= -o command=cmd | grep "[${LOGINNAME:0:1}]${LOGINNAME:1}.*[${SCRIPT_FN:0:1}]${SCRIPT_FN:1} ${@}">>${LOG_AFN}
# parent pid
# declare -i PPID=$(ps -a -x -ww -p ${$} -o ppid= -o logname= -o command= |\
# awk -v RegexUser="[${LOGINNAME:0:1}]${LOGINNAME:1}" \
# -v RegexCommand="[${SCRIPT_FN:0:1}]${SCRIPT_FN:1} ${@}" \
# 'BEGIN {
# Regex=sprintf("%s.*%s", RegexUser, RegexCommand)
# }
# $0 ~ Regex {
# print $1
# }
# ')
# log dir (absolute path name)
declare -r LOG_APN="${LOGINHOME}/Library/Logs"
# log file (absolute file name)
declare -r LOG_AFN="${LOG_APN}/${SCRIPTNAME}.log"
# temp dir (absolute path name)
declare -r TMP_APN="/tmp"
# lock dir (absolute path name)
declare -r LOCK_APN="${TMP_APN}/${SCRIPTNAME}.lock"
# lock file (absolute file name)
declare -r LOCK_AFN="${LOCK_APN}/pid"
# log levels
declare -a LOG_LEVEL
declare -ir LOG_EMERGENCY=${#LOG_LEVEL[@]}
LOG_LEVEL[${#LOG_LEVEL[@]}]="Emergency"
declare -ir LOG_ALERT=${#LOG_LEVEL[@]}
LOG_LEVEL[${#LOG_LEVEL[@]}]="Alert"
declare -ir LOG_CRITICAL=${#LOG_LEVEL[@]}
LOG_LEVEL[${#LOG_LEVEL[@]}]="Critical"
declare -ir LOG_ERROR=${#LOG_LEVEL[@]}
LOG_LEVEL[${#LOG_LEVEL[@]}]="Error"
declare -ir LOG_WARNING=${#LOG_LEVEL[@]}
LOG_LEVEL[${#LOG_LEVEL[@]}]="Warning"
declare -ir LOG_NOTICE=${#LOG_LEVEL[@]}
LOG_LEVEL[${#LOG_LEVEL[@]}]="Notice"
declare -ir LOG_INFO=${#LOG_LEVEL[@]}
LOG_LEVEL[${#LOG_LEVEL[@]}]="Info"
declare -ir LOG_DEBUG=${#LOG_LEVEL[@]}
LOG_LEVEL[${#LOG_LEVEL[@]}]="Debug"
declare -r LOG_LEVEL
# logfile delimiter
declare -r LOG_DELIMITER=$'|'
# signals
declare -a SIGNALS
declare -ir EXIT=0
SIGNALS[${EXIT}]="EXIT (${EXIT}): exit (bash)"
declare -ir SIGHUP=1
SIGNALS[${SIGHUP}]="SIGHUP (${SIGHUP}): terminal line hangup (Ctrl + D)"
declare -ir SIGINT=2
SIGNALS[${SIGINT}]="SIGINT (${SIGINT}): interrupt program (Ctrl + C)"
declare -ir SIGQUIT=3
SIGNALS[${SIGQUIT}]="SIGQUIT (${SIGQUIT}): quit program"
declare -ir SIGTERM=15
SIGNALS[${SIGTERM}]="SIGTERM (${SIGTERM}): software termination signal"
declare -ir SIGUSR1=30
SIGNALS[${SIGUSR1}]="SIGUSR1 (${SIGUSR1}): User defined signal 1"
declare -ir SIGUSR2=31
SIGNALS[${SIGUSR2}]="SIGUSR2 (${SIGUSR2}): User defined signal 2"
declare -r SIGNALS
# automount plist (absolute file name)
declare -r AUTOMOUNTPLIST_AFN="${LOGINHOME}/Library/Preferences/it.niemetz.automount.plist"
# login keychain (absolute file name)
declare -r LOGINKEYCHAIN_AFN="$(${LAUNCHASUSER} security list-keychains -d user | awk -F'"' '/login/ { print $2 }')"
# max pings
declare -r MAXRETRYINSECONDS=10
# mount options
declare -r MOUNTOPTIONS="nodev,nosuid"
# map protocol to value in keychain
declare -ra PROTOCOLMAPPING=( 'afp="afp "' 'cifs="cifs"' 'ftp="ftp "' 'http="http"' 'https="htps"' 'smb="smb "' )
# ping -t timeout
declare -ir PINGTIMEOUT=1
if [[ ${OSVERSION_INTEGER} -ge 101200 || ${LOGINID} -ne 0 ]]; then
# mountpoint absolute pathname
MOUNTPOINT_APN="${LOGINHOME}/Volumes"
else
MOUNTPOINT_APN="/Volumes"
fi
# Global variables
# index counter
declare -i MountlistIndex
# is ip in valid range
declare -i IsInValidRange=${TRUE}
# exit code
declare -i EC=${SUCCESS}
# array of ip addresses
declare -a IPAddresses=()
# late bound variables
CommonMaxRetryInSeconds=""
CommonValidIPRanges=""
CommonMountOptions=""
CommonAccount=""
ValidIPRanges=""
MountOptions=""
MaxRetryInSeconds=""
declare -i Simulate=${NO}
Protocol=""
Domain=""
Account=""
Server=""
Share=""
MountPoint=""
declare -i SuccessfullyMountedShares=0
declare -i AlreadyMountedShares=0
# Action to do
Action=""
# verbose
declare -i Verbose=0
# Function definitions
function log {
local _DateFormat='%Y-%m-%d %T %z'
local _Delimiter="${LOG_DELIMITER:-|}"
local -i _Priority=6
while :; do
case ${1} in
-p|--priority)
if [[ -n "${2}" && "${2:0:2}" != "--" && "${2:0:2}" != "-" ]]; then
if ! _Priority=${2} 2>/dev/null; then
printf 'ERROR: "%s" requires a numeric option argument.\n' "${1}" >&2
return ${ERROR}
fi
shift
else
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
return ${ERROR}
fi
;;
--priority=?*)
if ! _Priority=${1#*=} 2>/dev/null; then
printf 'ERROR: "%s" requires a numeric option argument.\n' "${1}" >&2
return ${ERROR}
fi
;;
--priority=)
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
return ${ERROR}
;;
--) # End of all options.
shift
break
;;
-?*)
printf 'WARN: Unknown option (ignored): %s\n' "${1}" >&2
;;
*) # Default case: If no more options then break out of the loop.
break
esac
shift
done
set -- "${1:-$(</dev/stdin)}" "${@:2}"
if [ ${_Priority} -le 3 ]; then
echo "${1}" >&2
else
echo "${1}"
fi
echo "$(date +"${_DateFormat}")${_Delimiter}${$}${_Delimiter}${LOG_LEVEL[${_Priority}]}${_Delimiter}${1}" >>"${LOG_AFN}"
return ${SUCCESS}
}
function cleanup {
local -i _Signal=${1}
rm -rf "${LOCK_APN}" >/dev/null 2>&1
trap -- ${SIGHUP} ${SIGINT} ${SIGQUIT} ${SIGTERM} ${EXIT}
exit ${1}
}
function onExit {
# executed before exiting, activate with "trap 'onExit' EXIT"
local -i _ExitCode=${?}
:
exit ${_ExitCode}
}
function catchTrap {
local _Signal
local _Func="${1}"; shift
for _Signal; do
trap "${_Func} ${_Signal}" "${_Signal}"
done
}
function showUsage {
cat <<EOH
Usage: ${SCRIPT_FN} (V${SCRIPTVERSION} ${SCRIPTLASTMOD}) (-m|--mountall)|(-n|--simulate)|(--addpassword (-p|--protocol) protocol (-s|--server) server [(-a|--account) account] [(-d|--description) description])
EOH
}
function getIPAddresses {
local _IPAddresses=""
local -i _Sleep=0
ipconfig waitall
while [[ ( -z "${_IPAddresses}" || "${_IPAddresses}" =~ (^| )169\.[0-9]+\.[0-9]+\.[0-9]+( |$) ) && ${_Sleep} -lt 10 ]]; do
sleep ${_Sleep}
((_Sleep++))
#/usr/libexec/PlistBuddy -c "Print 0:_items:0:IPv4:Addresses:0" /var/folders/5s/prj3y3g13nb9mllltrcg8rcw0000gn/T/SPNetworkDataType.kuCAGYvK
#system_profiler SPNetworkDataType |awk '/IPv4 Addresses:/ { gsub(/ IPv4 Addresses: /, ""); printf $0 " " }'
_IPAddresses="$(
/sbin/ifconfig |\
/usr/bin/awk \
'
BEGIN {
Device=""
}
/(^en[0-9]*:|^utun[0-9]*).*UP.*RUNNING/ {
Device=$1
next
}
$1 == "inet" && Device != "" {
IPAddresses=sprintf("%s%s", (IPAddresses == "" ? "" : IPAddresses " "), $2)
Device=""
next
}
END {
print IPAddresses
}
'
)"
done
if [ -n "${_IPAddresses}" ]; then
IPAddresses=( ${_IPAddresses} )
return ${SUCCESS}
else
log --priority=${LOG_ERROR} "Could not get local IP address(es)"
return ${ERROR}
fi
}
function getKeychainProtocol {
local _SearchKeychainProtocol="${Protocol:-unknown_protocol}="
local _Protocol _KeychainProtocol
for _Protocol in "${PROTOCOLMAPPING[@]}"; do
if [[ "${_Protocol}" =~ ^${_SearchKeychainProtocol} ]]; then
_KeychainProtocol="${_Protocol/${_SearchKeychainProtocol}/}"
fi
done
if [ -n "${_KeychainProtocol}" ]; then
echo "${_KeychainProtocol//\"/}"
return ${FOUND}
else
return ${MISSING}
fi
}
function convertToHexCode {
tr -d '\n' |\
od -A n -t x1 |\
sed -E 's/^ */ /;s/ *$//;s/ /\\x/g'
}
function getPasswordFromKeychain {
local -i _RC=${TRUE}
security find-internet-password \
-w \
-r "$(getKeychainProtocol)" \
-a "${Account}" \
-l "${Server}" \
-j "${SCRIPTNAME}" \
"${LOGINKEYCHAIN_AFN}"
_RC=${?}
if [ ${_RC} -ne ${SUCCESS} ]; then
log --priority=${LOG_ERROR} "getPasswordFromKeychain failed (RC=${_RC})"
fi
return ${_RC}
}
function isPingable {
# server to ping
local _Server="${1}"
# retry counter
local -i _Try=0
# return value
local _RV=""
if [ -n "${_Server}" ]; then
while ! _RV="$(ping -c 1 -t ${PINGTIMEOUT} -o -q "${_Server}" 2>&1)" && [ ${_Try} -le ${MaxRetryInSeconds} ]; do
((_Try++))
done
if [ ${_Try} -gt ${MaxRetryInSeconds} ]; then
log --priority=${LOG_ERROR} "Could not ping ${Server} within ${MaxRetryInSeconds} (RC=${RC}, RV=${_RV})"
return ${ERROR}
fi
fi
return ${SUCCESS}
}
function initCommonValues {
# set global common values
CommonMaxRetryInSeconds=$(/usr/libexec/PlistBuddy -c "Print CommonMaxRetryInSeconds" "${AUTOMOUNTPLIST_AFN}" 2>/dev/null)
CommonMaxRetryInSeconds=${CommonMaxRetryInSeconds:-${MAXRETRYINSECONDS}}
CommonValidIPRanges="$(/usr/libexec/PlistBuddy -c "Print CommonValidIPRanges" "${AUTOMOUNTPLIST_AFN}" 2>/dev/null)"
CommonMountOptions="$(/usr/libexec/PlistBuddy -c "Print CommonMountOptions" "${AUTOMOUNTPLIST_AFN}" 2>/dev/null)"
CommonMountOptions="${CommonMountOptions:-${MOUNTOPTIONS}}"
CommonAccount="$(/usr/libexec/PlistBuddy -c "Print CommonAccount" "${AUTOMOUNTPLIST_AFN}" 2>/dev/null)"
CommonAccount="${CommonAccount:-${LOGINNAME}}"
return ${SUCCESS}
}
function readMountlistValues {
local -i _Index=${1}
# first clear old values
unset ValidIPRanges MountOptions MaxRetryInSeconds Protocol Account Server Share MountPoint
# get values
ValidIPRanges="$(/usr/libexec/PlistBuddy -c "Print Mountlist:${_Index}:ValidIPRanges" "${AUTOMOUNTPLIST_AFN}" 2>/dev/null)"
ValidIPRanges="${ValidIPRanges:-${CommonValidIPRanges}}"
MountOptions="$(/usr/libexec/PlistBuddy -c "Print Mountlist:${_Index}:MountOptions" "${AUTOMOUNTPLIST_AFN}" 2>/dev/null)"
MountOptions="${MountOptions:-${CommonMountOptions}}"
MaxRetryInSeconds=$(/usr/libexec/PlistBuddy -c "Print Mountlist:${_Index}:MaxRetryInSeconds" "${AUTOMOUNTPLIST_AFN}" 2>/dev/null)
MaxRetryInSeconds=${MaxRetryInSeconds:-${CommonMaxRetryInSeconds}}
Protocol="$(/usr/libexec/PlistBuddy -c "Print Mountlist:${_Index}:Protocol" "${AUTOMOUNTPLIST_AFN}" 2>/dev/null)"
Domain="$(/usr/libexec/PlistBuddy -c "Print Mountlist:${_Index}:Domain" "${AUTOMOUNTPLIST_AFN}" 2>/dev/null)"
Account="$(/usr/libexec/PlistBuddy -c "Print Mountlist:${_Index}:Account" "${AUTOMOUNTPLIST_AFN}" 2>/dev/null)"
Account="${Account:-${CommonAccount}}"
Server="$(/usr/libexec/PlistBuddy -c "Print Mountlist:${_Index}:Server" "${AUTOMOUNTPLIST_AFN}" 2>/dev/null)"
Share="$(/usr/libexec/PlistBuddy -c "Print Mountlist:${_Index}:Share" "${AUTOMOUNTPLIST_AFN}" 2>/dev/null)"
MountPoint="$(/usr/libexec/PlistBuddy -c "Print Mountlist:${_Index}:MountPoint" "${AUTOMOUNTPLIST_AFN}" 2>/dev/null)"
MountPoint="${MountPoint:-${Share##*/}}"
if [[ -n "${Protocol}" && -n "${Account}" && -n "${Server}" && -n "${Share}" ]]; then
return ${SUCCESS}
else
log --priority=${LOG_ERROR} "Protocol '${Protocol}'/Account '${Account}'/Server '${Server}'/Share '${Share}' empty"
return ${ERROR}
fi
}
function isInValidIPRange {
local _ValidIPRanges="${1}"
local _IPAddress _IPAddressPart
if [ -n "${_ValidIPRanges}" ]; then
for _IPAddress in "${IPAddresses[@]}"; do
_IPAddressPart="$(echo "${_IPAddress}" | cut -d'.' -f1-3)"
if [[ "${_ValidIPRanges}" =~ (^|,)"${_IPAddressPart}"(,|$) ]]; then
return ${YES}
fi
done
log --priority=${LOG_WARNING} "'${IPAddresses[@]}' not in range of '${_ValidIPRanges}'"
return ${NO}
fi
return ${YES}
}
function isMounted {
local _RV=""
if _RV="$(mount | egrep "//.*${Server}/(${Share})? on ${MOUNTPOINT_APN}/${Share} \(.*(, mounted by ${LOGINNAME})?\)$" 2>&1)"; then
if [ ${Verbose} -ne 0 ]; then
log --priority=${LOG_WARNING} "Share '${Share}' already mounted (RV=${_RV})"
fi
return ${YES}
fi
return ${NO}
}
function createMountpoint {
local _Share="${1}"
local _RV=""
local -i _RC=${TRUE}
if [ -n "${_Share}" ]; then
if [ ! -d "${MOUNTPOINT_APN}/${_Share}" ]; then
_RV="$( { mkdir -p ${Verbose} "${MOUNTPOINT_APN}/${_Share}" && chown "${LOGINID}:${LOGINPRIMARYGROUPID}" "${MOUNTPOINT_APN}/${_Share}" && chmod 755 "${MOUNTPOINT_APN}/${_Share}"; } 2>&1 )"
_RC=${?}
if [ ${_RC} -ne ${SUCCESS} ]; then
log --priority=${LOG_ERROR} "Could not create '${MOUNTPOINT_APN}/${_Share}' (RC=${_RC}, RV=${_RV})"
rmdir "${MOUNTPOINT_APN}/${_Share}" >/dev/null 2>&1
return ${ERROR}
fi
fi
fi
return ${SUCCESS}
}
function processMountlist {
local _RV=""
local -i _RC=${TRUE}
local -i _EC=${TRUE}
# check all files exits
if [ ! -s "${AUTOMOUNTPLIST_AFN}" ] || [ ! -s "${LOGINKEYCHAIN_AFN}" ]; then
# if [[ ! ( -s "${AUTOMOUNTPLIST_AFN}" && ( -s "${LOGINKEYCHAIN_AFN}" || -s "${LOGINKEYCHAIN_AFN}-db" ) ) ]]; then
log --priority=${LOG_ERROR} "${AUTOMOUNTPLIST_AFN} and/or ${LOGINKEYCHAIN_AFN} are missing"
return ${ERROR}
fi
# get local ip address(es)
getIPAddresses
_RC=${?}
if [ ${_RC} -ne ${SUCCESS} ]; then
return ${_RC}
fi
# initialize common values
initCommonValues
# process automount plist file
MountlistIndex=0
while /usr/libexec/PlistBuddy -c "Print Mountlist:${MountlistIndex}" "${AUTOMOUNTPLIST_AFN}" >/dev/null 2>&1; do
# get the values
if ! readMountlistValues ${MountlistIndex}; then
_EC=$((_EC||!${?}))
((MountlistIndex++))
continue
fi
# check if in valid ip range
if ! isInValidIPRange "${ValidIPRanges}"; then
((MountlistIndex++))
continue
fi
# is share already mounted?
if isMounted; then
((AlreadyMountedShares++))
((MountlistIndex++))
continue
fi
# is server reachable?
if ! isPingable "${Server}"; then
_EC=$((_EC||!${?}))
((MountlistIndex++))
continue
fi
# create mountpoint
if [ ${Simulate} -eq ${NO} ] && ! createMountpoint "${MountPoint}"; then
_EC=$((_EC||!${?}))
((MountlistIndex++))
continue
fi
case ${Protocol} in
http|https)
if [ ${Simulate} -eq ${YES} ]; then
echo "/sbin/mount_webdav -s -i${MountOptions:+ -o ${MountOptions}} ${Protocol}://${Server} ${MOUNTPOINT_APN}/${MountPoint}"
else
_RV="$(${LAUNCHASUSER} expect -c '
set timeout '${MaxRetryInSeconds}'
'"${EXPECTDEBUG}"'
spawn /sbin/mount_webdav -s -i'"${MountOptions:+ -o ${MountOptions}}"' '"${Protocol}"'://'"${Server}"' '"${MOUNTPOINT_APN}"'/'"${MountPoint}"'
expect {
-re ".*ser.*|.*name.*" {
send -- "'"${Account}"'\r"
exp_continue
}
-re ".*ssword.*" {
send -- "'$(getPasswordFromKeychain | convertToHexCode)'\r"
exp_continue
}
timeout {
exit 1
}
eof {
return
}
}
catch wait result
exit [lindex $result 3]
' 2>&1)"
fi
_RC=${?}
;;
ftp)
if [ ${Simulate} -eq ${YES} ]; then
echo "/sbin/mount_ftp -i${MountOptions:+ -o ${MountOptions}} ${Protocol}://${Server} ${MOUNTPOINT_APN}/${MountPoint}"
else
_RV="$(${LAUNCHASUSER} expect -c '
set timeout '${MaxRetryInSeconds}'
'"${EXPECTDEBUG}"'
spawn /sbin/mount_ftp -i'"${MountOptions:+ -o ${MountOptions}}"' '"${Protocol}"'://'"${Server}"' '"${MOUNTPOINT_APN}"'/'"${MountPoint}"'
expect {
-re ".*ser.*|.*name.*" {
send -- "'"${Account}"'\r"
exp_continue
}
-re ".*ssword.*" {
send -- "'$(getPasswordFromKeychain | convertToHexCode)'\r"
exp_continue
}
eof {
return
}
timeout {
exit 1
}
}
catch wait result
exit [lindex $result 3]' 2>&1)"
fi
_RC=${?}
;;
nfs)
if [ ${Simulate} -eq ${YES} ]; then
echo "/sbin/mount -t ${Protocol}${MountOptions:+ -o ${MountOptions}} ${Server}://${Share} ${MOUNTPOINT_APN}/${MountPoint}"
else
_RV="$(${LAUNCHASUSER} /sbin/mount -t ${Protocol}${MountOptions:+ -o ${MountOptions}} "${Server}://${Share}" "${MOUNTPOINT_APN}/${MountPoint}" 2>&1)"
fi
_RC=${?}
;;
afp)
if [ ${Simulate} -eq ${YES} ]; then
echo "/sbin/mount_afp -i -s${MountOptions:+ -o ${MountOptions}} ${Protocol}://${Server}/${Share} ${MOUNTPOINT_APN}/${MountPoint}"
else
_RV="$(${LAUNCHASUSER} expect -c '
set timeout '${MaxRetryInSeconds}'
'"${EXPECTDEBUG}"'
spawn /sbin/mount_afp -i -s'"${MountOptions:+ -o ${MountOptions}}"' '"${Protocol}"'://'"${Server}"'/'"${Share}"' '"${MOUNTPOINT_APN}"'/'"${MountPoint}"'
expect {
-re ".*ser.*" {
if {"'"${Domain}"'" == ""} {
send -- "'"${Account}"'\r"
} else {
send -- "'"${Domain}"';'"${Account}"'\r"
}
exp_continue
}
-re ".*ssword.*" {
send -- "'"$(getPasswordFromKeychain | convertToHexCode)"'\r"
exp_continue
}
timeout {
exit 1
}
eof {
return
}
}
catch wait result
exit [lindex $result 3]' 2>&1)"
fi
_RC=${?}
;;
smb)
if [ ${Simulate} -eq ${YES} ]; then
echo "/sbin/mount_smbfs -o soft${MountOptions:+,${MountOptions}} '//${Domain:+${Domain};}${Account}@${Server}/${Share}' ${MOUNTPOINT_APN}/${MountPoint}"
else
_RV="$(${LAUNCHASUSER} expect -c '
set timeout '${MaxRetryInSeconds}'
'"${EXPECTDEBUG}"'
spawn /sbin/mount_smbfs -o soft'"${MountOptions:+,${MountOptions}}"' "//'"${Domain:+${Domain};}${Account}"'@'"${Server}"'/'"${Share}"'" '"${MOUNTPOINT_APN}"'/'"${MountPoint}"'
expect {
-re "..*ser.*|.*name.*" {
if {"'"${Domain}"'" == ""} {
send -- "'"${Account}"'\r"
} else {
send -- "'"${Domain}"';'"${Account}"'\r"
}
exp_continue
}
-re ".*ssword.*" {
send -- "'"$(getPasswordFromKeychain | convertToHexCode)"'\r"
exp_continue
}
timeout {
exit 1
}
eof {
return
}
}
catch wait result
exit [lindex $result 3]' 2>&1)"
fi
_RC=${?}
;;
cifs)
if [ ${Simulate} -eq ${YES} ]; then
echo "/sbin/mount -t ${Protocol}${MountOptions:+ -o ${MountOptions}} '//${Account}@${Server}/${Share}' ${MOUNTPOINT_APN}/${MountPoint}"
else
_RV="$(${LAUNCHASUSER} expect -c '
set timeout '${MaxRetryInSeconds}'
'"${EXPECTDEBUG}"'
spawn /sbin/mount -t '"${Protocol}"''"${MountOptions:+ -o ${MountOptions}}"' "//'"${Account}"'@'"${Server}"'/'"${Share}"'" '"${MOUNTPOINT_APN}"'/'"${MountPoint}"'
expect {
-re ".*ssword.*" {
send -- "'"$(getPasswordFromKeychain | convertToHexCode)"'\r"
exp_continue
}
timeout {
exit 1
}
eof {
return
}
}
catch wait result
exit [lindex $result 3]' 2>&1)"
fi
_RC=${?}
;;
*)
log --priority=${LOG_ERROR} "Unknown protocol ${Protocol}"
((MountlistIndex++))
continue
;;
esac
if [ ${Simulate} -eq ${NO} ]; then
if [ ${_RC} -eq ${SUCCESS} ]; then
log --priority=${LOG_INFO} "${Share} mounted successfully"
((SuccessfullyMountedShares++))
else
log --priority=${LOG_ERROR} "mount of ${Share} failed (RC=${_RC}, RV=${_RV})"
fi
fi
_EC=$((_EC||_RC))
((MountlistIndex++))
done
if [ ${Simulate} -eq ${NO} ]; then
if [ ${_EC} -eq ${SUCCESS} ]; then
if [ ${SuccessfullyMountedShares} -eq ${MountlistIndex} ]; then
log --priority=${LOG_INFO} "All shares mountd successfully."
if [ ${BACKGROUND} -eq ${YES} ]; then
${LAUNCHASUSER} /usr/bin/osascript -e 'display notification "All shares mounted successfully." with title "automount" subtitle ""'
fi
else
if [ $((${SuccessfullyMountedShares}+${AlreadyMountedShares})) -ne ${MountlistIndex} ]; then
log --priority=${LOG_INFO} "Some shares mountd successfully."
fi
fi
else
log --priority=${LOG_ERROR} "automount runned with errors."
if [ ${BACKGROUND} -eq ${YES} ]; then
${LAUNCHASUSER} /usr/bin/osascript -e 'display notification "automount runned with errors." with title "automount" subtitle ""'
fi
fi
fi
return ${_EC}
}
function addPassword {
local _Account="${Account:-${LOGINNAME}}"
local _AppAccess=""
local _RV=""
local -i RC=0
if [[ "${Protocol}" =~ ^http(s)+ ]]; then
_AppAccess="-T /System/Library/Extensions/webdav_fs.kext/Contents/Resources/webdavfs_agent"
fi
_RV="$(security add-internet-password \
-a "${_Account}" \
-l "${Server}" \
-D "${Description:-Netzwerkpasswort}" \
-j "${SCRIPTNAME}" \
-r "$(getKeychainProtocol)" \
-s "${Server}" \
-w "$(read -r -p "Password: " -s && echo "${REPLY}"; unset REPLY)" \
-U \
-T /usr/bin/security \
-T /System/Library/CoreServices/NetAuthAgent.app/Contents/MacOS/NetAuthSysAgent \
-T /System/Library/CoreServices/NetAuthAgent.app \
-T group://NetAuth \
${_AppAccess} \
"${LOGINHOME}"/Library/Keychains/login.keychain 2>&1)"
_RC=${?}
if [ ${_RC} -eq ${SUCCESS} ]; then
log --priority=${LOG_INFO} "successfully added password to keychain."
else
log --priority=${LOG_ERROR} "error adding password to keychain. (RC=${_RC}, RV=${_RV})"
fi
exit ${_RC}
}
function create_lock {
local _RV _RunningPID
local -i _RC=${TRUE}
_RV="$( { mkdir "${LOCK_APN}" && echo "${$}" > "${LOCK_AFN}"; } 2>&1 || false )"
_RC=${?}
if [ ${_RC} -ne ${SUCCESS} ]; then
if [ -s "${LOCK_AFN}" ]; then
_RunningPID="$(cat "${LOCK_AFN}")"
_RV="$(pgrep -f -l -F "${LOCK_AFN}" "${SCRIPT_FN}" 2>&1)"
_RC=${?}
else
_RunningPID=""
_RV="$(pgrep -f -l "${SCRIPT_FN}" 2>&1)"
_RC=${?}
fi
if [ ${_RC} -eq ${FOUND} ]; then
log --priority=${LOG_ERROR} "${SCRIPT_FN} is already running${_RunningPID:+ with PID ${_RunningPID}}"
exit 1
else
_RV="$( { rm -rf "${LOCK_APN}" && mkdir "${LOCK_APN}" && echo "${$}" > "${LOCK_AFN}"; } 2>&1 || false )"
_RC=${?}
if [ ${_RC} -ne ${SUCCESS} ]; then
log --priority=${LOG_ERROR} "Could not create '${LOCK_AFN}', exiting (RC=${_RC}, RV=${_RV})"
exit 1
fi
fi
fi
}
# Main
# catch traps
catchTrap 'cleanup' ${SIGHUP} ${SIGINT} ${SIGQUIT} ${SIGTERM}
create_lock
while :; do
case ${1} in
-h|-\?|--help) # Call a "showUsage" function to display a synopsis, then exit.
showUsage
exit
;;
-n|--simulate)
Simulate=${YES}
Action="processMountlist"
;;
-o|--domain)
if [[ -n "${2}" && "${2:0:2}" != "--" && "${2:0:1}" != "-" ]]; then
Domain="${2}"
shift
else
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
exit 1
fi
;;
--domain=?*)
Domain=${1#*=} # Delete everything up to "=" and assign the remainder.
;;
--domain=) # Handle the case of an empty --domain=
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
exit 1
;;
-a|--account)
if [[ -n "${2}" && "${2:0:2}" != "--" && "${2:0:1}" != "-" ]]; then
Account="${2}"
shift
else
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
exit 1
fi
;;
--account=?*)
Account=${1#*=} # Delete everything up to "=" and assign the remainder.
;;
--account=) # Handle the case of an empty --account=
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
exit 1
;;
-d|--description)
if [[ -n "${2}" && "${2:0:2}" != "--" && "${2:0:1}" != "-" ]]; then
Description="${2}"
shift
else
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
exit 1
fi
;;
--description=?*)
Description=${1#*=}
;;
--description=)
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
exit 1
;;
-p|--protocol)
if [[ -n "${2}" && "${2:0:2}" != "--" && "${2:0:1}" != "-" ]]; then
Protocol="${2}"
shift
else
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
exit 1
fi
;;
--protocol=?*)
Protocol=${1#*=}
;;
--protocol=)
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
exit 1
;;
-s|--server)
if [[ -n "${2}" && "${2:0:2}" != "--" && "${2:0:1}" != "-" ]]; then
Server="${2}"
shift
else
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
exit 1
fi
;;
--server=?*)
Server=${1#*=}
;;
--server=)
printf 'ERROR: "%s" requires a non-empty option argument.\n' "${1}" >&2
exit 1
;;
--addpassword)
Action="addPassword"
;;
-m|--mountall)