ServiceCom.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. //
  2. // ServiceCom.m
  3. // ZeroTier One
  4. //
  5. // Created by Grant Limberg on 8/4/16.
  6. // Copyright © 2016 ZeroTier, Inc. All rights reserved.
  7. //
  8. #import "ServiceCom.h"
  9. #import "AuthtokenCopy.h"
  10. #import "Network.h"
  11. #import "NodeStatus.h"
  12. @import AppKit;
  13. @interface ServiceCom (Private)
  14. - (NSString*)key;
  15. @end
  16. @implementation ServiceCom
  17. + (ServiceCom*)sharedInstance {
  18. static ServiceCom *sc = nil;
  19. static dispatch_once_t onceToken;
  20. dispatch_once(&onceToken, ^{
  21. sc = [[ServiceCom alloc] init];
  22. });
  23. return sc;
  24. }
  25. - (id)init
  26. {
  27. self = [super init];
  28. if(self) {
  29. baseURL = @"http://localhost:9993";
  30. session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration]];
  31. _isQuitting = NO;
  32. }
  33. return self;
  34. }
  35. - (NSString*)key:(NSError* __autoreleasing *)err
  36. {
  37. static NSString *k = nil;
  38. if (k == nil) {
  39. NSError *error = nil;
  40. NSURL *appSupportDir = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:false error:&error];
  41. if (error) {
  42. NSLog(@"Error: %@", error);
  43. return @"";
  44. }
  45. appSupportDir = [[appSupportDir URLByAppendingPathComponent:@"ZeroTier"] URLByAppendingPathComponent:@"One"];
  46. NSURL *authtokenURL = [appSupportDir URLByAppendingPathComponent:@"authtoken.secret"];
  47. if ([[NSFileManager defaultManager] fileExistsAtPath:[authtokenURL path]]) {
  48. k = [NSString stringWithContentsOfURL:authtokenURL
  49. encoding:NSUTF8StringEncoding
  50. error:&error];
  51. if (error) {
  52. NSLog(@"Error: %@", error);
  53. k = nil;
  54. *err = error;
  55. return @"";
  56. }
  57. }
  58. else {
  59. NSURL *sysAppSupportDir = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSSystemDomainMask appropriateForURL:nil create:false error:nil];
  60. sysAppSupportDir = [[sysAppSupportDir URLByAppendingPathComponent:@"ZeroTier"] URLByAppendingPathComponent:@"One"];
  61. NSURL *sysAuthtokenURL = [sysAppSupportDir URLByAppendingPathComponent:@"authtoken.secret"];
  62. if(![[NSFileManager defaultManager] fileExistsAtPath:[sysAuthtokenURL path]]) {
  63. }
  64. [[NSFileManager defaultManager] createDirectoryAtURL:appSupportDir
  65. withIntermediateDirectories:YES
  66. attributes:nil
  67. error:&error];
  68. if (error) {
  69. NSLog(@"Error: %@", error);
  70. *err = error;
  71. k = nil;
  72. return @"";
  73. }
  74. AuthorizationRef authRef;
  75. OSStatus status = AuthorizationCreate(nil, nil, kAuthorizationFlagDefaults, &authRef);
  76. if (status != errAuthorizationSuccess) {
  77. NSLog(@"Authorization Failed! %d", status);
  78. NSDictionary *userInfo = @{
  79. NSLocalizedDescriptionKey: NSLocalizedString(@"Couldn't create AuthorizationRef", nil),
  80. };
  81. *err = [NSError errorWithDomain:@"com.zerotier.one" code:-1 userInfo:userInfo];
  82. return @"";
  83. }
  84. AuthorizationItem authItem;
  85. authItem.name = kAuthorizationRightExecute;
  86. authItem.valueLength = 0;
  87. authItem.flags = 0;
  88. AuthorizationRights authRights;
  89. authRights.count = 1;
  90. authRights.items = &authItem;
  91. AuthorizationFlags authFlags = kAuthorizationFlagDefaults |
  92. kAuthorizationFlagInteractionAllowed |
  93. kAuthorizationFlagPreAuthorize |
  94. kAuthorizationFlagExtendRights;
  95. status = AuthorizationCopyRights(authRef, &authRights, nil, authFlags, nil);
  96. if (status != errAuthorizationSuccess) {
  97. NSLog(@"Authorization Failed! %d", status);
  98. NSDictionary *userInfo = @{
  99. NSLocalizedDescriptionKey: NSLocalizedString(@"Couldn't copy authorization rights", nil),
  100. };
  101. *err = [NSError errorWithDomain:@"com.zerotier.one" code:-1 userInfo:userInfo];
  102. return @"";
  103. }
  104. NSString *localKey = getAdminAuthToken(authRef);
  105. AuthorizationFree(authRef, kAuthorizationFlagDestroyRights);
  106. if (localKey != nil && [localKey lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 0) {
  107. k = localKey;
  108. [localKey writeToURL:authtokenURL
  109. atomically:YES
  110. encoding:NSUTF8StringEncoding
  111. error:&error];
  112. if (error) {
  113. NSLog(@"Error writing token to disk: %@", error);
  114. *err = error;
  115. }
  116. }
  117. }
  118. }
  119. if (k == nil) {
  120. NSDictionary *userInfo = @{
  121. NSLocalizedDescriptionKey: NSLocalizedString(@"Unknown error finding authorization key", nil),
  122. };
  123. *err = [NSError errorWithDomain:@"com.zerotier.one" code:-1 userInfo:userInfo];
  124. return @"";
  125. }
  126. return k;
  127. }
  128. - (void)getNetworklist:(void (^)(NSArray<Network *> *))completionHandler error:(NSError *__autoreleasing*)error
  129. {
  130. NSString* key = [self key:error];
  131. if(*error) {
  132. return;
  133. }
  134. NSString *urlString = [[baseURL stringByAppendingString:@"/network?auth="] stringByAppendingString:key];
  135. NSURL *url = [NSURL URLWithString:urlString];
  136. NSURLSessionDataTask *task =
  137. [session dataTaskWithURL:url
  138. completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable err) {
  139. if (err) {
  140. [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  141. NSAlert *alert = [NSAlert alertWithError:err];
  142. alert.alertStyle = NSCriticalAlertStyle;
  143. [alert addButtonWithTitle:@"Quit"];
  144. [alert addButtonWithTitle:@"Retry"];
  145. NSModalResponse res;
  146. if (!_isQuitting) {
  147. res = [alert runModal];
  148. }
  149. else {
  150. return;
  151. }
  152. if(res == NSAlertFirstButtonReturn) {
  153. [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0];
  154. _isQuitting = YES;
  155. }
  156. }];
  157. return;
  158. }
  159. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  160. NSInteger status = [httpResponse statusCode];
  161. NSError *err2;
  162. if (status == 200) {
  163. NSArray *json = [NSJSONSerialization JSONObjectWithData:data
  164. options:0
  165. error:&err2];
  166. if (err) {
  167. NSLog(@"Error fetching network list: %@", err2);
  168. [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  169. NSAlert *alert = [NSAlert alertWithError:err2];
  170. alert.alertStyle = NSCriticalAlertStyle;
  171. [alert addButtonWithTitle:@"Quit"];
  172. [alert addButtonWithTitle:@"Retry"];
  173. NSModalResponse res;
  174. if (!_isQuitting) {
  175. res = [alert runModal];
  176. }
  177. else {
  178. return;
  179. }
  180. if(res == NSAlertFirstButtonReturn) {
  181. _isQuitting = YES;
  182. [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0];
  183. }
  184. }];
  185. return;
  186. }
  187. NSMutableArray<Network*> *networks = [[NSMutableArray<Network*> alloc] init];
  188. for(NSDictionary *dict in json) {
  189. [networks addObject:[[Network alloc] initWithJsonData:dict]];
  190. }
  191. completionHandler(networks);
  192. }
  193. }];
  194. [task resume];
  195. }
  196. - (void)getNodeStatus:(void (^)(NodeStatus*))completionHandler error:(NSError*__autoreleasing*)error
  197. {
  198. NSString *key = [self key:error];
  199. if(*error) {
  200. return;
  201. }
  202. NSString *urlString = [[baseURL stringByAppendingString:@"/status?auth="] stringByAppendingString:key];
  203. NSURL *url = [NSURL URLWithString:urlString];
  204. NSURLSessionDataTask *task =
  205. [session dataTaskWithURL:url
  206. completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable err) {
  207. if(err) {
  208. [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  209. NSAlert *alert = [NSAlert alertWithError:err];
  210. alert.alertStyle = NSCriticalAlertStyle;
  211. [alert addButtonWithTitle:@"Quit"];
  212. [alert addButtonWithTitle:@"Retry"];
  213. NSModalResponse res;
  214. if (!_isQuitting) {
  215. res = [alert runModal];
  216. }
  217. else {
  218. return;
  219. }
  220. if(res == NSAlertFirstButtonReturn) {
  221. [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0];
  222. _isQuitting = YES;
  223. }
  224. }];
  225. return;
  226. }
  227. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  228. NSInteger status = [httpResponse statusCode];
  229. NSError *err2;
  230. if(status == 200) {
  231. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
  232. options:0
  233. error:&err2];
  234. if(err2) {
  235. NSLog(@"Error fetching node status: %@", err2);
  236. [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  237. NSAlert *alert = [NSAlert alertWithError:err2];
  238. alert.alertStyle = NSCriticalAlertStyle;
  239. [alert addButtonWithTitle:@"Quit"];
  240. [alert addButtonWithTitle:@"Retry"];
  241. NSModalResponse res;
  242. if (!_isQuitting) {
  243. res = [alert runModal];
  244. }
  245. else {
  246. return;
  247. }
  248. if(res == NSAlertFirstButtonReturn) {
  249. [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0];
  250. _isQuitting = YES;
  251. }
  252. }];
  253. return;
  254. }
  255. NodeStatus *status = [[NodeStatus alloc] initWithJsonData:json];
  256. completionHandler(status);
  257. }
  258. }];
  259. [task resume];
  260. }
  261. - (void)joinNetwork:(NSString*)networkId allowManaged:(BOOL)allowManaged allowGlobal:(BOOL)allowGlobal allowDefault:(BOOL)allowDefault error:(NSError *__autoreleasing*)error
  262. {
  263. NSString *key = [self key:error];
  264. if(*error) {
  265. return;
  266. }
  267. NSString *urlString = [[[[baseURL stringByAppendingString:@"/network/"]
  268. stringByAppendingString:networkId]
  269. stringByAppendingString:@"?auth="]
  270. stringByAppendingString:key];
  271. NSURL *url = [NSURL URLWithString:urlString];
  272. NSMutableDictionary *jsonDict = [NSMutableDictionary dictionary];
  273. [jsonDict setObject:[NSNumber numberWithBool:allowManaged] forKey:@"allowManaged"];
  274. [jsonDict setObject:[NSNumber numberWithBool:allowGlobal] forKey:@"allowGlobal"];
  275. [jsonDict setObject:[NSNumber numberWithBool:allowDefault] forKey:@"allowDefault"];
  276. NSError *err = nil;
  277. NSData *json = [NSJSONSerialization dataWithJSONObject:jsonDict
  278. options:0
  279. error:&err];
  280. if(err) {
  281. NSLog(@"Error creating json data: %@", err);
  282. *error = err;
  283. return;
  284. }
  285. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  286. request.HTTPMethod = @"POST";
  287. request.HTTPBody = json;
  288. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  289. NSURLSessionDataTask *task =
  290. [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable err) {
  291. if(err) {
  292. NSLog(@"Error posting join request: %@", err);
  293. [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  294. NSAlert *alert = [NSAlert alertWithError:err];
  295. alert.alertStyle = NSCriticalAlertStyle;
  296. [alert addButtonWithTitle:@"Quit"];
  297. [alert addButtonWithTitle:@"Retry"];
  298. NSModalResponse res;
  299. if (!_isQuitting) {
  300. res = [alert runModal];
  301. }
  302. else {
  303. return;
  304. }
  305. if(res == NSAlertFirstButtonReturn) {
  306. [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0];
  307. _isQuitting = YES;
  308. }
  309. }];
  310. }
  311. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  312. NSInteger status = [httpResponse statusCode];
  313. if(status == 200) {
  314. NSLog(@"join ok");
  315. }
  316. else {
  317. NSLog(@"join error: %ld", (long)status);
  318. }
  319. }];
  320. [task resume];
  321. }
  322. - (void)leaveNetwork:(NSString*)networkId error:(NSError*__autoreleasing*)error
  323. {
  324. NSString *key = [self key:error];
  325. if(*error) {
  326. return;
  327. }
  328. NSString *urlString = [[[[baseURL stringByAppendingString:@"/network/"]
  329. stringByAppendingString:networkId]
  330. stringByAppendingString:@"?auth="]
  331. stringByAppendingString:key];
  332. NSURL *url = [NSURL URLWithString:urlString];
  333. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  334. request.HTTPMethod = @"DELETE";
  335. NSURLSessionDataTask *task =
  336. [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable err) {
  337. if(err) {
  338. NSLog(@"Error posting delete request: %@", err);
  339. [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  340. NSAlert *alert = [NSAlert alertWithError:err];
  341. alert.alertStyle = NSCriticalAlertStyle;
  342. [alert addButtonWithTitle:@"Quit"];
  343. [alert addButtonWithTitle:@"Retry"];
  344. NSModalResponse res;
  345. if (!_isQuitting) {
  346. res = [alert runModal];
  347. }
  348. else {
  349. return;
  350. }
  351. if(res == NSAlertFirstButtonReturn) {
  352. [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0];
  353. _isQuitting = YES;
  354. }
  355. }];
  356. return;
  357. }
  358. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  359. NSInteger status = httpResponse.statusCode;
  360. if(status == 200) {
  361. NSLog(@"leave ok");
  362. }
  363. else {
  364. NSLog(@"leave error: %ld", status);
  365. }
  366. }];
  367. [task resume];
  368. }
  369. @end