aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/linden/indra/mac_updater/mac_updater.cpp
blob: 79783d370562149e44cd5551f4b951e36f4588da (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
/** 
 * @file mac_updater.cpp
 * @brief 
 *
 * $LicenseInfo:firstyear=2006&license=viewergpl$
 * 
 * Copyright (c) 2006-2009, Linden Research, Inc.
 * 
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 * 
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 * 
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 * 
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#include "linden_common.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <curl/curl.h>
#include <pthread.h>

#include "llerror.h"
#include "lltimer.h"
#include "lldir.h"
#include "llfile.h"

#include "llstring.h"

#include <Carbon/Carbon.h>

#include "MoreFilesX.h"
#include "FSCopyObject.h"

#include "llerrorcontrol.h"

enum
{
	kEventClassCustom = 'Cust',
	kEventCustomProgress = 'Prog',
	kEventParamCustomCurValue = 'Cur ',
	kEventParamCustomMaxValue = 'Max ',
	kEventParamCustomText = 'Text',
	kEventCustomDone = 'Done',
};

WindowRef gWindow = NULL;
EventHandlerRef gEventHandler = NULL;
OSStatus gFailure = noErr;
Boolean gCancelled = false;

const char *gUpdateURL;
const char *gProductName;

void *updatethreadproc(void*);

pthread_t updatethread;

OSStatus setProgress(int cur, int max)
{
	OSStatus err;
	ControlRef progressBar = NULL;
	ControlID id;

	id.signature = 'prog';
	id.id = 0;

	err = GetControlByID(gWindow, &id, &progressBar);
	if(err == noErr)
	{
		Boolean indeterminate;
		
		if(max == 0)
		{
			indeterminate = true;
			err = SetControlData(progressBar, kControlEntireControl, kControlProgressBarIndeterminateTag, sizeof(Boolean), (Ptr)&indeterminate);
		}
		else
		{
			double percentage = (double)cur / (double)max;
			SetControlMinimum(progressBar, 0);
			SetControlMaximum(progressBar, 100);
			SetControlValue(progressBar, (SInt16)(percentage * 100));

			indeterminate = false;
			err = SetControlData(progressBar, kControlEntireControl, kControlProgressBarIndeterminateTag, sizeof(Boolean), (Ptr)&indeterminate);

			Draw1Control(progressBar);
		}
	}

	return(err);
}

OSStatus setProgressText(CFStringRef text)
{
	OSStatus err;
	ControlRef progressText = NULL;
	ControlID id;

	id.signature = 'what';
	id.id = 0;

	err = GetControlByID(gWindow, &id, &progressText);
	if(err == noErr)
	{
		err = SetControlData(progressText, kControlEntireControl, kControlStaticTextCFStringTag, sizeof(CFStringRef), (Ptr)&text);
		Draw1Control(progressText);
	}

	return(err);
}

OSStatus sendProgress(long cur, long max, CFStringRef text = NULL)
{
	OSStatus result;
	EventRef evt;
	
	result = CreateEvent( 
			NULL,
			kEventClassCustom, 
			kEventCustomProgress,
			0, 
			kEventAttributeNone, 
			&evt);
	
	// This event needs to be targeted at the window so it goes to the window's handler.
	if(result == noErr)
	{
		EventTargetRef target = GetWindowEventTarget(gWindow);
		result = SetEventParameter (
			evt,
			kEventParamPostTarget,
			typeEventTargetRef,
			sizeof(target),
			&target);
	}

	if(result == noErr)
	{
		result = SetEventParameter (
			evt,
			kEventParamCustomCurValue,
			typeLongInteger,
			sizeof(cur),
			&cur);
	}

	if(result == noErr)
	{
		result = SetEventParameter (
			evt,
			kEventParamCustomMaxValue,
			typeLongInteger,
			sizeof(max),
			&max);
	}
	
	if(result == noErr)
	{
		if(text != NULL)
		{
			result = SetEventParameter (
				evt,
				kEventParamCustomText,
				typeCFStringRef,
				sizeof(text),
				&text);
		}
	}
	
	if(result == noErr)
	{
		// Send the event
		PostEventToQueue(
			GetMainEventQueue(),
			evt,
			kEventPriorityStandard);

	}
	
	return(result);
}

OSStatus sendDone(void)
{
	OSStatus result;
	EventRef evt;
	
	result = CreateEvent( 
			NULL,
			kEventClassCustom, 
			kEventCustomDone,
			0, 
			kEventAttributeNone, 
			&evt);
	
	// This event needs to be targeted at the window so it goes to the window's handler.
	if(result == noErr)
	{
		EventTargetRef target = GetWindowEventTarget(gWindow);
		result = SetEventParameter (
			evt,
			kEventParamPostTarget,
			typeEventTargetRef,
			sizeof(target),
			&target);
	}

	if(result == noErr)
	{
		// Send the event
		PostEventToQueue(
			GetMainEventQueue(),
			evt,
			kEventPriorityStandard);

	}
	
	return(result);
}

OSStatus dialogHandler(EventHandlerCallRef handler, EventRef event, void *userdata)
{
	OSStatus result = eventNotHandledErr;
	OSStatus err;
	UInt32 evtClass = GetEventClass(event);
	UInt32 evtKind = GetEventKind(event);
	
	if((evtClass == kEventClassCommand) && (evtKind == kEventCommandProcess))
	{
		HICommand cmd;
		err = GetEventParameter(event, kEventParamDirectObject, typeHICommand, NULL, sizeof(cmd), NULL, &cmd);
		
		if(err == noErr)
		{
			switch(cmd.commandID)
			{				
				case kHICommandCancel:
					gCancelled = true;
//					QuitAppModalLoopForWindow(gWindow);
					result = noErr;
				break;
			}
		}
	}
	else if((evtClass == kEventClassCustom) && (evtKind == kEventCustomProgress))
	{
		// Request to update the progress dialog
		long cur = 0;
		long max = 0;
		CFStringRef text = NULL;
		(void) GetEventParameter(event, kEventParamCustomCurValue, typeLongInteger, NULL, sizeof(cur), NULL, &cur);
		(void) GetEventParameter(event, kEventParamCustomMaxValue, typeLongInteger, NULL, sizeof(max), NULL, &max);
		(void) GetEventParameter(event, kEventParamCustomText, typeCFStringRef, NULL, sizeof(text), NULL, &text);
		
		err = setProgress(cur, max);
		if(err == noErr)
		{
			if(text != NULL)
			{
				setProgressText(text);
			}
		}
		
		result = noErr;
	}
	else if((evtClass == kEventClassCustom) && (evtKind == kEventCustomDone))
	{
		// We're done.  Exit the modal loop.
		QuitAppModalLoopForWindow(gWindow);
		result = noErr;
	}
	
	return(result);
}

#if 0
size_t curl_download_callback(void *data, size_t size, size_t nmemb,
										  void *user_data)
{
	S32 bytes = size * nmemb;
	char *cdata = (char *) data;
	for (int i =0; i < bytes; i += 1)
	{
		gServerResponse.append(cdata[i]);
	}
	return bytes;
}
#endif

int curl_progress_callback_func(void *clientp,
							  double dltotal,
							  double dlnow,
							  double ultotal,
							  double ulnow)
{
	int max = (int)(dltotal / 1024.0);
	int cur = (int)(dlnow / 1024.0);
	sendProgress(cur, max);
	
	if(gCancelled)
		return(1);

	return(0);
}

int parse_args(int argc, char **argv)
{
	int j;

	for (j = 1; j < argc; j++) 
	{
		if ((!strcmp(argv[j], "-url")) && (++j < argc)) 
		{
			gUpdateURL = argv[j];
		}
		else if ((!strcmp(argv[j], "-name")) && (++j < argc)) 
		{
			gProductName = argv[j];
		}
	}

	return 0;
}

int main(int argc, char **argv)
{
	// We assume that all the logs we're looking for reside on the current drive
	gDirUtilp->initAppDirs("SecondLife");

	LLError::initForApplication( gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""));

	// Rename current log file to ".old"
	std::string old_log_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, "updater.log.old");
	std::string log_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, "updater.log");
	LLFile::rename(log_file.c_str(), old_log_file.c_str());

	// Set the log file to updater.log
	LLError::logToFile(log_file);

	/////////////////////////////////////////
	//
	// Process command line arguments
	//
	gUpdateURL  = NULL;
	gProductName = NULL;
	parse_args(argc, argv);
	if (!gUpdateURL)
	{
		llinfos << "Usage: mac_updater -url <url> [-name <product_name>] [-program <program_name>]" << llendl;
		exit(1);
	}
	else
	{
		llinfos << "Update url is: " << gUpdateURL << llendl;
		if (gProductName)
		{
			llinfos << "Product name is: " << gProductName << llendl;
		}
		else
		{
			gProductName = "meta-impy";
		}
	}
	
	llinfos << "Starting " << gProductName << " Updater" << llendl;

	// Real UI...
	OSStatus err;
	IBNibRef nib = NULL;
	
	err = CreateNibReference(CFSTR("AutoUpdater"), &nib);

	char windowTitle[MAX_PATH];		/* Flawfinder: ignore */
	snprintf(windowTitle, sizeof(windowTitle), "%s Updater", gProductName);		
	CFStringRef windowTitleRef = NULL;
	windowTitleRef = CFStringCreateWithCString(NULL, windowTitle, kCFStringEncodingUTF8);
	
	if(err == noErr)
	{
		err = CreateWindowFromNib(nib, CFSTR("Updater"), &gWindow);
	}

	if (err == noErr)
	{
		err = SetWindowTitleWithCFString(gWindow, windowTitleRef);	
	}
	CFRelease(windowTitleRef);

	if(err == noErr)
	{
		// Set up an event handler for the window.
		EventTypeSpec handlerEvents[] = 
		{
			{ kEventClassCommand, kEventCommandProcess },
			{ kEventClassCustom, kEventCustomProgress },
			{ kEventClassCustom, kEventCustomDone }
		};
		InstallStandardEventHandler(GetWindowEventTarget(gWindow));
		InstallWindowEventHandler(
				gWindow, 
				NewEventHandlerUPP(dialogHandler), 
				GetEventTypeCount (handlerEvents), 
				handlerEvents, 
				0, 
				&gEventHandler);
	}
	
	if(err == noErr)
	{
		ShowWindow(gWindow);
		SelectWindow(gWindow);
	}
		
	if(err == noErr)
	{
		pthread_create(&updatethread, 
                         NULL,
                         &updatethreadproc, 
                         NULL);
						 
	}
	
	if(err == noErr)
	{
		RunAppModalLoopForWindow(gWindow);
	}

	void *threadresult;

	pthread_join(updatethread, &threadresult);

	if(!gCancelled && (gFailure != noErr))
	{
		// Something went wrong.  Since we always just tell the user to download a new version, we don't really care what.
		AlertStdCFStringAlertParamRec params;
		SInt16 retval_mac = 1;
		DialogRef alert = NULL;
		OSStatus err;

		params.version = kStdCFStringAlertVersionOne;
		params.movable = false;
		params.helpButton = false;
		params.defaultText = (CFStringRef)kAlertDefaultOKText;
		params.cancelText = 0;
		params.otherText = 0;
		params.defaultButton = 1;
		params.cancelButton = 0;
		params.position = kWindowDefaultPosition;
		params.flags = 0;

		err = CreateStandardAlert(
				kAlertStopAlert,
				CFSTR("Error"),
				CFSTR("An error occurred while updating meta-impy.  Please download the latest version from http://www.meta7.com/download.php"),
				&params,
				&alert);
		
		if(err == noErr)
		{
			err = RunStandardAlert(
					alert,
					NULL,
					&retval_mac);
		}

	}
	
	// Don't dispose of things, just exit.  This keeps the update thread from potentially getting hosed.
	exit(0);

	if(gWindow != NULL)
	{
		DisposeWindow(gWindow);
	}
	
	if(nib != NULL)
	{
		DisposeNibReference(nib);
	}
	
	return 0;
}

