1 | #include <functional> |
---|
2 | #include <memory> |
---|
3 | #include <iostream> |
---|
4 | #include <algorithm> |
---|
5 | #include <string> |
---|
6 | #include <list> |
---|
7 | #include <sys/stat.h> |
---|
8 | #include <stdlib.h> |
---|
9 | #include <future> |
---|
10 | #include <vector> |
---|
11 | |
---|
12 | #import <Foundation/Foundation.h> |
---|
13 | #import <Foundation/NSFileManager.h> |
---|
14 | #include <CoreFoundation/CFPreferences.h> |
---|
15 | |
---|
16 | #import <objc/Object.h> |
---|
17 | #import <Cocoa/Cocoa.h> |
---|
18 | #import <AppKit/AppKit.h> |
---|
19 | #import <AppKit/NSApplication.h> |
---|
20 | |
---|
21 | #import "I2PLauncher-Swift.h" |
---|
22 | |
---|
23 | #include "AppDelegate.h" |
---|
24 | #include "RouterTask.h" |
---|
25 | #include "include/fn.h" |
---|
26 | #include "include/portcheck.h" |
---|
27 | #import "SBridge.h" |
---|
28 | |
---|
29 | #ifdef __cplusplus |
---|
30 | #include <string> |
---|
31 | |
---|
32 | #include "include/subprocess.hpp" |
---|
33 | #include "include/strutil.hpp" |
---|
34 | |
---|
35 | using namespace subprocess; |
---|
36 | |
---|
37 | #endif |
---|
38 | |
---|
39 | #define debug(format, ...) CFShow([NSString stringWithFormat:format, ## __VA_ARGS__]); |
---|
40 | |
---|
41 | @interface AppDelegate () <NSUserNotificationCenterDelegate, NSApplicationDelegate> |
---|
42 | @end |
---|
43 | |
---|
44 | |
---|
45 | @implementation ExtractMetaInfo : NSObject |
---|
46 | @end |
---|
47 | |
---|
48 | |
---|
49 | @implementation AppDelegate |
---|
50 | |
---|
51 | - (void) awakeFromNib { |
---|
52 | } |
---|
53 | |
---|
54 | |
---|
55 | - (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center |
---|
56 | shouldPresentNotification:(NSUserNotification *)notification { |
---|
57 | return YES; |
---|
58 | } |
---|
59 | |
---|
60 | #ifdef __cplusplus |
---|
61 | |
---|
62 | - (void)extractI2PBaseDir:(void(^)(BOOL success, NSError *error))completion |
---|
63 | { |
---|
64 | |
---|
65 | NSBundle *launcherBundle = [NSBundle mainBundle]; |
---|
66 | auto homeDir = RealHomeDirectory(); |
---|
67 | NSLog(@"Home directory is %s", homeDir); |
---|
68 | |
---|
69 | std::string basePath(homeDir); |
---|
70 | basePath.append("/Library/I2P"); |
---|
71 | auto jarResPath = [launcherBundle pathForResource:@"launcher" ofType:@"jar"]; |
---|
72 | NSLog(@"Trying to load launcher.jar from url = %@", jarResPath); |
---|
73 | self.metaInfo.jarFile = jarResPath; |
---|
74 | self.metaInfo.zipFile = [launcherBundle pathForResource:@"base" ofType:@"zip"]; |
---|
75 | |
---|
76 | NSParameterAssert(basePath.c_str()); |
---|
77 | NSError *error = NULL; |
---|
78 | BOOL success = NO; |
---|
79 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ |
---|
80 | |
---|
81 | |
---|
82 | try { |
---|
83 | std::string basearg("-Di2p.dir.base="); |
---|
84 | basearg += basePath; |
---|
85 | |
---|
86 | std::string zippath("-Di2p.base.zip="); |
---|
87 | zippath += [self.metaInfo.zipFile UTF8String]; |
---|
88 | |
---|
89 | std::string jarfile("-cp "); |
---|
90 | jarfile += [self.metaInfo.jarFile UTF8String]; |
---|
91 | |
---|
92 | // Create directory |
---|
93 | mkdir(basePath.c_str(), S_IRUSR | S_IWUSR | S_IXUSR); |
---|
94 | |
---|
95 | auto cli = defaultFlagsForExtractorJob; |
---|
96 | setenv("I2PBASE", basePath.c_str(), true); |
---|
97 | setenv("ZIPPATH", zippath.c_str(), true); |
---|
98 | //setenv("DYLD_LIBRARY_PATH",".:/usr/lib:/lib:/usr/local/lib", true); |
---|
99 | |
---|
100 | cli.push_back(basearg); |
---|
101 | cli.push_back(zippath); |
---|
102 | cli.push_back(jarfile); |
---|
103 | cli.push_back("net.i2p.launchers.BaseExtractor"); |
---|
104 | auto rs = [[RouterProcessStatus alloc] init]; |
---|
105 | |
---|
106 | std::string execStr = std::string([rs.getJavaHome UTF8String]); |
---|
107 | for_each(cli, [&execStr](std::string str){ execStr += std::string(" ") + str; }); |
---|
108 | |
---|
109 | NSLog(@"Trying cmd: %@", [NSString stringWithUTF8String:execStr.c_str()]); |
---|
110 | try { |
---|
111 | sendUserNotification(APP_IDSTR, @"Please hold on while we extract I2P. You'll get a new message once done!"); |
---|
112 | int extractStatus = Popen(execStr.c_str(), environment{{ |
---|
113 | {"ZIPPATH", zippath.c_str()}, |
---|
114 | {"I2PBASE", basePath.c_str()} |
---|
115 | }}).wait(); |
---|
116 | NSLog(@"Extraction exit code %@",[NSString stringWithUTF8String:(std::to_string(extractStatus)).c_str()]); |
---|
117 | if (extractStatus == 0) |
---|
118 | { |
---|
119 | NSLog(@"Extraction complete!"); |
---|
120 | } |
---|
121 | |
---|
122 | } catch (subprocess::OSError &err) { |
---|
123 | auto errMsg = [NSString stringWithUTF8String:err.what()]; |
---|
124 | //success = NO; |
---|
125 | NSLog(@"Exception: %@", errMsg); |
---|
126 | sendUserNotification(APP_IDSTR, [NSString stringWithFormat:@"Error: %@", errMsg]); |
---|
127 | } |
---|
128 | |
---|
129 | // All done. Assume success and error are already set. |
---|
130 | dispatch_async(dispatch_get_main_queue(), ^{ |
---|
131 | if (completion) { |
---|
132 | completion(success, error); |
---|
133 | } |
---|
134 | }); |
---|
135 | |
---|
136 | |
---|
137 | } catch (OSError &err) { |
---|
138 | auto errMsg = [NSString stringWithUTF8String:err.what()]; |
---|
139 | NSLog(@"Exception: %@", errMsg); |
---|
140 | } |
---|
141 | }); |
---|
142 | } |
---|
143 | |
---|
144 | - (void)setApplicationDefaultPreferences { |
---|
145 | [self.userPreferences registerDefaults:@{ |
---|
146 | @"enableLogging": @YES, |
---|
147 | @"enableVerboseLogging": @YES, |
---|
148 | @"autoStartRouter": @YES, |
---|
149 | @"i2pBaseDirectory": (NSString *)CFStringCreateWithCString(NULL, const_cast<const char *>(getDefaultBaseDir().c_str()), kCFStringEncodingUTF8) |
---|
150 | }]; |
---|
151 | |
---|
152 | auto dict = [self.userPreferences dictionaryRepresentation]; |
---|
153 | [self.userPreferences setPersistentDomain:dict forName:NSAPPDOMAIN]; |
---|
154 | |
---|
155 | CFPreferencesSetMultiple((CFDictionaryRef)dict, NULL, CFAPPDOMAIN, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost); |
---|
156 | CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication); |
---|
157 | |
---|
158 | if (self.enableVerboseLogging) NSLog(@"Default preferences stored!"); |
---|
159 | } |
---|
160 | |
---|
161 | #endif |
---|
162 | |
---|
163 | |
---|
164 | - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { |
---|
165 | // Init application here |
---|
166 | |
---|
167 | self.swiftRuntime = [[SwiftMainDelegate alloc] init]; |
---|
168 | |
---|
169 | // This setup allows the application to send notifications |
---|
170 | [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self]; |
---|
171 | |
---|
172 | |
---|
173 | // Start with user preferences |
---|
174 | self.userPreferences = [NSUserDefaults standardUserDefaults]; |
---|
175 | [self setApplicationDefaultPreferences]; |
---|
176 | self.enableLogging = [self.userPreferences boolForKey:@"enableLogging"]; |
---|
177 | self.enableVerboseLogging = [self.userPreferences boolForKey:@"enableVerboseLogging"]; |
---|
178 | // In case we are unbundled, make us a proper UI application |
---|
179 | [NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory]; |
---|
180 | [NSApp activateIgnoringOtherApps:YES]; |
---|
181 | |
---|
182 | |
---|
183 | #ifdef __cplusplus |
---|
184 | |
---|
185 | RouterProcessStatus* routerStatus = [[RouterProcessStatus alloc] init]; |
---|
186 | std::string i2pBaseDir(getDefaultBaseDir()); |
---|
187 | NSLog(@"i2pBaseDir = %s", i2pBaseDir.c_str()); |
---|
188 | bool shouldAutoStartRouter = false; |
---|
189 | |
---|
190 | // TODO: Make the port a setting which defaults to 7657 |
---|
191 | if (port_check(7657) != 0) |
---|
192 | { |
---|
193 | NSLog(@"Seems i2p is already running - I will not start the router (port 7657 is in use..)"); |
---|
194 | sendUserNotification(@"Found already running router", @"TCP port 7657 seem to be used by another i2p instance."); |
---|
195 | |
---|
196 | [routerStatus setRouterStatus: true]; |
---|
197 | [routerStatus setRouterRanByUs: false]; |
---|
198 | shouldAutoStartRouter = false; |
---|
199 | } else { |
---|
200 | shouldAutoStartRouter = true; |
---|
201 | } |
---|
202 | |
---|
203 | if (self.enableVerboseLogging) NSLog(@"processinfo %@", [[NSProcessInfo processInfo] arguments]); |
---|
204 | |
---|
205 | |
---|
206 | NSBundle *launcherBundle = [NSBundle mainBundle]; |
---|
207 | |
---|
208 | // Helper object to hold statefull path information |
---|
209 | self.metaInfo = [[ExtractMetaInfo alloc] init]; |
---|
210 | self.metaInfo.i2pBase = [NSString stringWithUTF8String:i2pBaseDir.c_str()]; |
---|
211 | self.metaInfo.javaBinary = [routerStatus getJavaHome]; |
---|
212 | self.metaInfo.jarFile = [launcherBundle pathForResource:@"launcher" ofType:@"jar"]; |
---|
213 | self.metaInfo.zipFile = [launcherBundle pathForResource:@"base" ofType:@"zip"]; |
---|
214 | |
---|
215 | std::string basearg("-Di2p.dir.base="); |
---|
216 | basearg += i2pBaseDir; |
---|
217 | |
---|
218 | std::string jarfile("-cp "); |
---|
219 | jarfile += [self.metaInfo.zipFile UTF8String]; |
---|
220 | |
---|
221 | // Initialize the Swift environment (the UI components) |
---|
222 | [self.swiftRuntime applicationDidFinishLaunching]; |
---|
223 | |
---|
224 | struct stat sb; |
---|
225 | if ( !(stat(i2pBaseDir.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) ) |
---|
226 | { |
---|
227 | // I2P is not extracted. |
---|
228 | if (self.enableVerboseLogging) NSLog(@"I2P Directory don't exists!"); |
---|
229 | |
---|
230 | // Might be hard to read if you're not used to Objective-C |
---|
231 | // But this is a "function call" that contains a "callback function" |
---|
232 | [self extractI2PBaseDir:^(BOOL success, NSError *error) { |
---|
233 | sendUserNotification(@"I2P is done extracting", @"I2P is now installed and ready to run!"); |
---|
234 | NSLog(@"Done extracting I2P"); |
---|
235 | |
---|
236 | NSLog(@"Time to detect I2P version in install directory"); |
---|
237 | [self.swiftRuntime findInstalledI2PVersion]; |
---|
238 | if (shouldAutoStartRouter) { |
---|
239 | [[SBridge sharedInstance] startupI2PRouter:self.metaInfo.i2pBase javaBinPath:self.metaInfo.javaBinary]; |
---|
240 | [routerStatus setRouterRanByUs: true]; |
---|
241 | } |
---|
242 | }]; |
---|
243 | |
---|
244 | } else { |
---|
245 | // I2P was already found extracted |
---|
246 | NSLog(@"Time to detect I2P version in install directory"); |
---|
247 | [self.swiftRuntime findInstalledI2PVersion]; |
---|
248 | |
---|
249 | if (shouldAutoStartRouter) { |
---|
250 | [[SBridge sharedInstance] startupI2PRouter:self.metaInfo.i2pBase javaBinPath:self.metaInfo.javaBinary]; |
---|
251 | [routerStatus setRouterRanByUs: true]; |
---|
252 | } |
---|
253 | } |
---|
254 | |
---|
255 | #endif |
---|
256 | } |
---|
257 | |
---|
258 | |
---|
259 | |
---|
260 | /** |
---|
261 | * |
---|
262 | * Exit sequence |
---|
263 | * |
---|
264 | **/ |
---|
265 | - (void)applicationWillTerminate:(NSNotification *)aNotification { |
---|
266 | // Tear down here |
---|
267 | NSString *string = @"applicationWillTerminate executed"; |
---|
268 | NSLog(@"%@", string); |
---|
269 | [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:nil]; |
---|
270 | } |
---|
271 | |
---|
272 | |
---|
273 | /* wrapper for main */ |
---|
274 | - (AppDelegate *)initWithArgc:(int)argc argv:(const char **)argv { |
---|
275 | return self; |
---|
276 | } |
---|
277 | @end |
---|
278 | |
---|
279 | |
---|
280 | |
---|
281 | int main(int argc, const char **argv) |
---|
282 | { |
---|
283 | NSApplication *app = [NSApplication sharedApplication]; |
---|
284 | |
---|
285 | AppDelegate *appDelegate = [[AppDelegate alloc] initWithArgc:argc argv:argv]; |
---|
286 | app.delegate = appDelegate; |
---|
287 | auto mainBundle = [NSBundle mainBundle]; |
---|
288 | NSString* stringNameBundle = [mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey]; |
---|
289 | if ([[NSRunningApplication runningApplicationsWithBundleIdentifier:[mainBundle bundleIdentifier]] count] > 1) { |
---|
290 | [[NSAlert alertWithMessageText:[NSString stringWithFormat:@"Another copy of %@ is already running.",stringNameBundle] |
---|
291 | defaultButton:nil alternateButton:nil otherButton:nil informativeTextWithFormat:@"This copy will now quit."] runModal]; |
---|
292 | |
---|
293 | [NSApp terminate:nil]; |
---|
294 | } |
---|
295 | [NSBundle loadNibNamed:@"I2Launcher" owner:NSApp]; |
---|
296 | |
---|
297 | [NSApp run]; |
---|
298 | return 0; |
---|
299 | } |
---|
300 | |
---|
301 | |
---|
302 | |
---|