source: launchers/macosx/main.mm @ 70fa2dae

Last change on this file since 70fa2dae was 70fa2dae, checked in by meeh <meeh@…>, 2 years ago

Mac OS X Launcher: Let version detection etc happen even a router is already started.

  • Property mode set to 100644
File size: 9.4 KB
Line 
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
35using 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  auto sBridge = [[SBridge alloc] init];
208 
209  // Helper object to hold statefull path information
210  self.metaInfo = [[ExtractMetaInfo alloc] init];
211  self.metaInfo.i2pBase = [NSString stringWithUTF8String:i2pBaseDir.c_str()];
212  self.metaInfo.javaBinary = [routerStatus getJavaHome];
213  self.metaInfo.jarFile = [launcherBundle pathForResource:@"launcher" ofType:@"jar"];
214  self.metaInfo.zipFile = [launcherBundle pathForResource:@"base" ofType:@"zip"];
215
216  std::string basearg("-Di2p.dir.base=");
217  basearg += i2pBaseDir;
218
219  std::string jarfile("-cp ");
220  jarfile += [self.metaInfo.zipFile UTF8String];
221 
222  // Initialize the Swift environment (the UI components)
223  [self.swiftRuntime applicationDidFinishLaunching];
224
225  struct stat sb;
226  if ( !(stat(i2pBaseDir.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) )
227  {
228    // I2P is not extracted.
229    if (self.enableVerboseLogging) NSLog(@"I2P Directory don't exists!");
230
231    // Might be hard to read if you're not used to Objective-C
232    // But this is a "function call" that contains a "callback function"
233    [self extractI2PBaseDir:^(BOOL success, NSError *error) {
234      sendUserNotification(@"I2P is done extracting", @"I2P is now installed and ready to run!");
235      NSLog(@"Done extracting I2P");
236     
237      NSLog(@"Time to detect I2P version in install directory");
238      [self.swiftRuntime findInstalledI2PVersion];
239      if (shouldAutoStartRouter) {
240        [sBridge startupI2PRouter:self.metaInfo.i2pBase javaBinPath:self.metaInfo.javaBinary];
241        [routerStatus setRouterRanByUs: true];
242      }
243    }];
244
245  } else {
246    // I2P was already found extracted
247    NSLog(@"Time to detect I2P version in install directory");
248    [self.swiftRuntime findInstalledI2PVersion];
249   
250    if (shouldAutoStartRouter) {
251      [sBridge startupI2PRouter:self.metaInfo.i2pBase javaBinPath:self.metaInfo.javaBinary];
252      [routerStatus setRouterRanByUs: true];
253    }
254  }
255 
256#endif
257}
258
259
260
261/**
262 *
263 * Exit sequence
264 *
265 **/
266- (void)applicationWillTerminate:(NSNotification *)aNotification {
267  // Tear down here
268  NSString *string = @"applicationWillTerminate executed";
269  NSLog(@"%@", string);
270  [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:nil];
271}
272
273
274/* wrapper for main */
275- (AppDelegate *)initWithArgc:(int)argc argv:(const char **)argv {
276  return self;
277}
278@end
279
280
281
282int main(int argc, const char **argv)
283{
284  NSApplication *app = [NSApplication sharedApplication];
285
286  AppDelegate *appDelegate = [[AppDelegate alloc] initWithArgc:argc argv:argv];
287  app.delegate = appDelegate;
288  auto mainBundle = [NSBundle mainBundle];
289  NSString* stringNameBundle = [mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey];
290  if ([[NSRunningApplication runningApplicationsWithBundleIdentifier:[mainBundle bundleIdentifier]] count] > 1) {
291    [[NSAlert alertWithMessageText:[NSString stringWithFormat:@"Another copy of %@ is already running.",stringNameBundle]
292                     defaultButton:nil alternateButton:nil otherButton:nil informativeTextWithFormat:@"This copy will now quit."] runModal];
293   
294    [NSApp terminate:nil];
295  }
296  [NSBundle loadNibNamed:@"I2Launcher" owner:NSApp];
297
298  [NSApp run];
299  return 0;
300}
301
302
303
Note: See TracBrowser for help on using the repository browser.