bool isDirWritable(FSRef &dir)
{
	bool result = false;
	
	// Test for a writable directory by creating a directory, then deleting it again.
	// This is kinda lame, but will pretty much always give the right answer.
	
	OSStatus err = noErr;
	char temp[PATH_MAX] = "";		/* Flawfinder: ignore */

	err = FSRefMakePath(&dir, (UInt8*)temp, sizeof(temp));

	if(err == noErr)
	{
		strncat(temp, "/.test_XXXXXX", (sizeof(temp) - strlen(temp)) - 1);
		
		if(mkdtemp(temp) != NULL)
		{
			// We were able to make the directory.  This means the directory is writable.
			result = true;
			
			// Clean up.
			rmdir(temp);
		}
	}

#if 0
	// This seemed like a good idea, but won't tell us if we're on a volume mounted read-only.
	UInt8 perm;
	err = FSGetUserPrivilegesPermissions(&targetParentRef, &perm, NULL);
	if(err == noErr)
	{
		if(perm & kioACUserNoMakeChangesMask)
		{
			// Parent directory isn't writable.
			llinfos << "Target parent directory not writable." << llendl;
			err = -1;
			replacingTarget = false;
		}
	}
#endif

	return result;
}

static void utf8str_to_HFSUniStr255(HFSUniStr255 *dest, const char* src)
{
	llutf16string	utf16str = utf8str_to_utf16str(src);

	dest->length = utf16str.size();
	if(dest->length > 255)
	{
		// There's onl room for 255 chars in a HFSUniStr25..
		// Truncate to avoid stack smaching or other badness.
		dest->length = 255;
	}
	memcpy(dest->unicode, utf16str.data(), sizeof(UniChar)* dest->length);		/* Flawfinder: ignore */
}

