source: launchers/macosx/main.mm @ a9bf9e06

Last change on this file since a9bf9e06 was a9bf9e06, checked in by meeh <meeh@…>, 22 months ago

OSX Launcher: make deployer an property so it's not deleted in mid-extract by GC.

  • Property mode set to 100644
File size: 8.7 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#import "Deployer.h"
29#include "logger_c.h"
30
31#ifdef __cplusplus
32#include <string>
33
34#include "include/subprocess.hpp"
35#include "include/strutil.hpp"
36
37#include "Logger.h"
38#include "LoggerWorker.hpp"
39
40using namespace subprocess;
41#endif
42
43#define debug(format, ...) CFShow([NSString stringWithFormat:format, ## __VA_ARGS__]);
44
45
46
47@interface AppDelegate () <NSUserNotificationCenterDelegate, NSApplicationDelegate>
48@end
49
50
51@implementation ExtractMetaInfo : NSObject
52@end
53
54
55@implementation AppDelegate
56
57- (void) awakeFromNib {
58}
59
60
61- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center
62     shouldPresentNotification:(NSUserNotification *)notification {
63  return YES;
64}
65
66- (void)extractI2PBaseDir:(void(^)(BOOL success, NSError *error))completion
67{
68  self.deployer = [[I2PDeployer alloc] initWithMetaInfo:self.metaInfo];
69  [self.deployer extractI2PBaseDir:completion];
70}
71
72- (void)setApplicationDefaultPreferences {
73  [self.userPreferences registerDefaults:@{
74    @"enableLogging": @YES,
75    @"enableVerboseLogging": @YES,
76    @"autoStartRouter": @YES,
77    @"startRouterAtLogin": @NO,
78    @"startRouterAtStartup": @NO,
79    @"letRouterLiveEvenLauncherDied": @NO,
80    @"consolePortCheckNum": @7657,
81    @"i2pBaseDirectory": (NSString *)CFStringCreateWithCString(NULL, const_cast<const char *>(getDefaultBaseDir().c_str()), kCFStringEncodingUTF8)
82  }];
83
84  auto dict = [self.userPreferences dictionaryRepresentation];
85  [self.userPreferences setPersistentDomain:dict forName:NSAPPDOMAIN];
86
87  CFPreferencesSetMultiple((CFDictionaryRef)dict, NULL, CFAPPDOMAIN, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
88  CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
89
90  if (self.enableVerboseLogging) NSLog(@"Default preferences stored!");
91}
92
93
94- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
95  // Init application here
96 
97  self.swiftRuntime = [[SwiftMainDelegate alloc] init];
98 
99  // This setup allows the application to send notifications
100  [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
101 
102 
103  // Start with user preferences
104  self.userPreferences = [NSUserDefaults standardUserDefaults];
105  [self setApplicationDefaultPreferences];
106  self.enableLogging = [self.userPreferences boolForKey:@"enableLogging"];
107  self.enableVerboseLogging = [self.userPreferences boolForKey:@"enableVerboseLogging"];
108  // In case we are unbundled, make us a proper UI application
109  [NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];
110  [NSApp activateIgnoringOtherApps:YES];
111
112
113#ifdef __cplusplus
114
115  RouterProcessStatus* routerStatus = [[RouterProcessStatus alloc] init];
116  std::string i2pBaseDir(getDefaultBaseDir());
117  MLOG(INFO) << "i2pBaseDir = " << i2pBaseDir.c_str();
118  bool shouldAutoStartRouter = false;
119 
120  // Initialize the Swift environment (the UI components)
121  [self.swiftRuntime applicationDidFinishLaunching];
122 
123  NSInteger portNum = [self.userPreferences integerForKey:@"consolePortCheckNum"];
124  if (port_check((int)portNum) != 0)
125  {
126    NSLog(@"Seems i2p is already running - I will not start the router (port %d is in use..)", (int)portNum);
127    sendUserNotification(@"Found already running router", @"TCP port 7657 seem to be used by another i2p instance.");
128   
129    [routerStatus setRouterStatus: true];
130    [routerStatus setRouterRanByUs: false];
131    shouldAutoStartRouter = false;
132  } else {
133    shouldAutoStartRouter = true;
134  }
135  if (![self.userPreferences boolForKey:@"startRouterAtLogin"] && ![self.userPreferences boolForKey:@"startRouterAtStartup"])
136  {
137    // In this case we don't want to find a running service
138    std::string launchdFile(RealHomeDirectory());
139    launchdFile += "/Library/LaunchAgents/net.i2p.macosx.I2PRouter.plist";
140   
141  }
142
143  NSBundle *launcherBundle = [NSBundle mainBundle];
144 
145 
146  // Helper object to hold statefull path information
147  self.metaInfo = [[ExtractMetaInfo alloc] init];
148  self.metaInfo.i2pBase = [NSString stringWithUTF8String:i2pBaseDir.c_str()];
149  self.metaInfo.javaBinary = [routerStatus getJavaHome];
150  self.metaInfo.jarFile = [launcherBundle pathForResource:@"launcher" ofType:@"jar"];
151  self.metaInfo.zipFile = [launcherBundle pathForResource:@"base" ofType:@"zip"];
152
153  std::string basearg("-Di2p.dir.base=");
154  basearg += i2pBaseDir;
155
156  std::string jarfile("-cp ");
157  jarfile += [self.metaInfo.zipFile UTF8String];
158 
159  // This will trigger the router start after an upgrade.
160  [routerStatus listenForEventWithEventName:@"router_must_upgrade" callbackActionFn:^(NSString* information) {
161    NSLog(@"Got signal, router must be deployed from base.zip");
162    [self extractI2PBaseDir:^(BOOL success, NSError *error) {
163      if (success) {
164        sendUserNotification(@"I2P is done extracting", @"I2P is now installed and ready to run!");
165        NSLog(@"Done extracting I2P");
166        [routerStatus triggerEventWithEn:@"extract_completed" details:@"upgrade complete"];
167      } else {
168        NSLog(@"Error while extracting I2P");
169        [routerStatus triggerEventWithEn:@"extract_errored" details:[NSString stringWithFormat:@"%@", error]];
170      }
171    }];
172  }];
173 
174  NSString *nsI2PBaseStr = [NSString stringWithUTF8String:i2pBaseDir.c_str()];
175
176  [routerStatus listenForEventWithEventName:@"extract_completed" callbackActionFn:^(NSString* information) {
177    NSLog(@"Time to detect I2P version in install directory");
178    [self.swiftRuntime findInstalledI2PVersion];
179  }];
180 
181  //struct stat sb;
182  //if ( !(stat(i2pBaseDir.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) )
183  BOOL shouldBeTrueOnReturnDir = YES;
184  if (! [NSFileManager.defaultManager fileExistsAtPath: nsI2PBaseStr isDirectory: &shouldBeTrueOnReturnDir])
185  {
186    // I2P is not extracted.
187    if (shouldBeTrueOnReturnDir) {
188      if (self.enableVerboseLogging) NSLog(@"I2P Directory don't exists!");
189      [routerStatus triggerEventWithEn:@"router_must_upgrade" details:@"deploy needed"];
190    } else {
191      // TODO: handle if i2p path exists but it's not a dir.
192    }
193  } else {
194    // I2P was already found extracted
195    NSString *nsI2pJar = [NSString stringWithFormat:@"%@/lib/i2p.jar", nsI2PBaseStr];
196   
197    // But does I2PBASE/lib/i2p.jar exists?
198    if ([NSFileManager.defaultManager fileExistsAtPath:nsI2pJar]) {
199      NSLog(@"Time to detect I2P version in install directory");
200      [self.swiftRuntime findInstalledI2PVersion];
201    } else {
202      // The directory exists, but not i2p.jar - most likely we're in mid-extraction state.
203      [routerStatus triggerEventWithEn:@"router_must_upgrade" details:@"deploy needed"];
204    }
205  }
206 
207#endif
208}
209
210/**
211 *
212 * Exit sequence
213 *
214 **/
215- (void)applicationWillTerminate:(NSNotification *)aNotification {
216  // Tear down here
217  [self.swiftRuntime applicationWillTerminate];
218  NSString *string = @"applicationWillTerminate executed";
219  NSLog(@"%@", string);
220  [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:nil];
221}
222
223
224/* wrapper for main */
225- (AppDelegate *)initWithArgc:(int)argc argv:(const char **)argv {
226  return self;
227}
228@end
229
230#ifdef __cplusplus
231namespace {
232  const std::string logDirectory = getDefaultLogDir();
233}
234#endif
235
236int main(int argc, const char **argv)
237{
238  NSApplication *app = [NSApplication sharedApplication];
239
240#ifdef __cplusplus
241  mkdir(logDirectory.c_str(), S_IRUSR | S_IWUSR | S_IXUSR);
242 
243  SharedLogWorker logger("I2PLauncher", logDirectory);
244  MeehLog::initializeLogging(&logger);
245 
246  MLOG(INFO) << "Application is starting up";
247#endif
248 
249  AppDelegate *appDelegate = [[AppDelegate alloc] initWithArgc:argc argv:argv];
250  app.delegate = appDelegate;
251  auto mainBundle = [NSBundle mainBundle];
252  NSString* stringNameBundle = [mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey];
253  if ([[NSRunningApplication runningApplicationsWithBundleIdentifier:[mainBundle bundleIdentifier]] count] > 1) {
254    [[NSAlert alertWithMessageText:[NSString stringWithFormat:@"Another copy of %@ is already running.",stringNameBundle]
255                     defaultButton:nil alternateButton:nil otherButton:nil informativeTextWithFormat:@"This copy will now quit."] runModal];
256   
257    [NSApp terminate:nil];
258  }
259#pragma GCC diagnostic push
260#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
261  [NSBundle loadNibNamed:@"I2Launcher" owner:NSApp];
262#pragma GCC diagnostic pop
263 
264  [NSApp run];
265  return 0;
266}
267
268
269
Note: See TracBrowser for help on using the repository browser.