static std::string HFSUniStr255_to_utf8str(const HFSUniStr255* src)
{
	llutf16string string16((U16*)&(src->unicode), src->length);
	std::string result = utf16str_to_utf8str(string16);
	return result;
}

int restoreObject(const char* aside, const char* target, const char* path, const char* object)
{
	char source[PATH_MAX] = "";		/* Flawfinder: ignore */
	char dest[PATH_MAX] = "";		/* Flawfinder: ignore */
	snprintf(source, sizeof(source), "%s/%s/%s", aside, path, object);		
	snprintf(dest, sizeof(dest), "%s/%s", target, path);		
	FSRef sourceRef;
	FSRef destRef;
	OSStatus err;
	err = FSPathMakeRef((UInt8 *)source, &sourceRef, NULL);
	if(err != noErr) return false;
	err = FSPathMakeRef((UInt8 *)dest, &destRef, NULL);
	if(err != noErr) return false;

	llinfos << "Copying " << source << " to " << dest << llendl;

	err = FSCopyObject(	
			&sourceRef,
			&destRef,
			0,
			kFSCatInfoNone,
			kDupeActionReplace,
			NULL,
			false,
			false,
			NULL,
			NULL,
			NULL,
			NULL);

	if(err != noErr) return false;
	return true;
}

// Replace any mention of "Second Life" with the product name.
void filterFile(const char* filename)
{
	char temp[PATH_MAX] = "";		/* Flawfinder: ignore */
	// First copy the target's version, so we can run it through sed.
	snprintf(temp, sizeof(temp), "cp '%s' '%s.tmp'", filename, filename);		
	system(temp);		/* Flawfinder: ignore */

	// Now run it through sed.
	snprintf(temp, sizeof(temp), 		
			"sed 's/Second Life/%s/g' '%s.tmp' > '%s'", gProductName, filename, filename);
	system(temp);		/* Flawfinder: ignore */
}

static bool isFSRefViewerBundle(FSRef *targetRef)
{
	bool result = false;
	CFURLRef targetURL = NULL;
	CFBundleRef targetBundle = NULL;
	CFStringRef targetBundleID = NULL;
	
	targetURL = CFURLCreateFromFSRef(NULL, targetRef);

	if(targetURL == NULL)
	{
		llinfos << "Error creating target URL." << llendl;
	}
	else
	{
		targetBundle = CFBundleCreate(NULL, targetURL);
	}
	
	if(targetBundle == NULL)
	{
		llinfos << "Failed to create target bundle." << llendl;
	}
	else
	{
		targetBundleID = CFBundleGetIdentifier(targetBundle);
	}
	
	if(targetBundleID == NULL)
	{
		llinfos << "Couldn't retrieve target bundle ID." << llendl;
	}
	else
	{
		if(CFStringCompare(targetBundleID, CFSTR("org.imprudenceviewer.viewer"), 0) == kCFCompareEqualTo)
		{
			// This is the bundle we're looking for.
			result = true;
		}
		else
		{
			llinfos << "Target bundle ID mismatch." << llendl;
		}
	}
	
	// Don't release targetBundleID -- since we don't retain it, it's released when targetBundle is released.
	if(targetURL != NULL)
		CFRelease(targetURL);
	if(targetBundle != NULL)
		CFRelease(targetBundle);
	
	return result;
}

// Search through the directory specified by 'parent' for an item that appears to be a viewer.
static OSErr findAppBundleOnDiskImage(FSRef *parent, FSRef *app)
{
	FSIterator		iterator;
	bool			found = false;

	OSErr err = FSOpenIterator( parent, kFSIterateFlat, &iterator );
	if(!err)
	{
		do
		{
			ItemCount actualObjects = 0;
			Boolean containerChanged = false;
			FSCatalogInfo info;
			FSRef ref;
			HFSUniStr255 unicodeName;
			err = FSGetCatalogInfoBulk( 
					iterator, 
					1, 
					&actualObjects, 
					&containerChanged,
					kFSCatInfoNodeFlags, 
					&info, 
					&ref,
					NULL, 
					&unicodeName );
			
			if(actualObjects == 0)
				break;
				
			if(!err)
			{
				// Call succeeded and not done with the iteration.
				std::string name = HFSUniStr255_to_utf8str(&unicodeName);

				llinfos << "Considering \"" << name << "\"" << llendl;

				if(info.nodeFlags & kFSNodeIsDirectoryMask)
				{
					// This is a directory.  See if it's a .app
					if(name.find(".app") != std::string::npos)
					{
						// Looks promising.  Check to see if it has the right bundle identifier.
						if(isFSRefViewerBundle(&ref))
						{
							// This is the one.  Return it.
							*app = ref;
							found = true;
						}
					}
				}
			}
		}
		while(!err && !found);
		
		FSCloseIterator(iterator);
	}
	
	if(!err && !found)
		err = fnfErr;
		
	return err;
}

void *updatethreadproc(void*)
{
	char tempDir[PATH_MAX] = "";		/* Flawfinder: ignore */
	FSRef tempDirRef;
	char temp[PATH_MAX] = "";	/* Flawfinder: ignore */
	// *NOTE: This buffer length is used in a scanf() below.
	char deviceNode[1024] = "";	/* Flawfinder: ignore */
	LLFILE *downloadFile = NULL;
	OSStatus err;
	ProcessSerialNumber psn;
	char target[PATH_MAX] = "";		/* Flawfinder: ignore */
	FSRef targetRef;
	FSRef targetParentRef;
	FSVolumeRefNum targetVol;
	FSRef trashFolderRef;
	Boolean replacingTarget = false;

	memset(&tempDirRef, 0, sizeof(tempDirRef));
	memset(&targetRef, 0, sizeof(targetRef));
	memset(&targetParentRef, 0, sizeof(targetParentRef));
	
	try
	{
		// Attempt to get a reference to the viewer application bundle containing this updater.
		// Any failures during this process will cause us to default to updating /Applications/Second Life.app
		{
			FSRef myBundle;

			err = GetCurrentProcess(&psn);
			if(err == noErr)
			{
				err = GetProcessBundleLocation(&psn, &myBundle);
			}

			if(err == noErr)
			{
				// Sanity check:  Make sure the name of the item referenced by targetRef is "Second Life.app".
				FSRefMakePath(&myBundle, (UInt8*)target, sizeof(target));
				
				llinfos << "Updater bundle location: " << target << llendl;
			}
			
			// Our bundle should be in Second Life.app/Contents/Resources/AutoUpdater.app
			// so we need to go up 3 levels to get the path to the main application bundle.
			if(err == noErr)
			{
				err = FSGetParentRef(&myBundle, &targetRef);
			}
			if(err == noErr)
			{
				err = FSGetParentRef(&targetRef, &targetRef);
			}
			if(err == noErr)
			{
				err = FSGetParentRef(&targetRef, &targetRef);
			}
			
			// And once more to get the parent of the target
			if(err == noErr)
			{
				err = FSGetParentRef(&targetRef, &targetParentRef);
			}
			
			if(err == noErr)
			{
				FSRefMakePath(&targetRef, (UInt8*)target, sizeof(target));
				llinfos << "Path to target: " << target << llendl;
			}
			
			// Sanity check: make sure the target is a bundle with the right identifier
			if(err == noErr)
			{
				// Assume the worst...
				err = -1;

				if(isFSRefViewerBundle(&targetRef))
				{
					// This is the bundle we're looking for.
					err = noErr;
					replacingTarget = true;
				}
			}
			
			// Make sure the target's parent directory is writable.
			if(err == noErr)
			{
				if(!isDirWritable(targetParentRef))
				{
					// Parent directory isn't writable.
					llinfos << "Target parent directory not writable." << llendl;
					err = -1;
					replacingTarget = false;
				}
			}

			if(err != noErr)
			{
				Boolean isDirectory;
				llinfos << "Target search failed, defaulting to /Applications/" << gProductName << ".app." << llendl;
				
				// Set up the parent directory
				err = FSPathMakeRef((UInt8*)"/Applications", &targetParentRef, &isDirectory);
				if((err != noErr) || (!isDirectory))
				{
					// We're so hosed.
					llinfos << "Applications directory not found, giving up." << llendl;
					throw 0;
				}
				
				snprintf(target, sizeof(target), "/Applications/%s.app", gProductName);		

				memset(&targetRef, 0, sizeof(targetRef));
				err = FSPathMakeRef((UInt8*)target, &targetRef, NULL);
				if(err == fnfErr)
				{
					// This is fine, just means we're not replacing anything.
					err = noErr;
					replacingTarget = false;
				}
				else
				{
					replacingTarget = true;
				}

				// Make sure the target's parent directory is writable.
				if(err == noErr)
				{
					if(!isDirWritable(targetParentRef))
					{
						// Parent directory isn't writable.
						llinfos << "Target parent directory not writable." << llendl;
						err = -1;
						replacingTarget = false;
					}
				}

			}
			
			// If we haven't fixed all problems by this point, just bail.
			if(err != noErr)
			{
				llinfos << "Unable to pick a target, giving up." << llendl;
				throw 0;
			}
		}
		
		// Find the volID of the volume the target resides on
		{
			FSCatalogInfo info;
			err = FSGetCatalogInfo(
				&targetParentRef,
				kFSCatInfoVolume,
				&info,
				NULL, 
				NULL,  
				NULL);
				
			if(err != noErr)
				throw 0;
			
			targetVol = info.volume;
		}

		// Find the temporary items and trash folders on that volume.
		err = FSFindFolder(
			targetVol,
			kTrashFolderType,
			true,
			&trashFolderRef);

		if(err != noErr)
			throw 0;

#if 0 // *HACK for DEV-11935 see below for details.

		FSRef tempFolderRef;

		err = FSFindFolder(
			targetVol,
			kTemporaryFolderType,
			true,
			&tempFolderRef);
		
		if(err != noErr)
			throw 0;
		
		err = FSRefMakePath(&tempFolderRef, (UInt8*)temp, sizeof(temp));

		if(err != noErr)
			throw 0;

#else		

		// *HACK for DEV-11935  the above kTemporaryFolderType query was giving
		// back results with path names that seem to be too long to be used as
		// mount points.  I suspect this incompatibility was introduced in the
		// Leopard 10.5.2 update, but I have not verified this. 
		char const HARDCODED_TMP[] = "/tmp";
		strncpy(temp, HARDCODED_TMP, sizeof(HARDCODED_TMP));

#endif // 0 *HACK for DEV-11935
		
		strncat(temp, "/meta-impyUpdate_XXXXXX", (sizeof(temp) - strlen(temp)) - 1);
		if(mkdtemp(temp) == NULL)
		{
			throw 0;
		}
		
		strncpy(tempDir, temp, sizeof(tempDir));
		temp[sizeof(tempDir) - 1] = '\0';
		
		llinfos << "tempDir is " << tempDir << llendl;

		err = FSPathMakeRef((UInt8*)tempDir, &tempDirRef, NULL);

		if(err != noErr)
			throw 0;
				
		chdir(tempDir);
		
		snprintf(temp, sizeof(temp), "meta-impy.dmg");		
		
		downloadFile = LLFile::fopen(temp, "wb");		/* Flawfinder: ignore */
		if(downloadFile == NULL)
		{
			throw 0;
		}

		{
			CURL *curl = curl_easy_init();

			curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
	//		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &curl_download_callback);
			curl_easy_setopt(curl, CURLOPT_FILE, downloadFile);
			curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
			curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, &curl_progress_callback_func);
			curl_easy_setopt(curl, CURLOPT_URL,	gUpdateURL);
			curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
			
			sendProgress(0, 1, CFSTR("Downloading..."));
			
			CURLcode result = curl_easy_perform(curl);
			
			curl_easy_cleanup(curl);
			
			if(gCancelled)
			{
				llinfos << "User cancel, bailing out."<< llendl;
				throw 0;
			}
			
			if(result != CURLE_OK)
			{
				llinfos << "Error " << result << " while downloading disk image."<< llendl;
				throw 0;
			}
			
			fclose(downloadFile);
			downloadFile = NULL;
		}
		
		sendProgress(0, 0, CFSTR("Mounting image..."));
		LLFile::mkdir("mnt", 0700);
		
		// NOTE: we could add -private at the end of this command line to keep the image from showing up in the Finder,
		//		but if our cleanup fails, this makes it much harder for the user to unmount the image.
		std::string mountOutput;
		FILE* mounter = popen("hdiutil attach meta-impy.dmg -mountpoint mnt", "r");		/* Flawfinder: ignore */
		
		if(mounter == NULL)
		{
			llinfos << "Failed to mount disk image, exiting."<< llendl;
			throw 0;
		}
		
		// We need to scan the output from hdiutil to find the device node it uses to attach the disk image.
		// If we don't have this information, we can't detach it later.
		while(mounter != NULL)
		{
			size_t len = fread(temp, 1, sizeof(temp)-1, mounter);
			temp[len] = 0;
			mountOutput.append(temp);
			if(len < sizeof(temp)-1)
			{
				// End of file or error.
				int result = pclose(mounter);
				if(result != 0)
				{
					// NOTE: We used to abort here, but pclose() started returning 
					// -1, possibly when the size of the DMG passed a certain point 
					llinfos << "Unexpected result closing pipe: " << result << llendl; 
				}
				mounter = NULL;
			}
		}
		
		if(!mountOutput.empty())
		{
			const char *s = mountOutput.c_str();
			const char *prefix = "/dev/";
			char *sub = strstr(s, prefix);
			
			if(sub != NULL)
			{
				sub += strlen(prefix);	/* Flawfinder: ignore */
				sscanf(sub, "%1023s", deviceNode);	/* Flawfinder: ignore */
			}
		}
		
		if(deviceNode[0] != 0)
		{
			llinfos << "Disk image attached on /dev/" << deviceNode << llendl;
		}
		else
		{
			llinfos << "Disk image device node not found!" << llendl;
			throw 0; 
		}
		
		// Get an FSRef to the new application on the disk image
		FSRef sourceRef;
		FSRef mountRef;
		snprintf(temp, sizeof(temp), "%s/mnt", tempDir);		

		llinfos << "Disk image mount point is: " << temp << llendl;

		err = FSPathMakeRef((UInt8 *)temp, &mountRef, NULL);
		if(err != noErr)
		{
			llinfos << "Couldn't make FSRef to disk image mount point." << llendl;
			throw 0;
		}

		err = findAppBundleOnDiskImage(&mountRef, &sourceRef);
		if(err != noErr)
		{
			llinfos << "Couldn't find application bundle on mounted disk image." << llendl;
			throw 0;
		}
		
		FSRef asideRef;
		char aside[MAX_PATH];		/* Flawfinder: ignore */
		
		// this will hold the name of the destination target
		HFSUniStr255 appNameUniStr;

		if(replacingTarget)
		{
			// Get the name of the target we're replacing
			err = FSGetCatalogInfo(&targetRef, 0, NULL, &appNameUniStr, NULL, NULL);
			if(err != noErr)
				throw 0;
			
			// Move aside old version (into work directory)
			err = FSMoveObject(&targetRef, &tempDirRef, &asideRef);
			if(err != noErr)
				throw 0;

			// Grab the path for later use.
			err = FSRefMakePath(&asideRef, (UInt8*)aside, sizeof(aside));
		}
		else
		{
			// Construct the name of the target based on the product name
			char appName[MAX_PATH];		/* Flawfinder: ignore */
			snprintf(appName, sizeof(appName), "%s.app", gProductName);		
			utf8str_to_HFSUniStr255( &appNameUniStr, appName );
		}
		
		sendProgress(0, 0, CFSTR("Copying files..."));
		
		llinfos << "Starting copy..." << llendl;

		// Copy the new version from the disk image to the target location.
		err = FSCopyObject(	
				&sourceRef,
				&targetParentRef,
				0,
				kFSCatInfoNone,
				kDupeActionStandard,
				&appNameUniStr,
				false,
				false,
				NULL,
				NULL,
				&targetRef,
				NULL);
		
		// Grab the path for later use.
		err = FSRefMakePath(&targetRef, (UInt8*)target, sizeof(target));
		if(err != noErr)
			throw 0;

		llinfos << "Copy complete. Target = " << target << llendl;

		if(err != noErr)
		{
			// Something went wrong during the copy.  Attempt to put the old version back and bail.
			(void)FSDeleteObjects(&targetRef);
			if(replacingTarget)
			{
				(void)FSMoveObject(&asideRef, &targetParentRef, NULL);
			}
			throw 0;
		}
		else
		{
			// The update has succeeded.  Clear the cache directory.

			sendProgress(0, 0, CFSTR("Clearing cache..."));
	
			llinfos << "Clearing cache..." << llendl;
			
			char mask[LL_MAX_PATH];		/* Flawfinder: ignore */
			snprintf(mask, LL_MAX_PATH, "%s*.*", gDirUtilp->getDirDelimiter().c_str());		
			gDirUtilp->deleteFilesInDir(gDirUtilp->getExpandedFilename(LL_PATH_CACHE,""),mask);
			
			llinfos << "Clear complete." << llendl;

		}
	}
	catch(...)
	{
		if(!gCancelled)
			if(gFailure == noErr)
				gFailure = -1;
	}

	// Failures from here on out are all non-fatal and not reported.
	sendProgress(0, 3, CFSTR("Cleaning up..."));

	// Close disk image file if necessary
	if(downloadFile != NULL)
	{
		llinfos << "Closing download file." << llendl;

		fclose(downloadFile);
		downloadFile = NULL;
	}

	sendProgress(1, 3);
	// Unmount image
	if(deviceNode[0] != 0)
	{
		llinfos << "Detaching disk image." << llendl;

		snprintf(temp, sizeof(temp), "hdiutil detach '%s'", deviceNode);		
		system(temp);		/* Flawfinder: ignore */
	}

	sendProgress(2, 3);

	// Move work directory to the trash
	if(tempDir[0] != 0)
	{
//		chdir("/");
//		FSDeleteObjects(tempDirRef);

		llinfos << "Moving work directory to the trash." << llendl;

		err = FSMoveObject(&tempDirRef, &trashFolderRef, NULL);

//		snprintf(temp, sizeof(temp), "rm -rf '%s'", tempDir);
//		printf("%s\n", temp);
//		system(temp);
	}
	
	if(!gCancelled  && !gFailure && (target[0] != 0))
	{
		llinfos << "Touching application bundle." << llendl;

		snprintf(temp, sizeof(temp), "touch '%s'", target);		
		system(temp);		/* Flawfinder: ignore */

		llinfos << "Launching updated application." << llendl;

		snprintf(temp, sizeof(temp), "open '%s'", target);		
		system(temp);		/* Flawfinder: ignore */
	}

	sendDone();
	
	return(NULL);
}