├── screenshot
├── main.png
├── add-window.png
└── restful-api.png
├── GoldenPassport
├── Assets.xcassets
│ ├── Contents.json
│ ├── copyIcon.imageset
│ │ ├── copyIcon.png
│ │ └── Contents.json
│ ├── AppIcon.appiconset
│ │ ├── account-key-2.png
│ │ ├── account-key.png
│ │ └── Contents.json
│ ├── removeIcon.imageset
│ │ ├── removeIcon.png
│ │ └── Contents.json
│ └── statusIcon.imageset
│ │ ├── account-key-3.png
│ │ └── Contents.json
├── zh-Hans.lproj
│ ├── MainMenu.strings
│ └── I18n.strings
├── en.lproj
│ ├── I18n.strings
│ └── MainMenu.strings
├── GoldenPassport-Bridging-Header.h
├── google-toolbox-for-mac
│ ├── GTMNSNumber+64Bit.h
│ ├── GTMNSNumber+64Bit.m
│ ├── GTMDebugThreadValidation.m
│ ├── GTMMethodCheck.m
│ ├── GTMObjC2Runtime.m
│ ├── GTMObjC2Runtime.h
│ ├── GTMLightweightProxy.h
│ ├── GTMNSScanner+JSON.h
│ ├── GTMNSString+Replace.h
│ ├── GTMNSDictionary+URLArguments.h
│ ├── GTMNSArray+Merge.h
│ ├── GTMNSThread+Blocks.h
│ ├── GTMDebugThreadValidation.h
│ ├── GTMNSString+URLArguments.h
│ ├── GTMNSString+XML.h
│ ├── GTMNSFileManager+Path.h
│ ├── GTMNSString+URLArguments.m
│ ├── GTMNSString+Replace.m
│ ├── GTMNSString+FindFolder.h
│ ├── GTMNSFileManager+Carbon.h
│ ├── GTMTypeCasting.h
│ ├── GTMObjectSingleton.h
│ ├── GTMNSString+HTML.h
│ ├── GTMNSFileManager+Path.m
│ ├── GTMMethodCheck.h
│ ├── GTMNSObject+KeyValueObserving.h
│ ├── GTMSystemVersion.h
│ ├── GTMSignalHandler.h
│ ├── GTMNSDictionary+URLArguments.m
│ ├── GTMURLBuilder.h
│ ├── GTMNSScanner+JSON.m
│ ├── GTMServiceManagement.h
│ ├── GTMFileSystemKQueue.h
│ ├── GTMStackTrace.h
│ ├── GTMLocalizedString.h
│ ├── GTMLightweightProxy.m
│ ├── GTMLoggerRingBufferWriter.h
│ ├── GTMNSFileHandle+UniqueName.h
│ ├── GTMSynchronizationAsserts.m
│ ├── GTMNSString+FindFolder.m
│ ├── GTMNSFileManager+Carbon.m
│ ├── GTMLogger+ASL.h
│ ├── GTMURLBuilder.m
│ ├── GTMGeometryUtils.m
│ ├── GTMDebugSelectorValidation.h
│ ├── GTMNSArray+Merge.m
│ ├── GTMStringEncoding.h
│ ├── GTMNSFileHandle+UniqueName.m
│ ├── GTMPath.h
│ ├── GTMSynchronizationAsserts.h
│ ├── GTMLogger+ASL.m
│ └── GTMNSString+XML.m
├── Constant.swift
├── AppDelegate.swift
├── OTPAuth
│ ├── HOTPGenerator.h
│ ├── HOTPGenerator.m
│ ├── TOTPGenerator.m
│ ├── TOTPGenerator.h
│ ├── OTPGenerator.h
│ ├── OTPAuthURL.h
│ └── OTPGenerator.m
├── HttpServer.swift
├── Info.plist
├── OTPAuthURLParser.swift
├── HTTPPortConfigWindow.swift
├── KeyboardMonitor.swift
├── SimulateKeyBoardEvent.swift
├── KeyCode.swift
├── AddVerifyKeyWindow.swift
├── DataManager.swift
├── HTTPPortConfigWindow.xib
└── Base.lproj
│ └── MainMenu.xib
├── GoldenPassport.xcodeproj
└── project.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcshareddata
│ └── IDEWorkspaceChecks.plist
├── Podfile
├── .gitignore
└── README.md
/screenshot/main.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanzhai/GoldenPassport/HEAD/screenshot/main.png
--------------------------------------------------------------------------------
/screenshot/add-window.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanzhai/GoldenPassport/HEAD/screenshot/add-window.png
--------------------------------------------------------------------------------
/screenshot/restful-api.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanzhai/GoldenPassport/HEAD/screenshot/restful-api.png
--------------------------------------------------------------------------------
/GoldenPassport/Assets.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "version" : 1,
4 | "author" : "xcode"
5 | }
6 | }
--------------------------------------------------------------------------------
/GoldenPassport/Assets.xcassets/copyIcon.imageset/copyIcon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanzhai/GoldenPassport/HEAD/GoldenPassport/Assets.xcassets/copyIcon.imageset/copyIcon.png
--------------------------------------------------------------------------------
/GoldenPassport/Assets.xcassets/AppIcon.appiconset/account-key-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanzhai/GoldenPassport/HEAD/GoldenPassport/Assets.xcassets/AppIcon.appiconset/account-key-2.png
--------------------------------------------------------------------------------
/GoldenPassport/Assets.xcassets/AppIcon.appiconset/account-key.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanzhai/GoldenPassport/HEAD/GoldenPassport/Assets.xcassets/AppIcon.appiconset/account-key.png
--------------------------------------------------------------------------------
/GoldenPassport/Assets.xcassets/removeIcon.imageset/removeIcon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanzhai/GoldenPassport/HEAD/GoldenPassport/Assets.xcassets/removeIcon.imageset/removeIcon.png
--------------------------------------------------------------------------------
/GoldenPassport/Assets.xcassets/statusIcon.imageset/account-key-3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stanzhai/GoldenPassport/HEAD/GoldenPassport/Assets.xcassets/statusIcon.imageset/account-key-3.png
--------------------------------------------------------------------------------
/GoldenPassport/zh-Hans.lproj/MainMenu.strings:
--------------------------------------------------------------------------------
1 | "add_key_menu_item.title" = "Quit";
2 | "remove_key_menu_item.title" = "Quit";
3 |
4 | "about_menu_item.title" = "Quit";
5 | "quit_menu_item.title" = "Quit";
6 |
--------------------------------------------------------------------------------
/GoldenPassport/en.lproj/I18n.strings:
--------------------------------------------------------------------------------
1 | /*
2 | I18n.strings
3 | GoldenPassport
4 |
5 | Created by StanZhai on 2017/2/25.
6 | Copyright © 2017年 StanZhai. All rights reserved.
7 | */
8 | "quit_menu" = "Quit";
9 |
--------------------------------------------------------------------------------
/GoldenPassport/zh-Hans.lproj/I18n.strings:
--------------------------------------------------------------------------------
1 | /*
2 | I18n.strings
3 | GoldenPassport
4 |
5 | Created by StanZhai on 2017/2/25.
6 | Copyright © 2017年 StanZhai. All rights reserved.
7 | */
8 | "quit_menu" = "退出";
9 |
--------------------------------------------------------------------------------
/GoldenPassport/GoldenPassport-Bridging-Header.h:
--------------------------------------------------------------------------------
1 | //
2 | // Use this file to import your target's public headers that you would like to expose to Swift.
3 | //
4 |
5 | #import "OTPAuth/TOTPGenerator.h"
6 | #import "OTPAuth/OTPAuthURL.h"
7 |
--------------------------------------------------------------------------------
/GoldenPassport.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/GoldenPassport/en.lproj/MainMenu.strings:
--------------------------------------------------------------------------------
1 |
2 | /* Class = "NSMenuItem"; title = "Item 3"; ObjectID = "GAm-17-nOa"; */
3 |
4 | "add_key_menu_item.title" = "Quit";
5 | "remove_key_menu_item.title" = "Quit";
6 |
7 | "about_menu_item.title" = "Quit";
8 | "quit_menu_item.title" = "Quit";
9 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSNumber+64Bit.h:
--------------------------------------------------------------------------------
1 | //
2 | // This file previously included utility methods for creating
3 | // 64-bit NSNumbers.
4 | //
5 | // Applications should be updated to use NSNumber literals and
6 | // boxed expressions, as described at
7 | // http://clang.llvm.org/docs/ObjectiveCLiterals.html
8 | //
9 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSNumber+64Bit.m:
--------------------------------------------------------------------------------
1 | //
2 | // This file previously included utility methods for creating
3 | // 64-bit NSNumbers.
4 | //
5 | // Applications should be updated to use NSNumber literals and
6 | // boxed expressions, as described at
7 | // http://clang.llvm.org/docs/ObjectiveCLiterals.html
8 | //
9 |
--------------------------------------------------------------------------------
/GoldenPassport.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Podfile:
--------------------------------------------------------------------------------
1 | # Uncomment the next line to define a global platform for your project
2 | platform :osx, "10.11"
3 |
4 | target "GoldenPassport" do
5 | # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
6 | use_frameworks!
7 |
8 | # Pods for GoldenPassport
9 | pod "Swifter", "~> 1.5.0"
10 | end
11 |
--------------------------------------------------------------------------------
/GoldenPassport/Assets.xcassets/statusIcon.imageset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "mac",
5 | "filename" : "account-key-3.png",
6 | "scale" : "1x"
7 | },
8 | {
9 | "idiom" : "mac",
10 | "scale" : "2x"
11 | }
12 | ],
13 | "info" : {
14 | "version" : 1,
15 | "author" : "xcode"
16 | }
17 | }
--------------------------------------------------------------------------------
/GoldenPassport/Assets.xcassets/copyIcon.imageset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "universal",
5 | "filename" : "copyIcon.png",
6 | "scale" : "1x"
7 | },
8 | {
9 | "idiom" : "universal",
10 | "scale" : "2x"
11 | },
12 | {
13 | "idiom" : "universal",
14 | "scale" : "3x"
15 | }
16 | ],
17 | "info" : {
18 | "version" : 1,
19 | "author" : "xcode"
20 | }
21 | }
--------------------------------------------------------------------------------
/GoldenPassport/Assets.xcassets/removeIcon.imageset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "universal",
5 | "filename" : "removeIcon.png",
6 | "scale" : "1x"
7 | },
8 | {
9 | "idiom" : "universal",
10 | "scale" : "2x"
11 | },
12 | {
13 | "idiom" : "universal",
14 | "scale" : "3x"
15 | }
16 | ],
17 | "info" : {
18 | "version" : 1,
19 | "author" : "xcode"
20 | }
21 | }
--------------------------------------------------------------------------------
/GoldenPassport/Constant.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Constant.swift
3 | // GoldenPassport
4 | //
5 | // Created by StanZhai on 2017/2/26.
6 | // Copyright © 2017年 StanZhai. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | let EXPIRE_TIME_STR = "过期时间: "
12 |
13 | let COPY_AUTH_CODE_STR = "点击复制验证码"
14 | let DELETE_VERIFY_KEY_STR = "点击删除认证记录"
15 |
16 | let DONE_REMOVE_STR = "完成删除"
17 | let REMOVE_STR = "删除"
18 |
19 | let DEFAULT_HTTP_PORT = 17304
20 |
--------------------------------------------------------------------------------
/GoldenPassport/AppDelegate.swift:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.swift
3 | // GoldenPassport
4 | //
5 | // Created by StanZhai on 2017/2/25.
6 | // Copyright © 2017年 StanZhai. All rights reserved.
7 | //
8 |
9 | import Cocoa
10 | import Carbon
11 | import Swifter
12 |
13 | @NSApplicationMain
14 | class AppDelegate: NSObject, NSApplicationDelegate {
15 | let keyboardMonitor = KeyboardMonitor()
16 |
17 | func applicationDidFinishLaunching(_ aNotification: Notification) {
18 | keyboardMonitor.start()
19 | }
20 |
21 | func applicationWillTerminate(_ aNotification: Notification) {
22 | keyboardMonitor.stop()
23 | }
24 | }
25 |
26 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMDebugThreadValidation.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMDebugThreadValidation.m
3 | //
4 | // Copyright 2016 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | // No implementation source currently needed.
20 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMMethodCheck.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMMethodCheck.m
3 | //
4 | // Copyright 2006-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | // TODO(dmaclach): This file is no longer needed. Delete once we have cleaned
20 | // up GTM projects.
21 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMObjC2Runtime.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMObjC2Runtime.m
3 | //
4 | // Copyright 2007-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | // This source file is no longer necessary.
20 |
21 | #pragma GCC warning "GTMObjc2Runtime.m is deprecated and should no longer be used."
22 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMObjC2Runtime.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMObjC2Runtime.h
3 | //
4 | // Copyright 2007-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | // These headers only being pulled in to avoid breaking changes.
20 |
21 | #pragma GCC warning "GTMObjcRuntime.h is deprecated and should no longer be used."
22 |
23 | #import
24 | #import
25 | #import "GTMDefines.h"
26 |
27 | #import
28 | #import
29 |
30 | #import
31 |
32 |
--------------------------------------------------------------------------------
/GoldenPassport/OTPAuth/HOTPGenerator.h:
--------------------------------------------------------------------------------
1 | //
2 | // HOTPGenerator.h
3 | //
4 | // Copyright 2011 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "OTPGenerator.h"
20 |
21 | @interface HOTPGenerator : OTPGenerator
22 |
23 | // The counter, incremented on each generated OTP.
24 | @property(assign, nonatomic) uint64_t counter;
25 |
26 | + (uint64_t)defaultInitialCounter;
27 |
28 | - (id)initWithSecret:(NSData *)secret
29 | algorithm:(NSString *)algorithm
30 | digits:(NSUInteger)digits
31 | counter:(uint64_t)counter;
32 | @end
33 |
--------------------------------------------------------------------------------
/GoldenPassport/HttpServer.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HttpServer.swift
3 | // GoldenPassport
4 | //
5 | // Created by StanZhai on 2017/3/4.
6 | // Copyright © 2017年 StanZhai. All rights reserved.
7 | //
8 |
9 | import Foundation
10 | import Swifter
11 |
12 | public func httpServer() -> HttpServer {
13 | let server = HttpServer()
14 | server.listenAddressIPv4 = "127.0.0.1"
15 |
16 | server["/"] = scopes {
17 | html {
18 | body {
19 | h3 { inner = "Verification code list:" }
20 |
21 | ul(DataManager.shared.allAuthCode()) { code in
22 | li {
23 | a { href = "/code/\(code.key)"; inner = "\(code.key) -> \(code.value)" }
24 | }
25 | }
26 | }
27 | }
28 | }
29 |
30 | server["/code/:key"] = { r in
31 | let key = r.params[":key"]
32 | let allCodes = DataManager.shared.allAuthCode()
33 | for authInfo in allCodes {
34 | if authInfo.key == key! {
35 | return HttpResponse.ok(.text(authInfo.value))
36 | }
37 | }
38 | return HttpResponse.ok(.text("key does not exists!"))
39 | }
40 |
41 | return server
42 | }
43 |
--------------------------------------------------------------------------------
/GoldenPassport/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "mac",
5 | "size" : "16x16",
6 | "scale" : "1x"
7 | },
8 | {
9 | "idiom" : "mac",
10 | "size" : "16x16",
11 | "scale" : "2x"
12 | },
13 | {
14 | "idiom" : "mac",
15 | "size" : "32x32",
16 | "scale" : "1x"
17 | },
18 | {
19 | "size" : "32x32",
20 | "idiom" : "mac",
21 | "filename" : "account-key-2.png",
22 | "scale" : "2x"
23 | },
24 | {
25 | "size" : "128x128",
26 | "idiom" : "mac",
27 | "filename" : "account-key.png",
28 | "scale" : "1x"
29 | },
30 | {
31 | "idiom" : "mac",
32 | "size" : "128x128",
33 | "scale" : "2x"
34 | },
35 | {
36 | "idiom" : "mac",
37 | "size" : "256x256",
38 | "scale" : "1x"
39 | },
40 | {
41 | "idiom" : "mac",
42 | "size" : "256x256",
43 | "scale" : "2x"
44 | },
45 | {
46 | "idiom" : "mac",
47 | "size" : "512x512",
48 | "scale" : "1x"
49 | },
50 | {
51 | "idiom" : "mac",
52 | "size" : "512x512",
53 | "scale" : "2x"
54 | }
55 | ],
56 | "info" : {
57 | "version" : 1,
58 | "author" : "xcode"
59 | }
60 | }
--------------------------------------------------------------------------------
/GoldenPassport/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | zh_CN
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIconFile
10 |
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | $(PRODUCT_NAME)
17 | CFBundlePackageType
18 | APPL
19 | CFBundleShortVersionString
20 | $(MARKETING_VERSION)
21 | CFBundleVersion
22 | 1
23 | LSApplicationCategoryType
24 | public.app-category.utilities
25 | LSMinimumSystemVersion
26 | $(MACOSX_DEPLOYMENT_TARGET)
27 | LSUIElement
28 |
29 | NSHumanReadableCopyright
30 | Copyright © 2017年 StanZhai. All rights reserved.
31 | NSMainNibFile
32 | MainMenu
33 | NSPrincipalClass
34 | NSApplication
35 |
36 |
37 |
--------------------------------------------------------------------------------
/GoldenPassport/OTPAuthURLParser.swift:
--------------------------------------------------------------------------------
1 | //
2 | // OTPAuthURLParser.swift
3 | // GoldenPassport
4 | //
5 | // Created by StanZhai on 2017/2/26.
6 | // Copyright © 2017年 StanZhai. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | class OTPAuthURLParser {
12 | var protocal: String
13 | var user: String?
14 | var host: String
15 | var secret: String
16 |
17 | init?(_ otpAuthURL: String) {
18 | // otpauth://totp/user@host?secret=DA82347xxx&issuer=xxx
19 | // otpauth://totp/host?secret=ABCDEFG
20 | if let url = URL(string: otpAuthURL) {
21 | protocal = url.host!
22 |
23 | let pathComponent = url.lastPathComponent
24 |
25 | let parts = pathComponent.components(separatedBy: "@")
26 |
27 | if (parts.count > 1) {
28 | user = parts.first!
29 | host = parts.last!
30 | } else {
31 | host = parts.first!
32 | }
33 |
34 | secret = (
35 | url.query!.components(separatedBy: "&").filter({ (component) -> Bool in
36 | return component.hasPrefix("secret=")
37 | }).first?.components(separatedBy: "=")[1]
38 | )!
39 | } else {
40 | return nil
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/GoldenPassport/OTPAuth/HOTPGenerator.m:
--------------------------------------------------------------------------------
1 | //
2 | // HOTPGenerator.m
3 | //
4 | // Copyright 2011 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "HOTPGenerator.h"
20 |
21 |
22 | @implementation HOTPGenerator
23 | @synthesize counter = counter_;
24 |
25 | + (uint64_t)defaultInitialCounter {
26 | return 1;
27 | }
28 |
29 | - (id)initWithSecret:(NSData *)secret
30 | algorithm:(NSString *)algorithm
31 | digits:(NSUInteger)digits
32 | counter:(uint64_t)counter {
33 | if ((self = [super initWithSecret:secret
34 | algorithm:algorithm
35 | digits:digits])) {
36 | counter_ = counter;
37 | }
38 | return self;
39 | }
40 |
41 | - (NSString *)generateOTP {
42 | NSUInteger counter = [self counter];
43 | counter += 1;
44 | NSString *otp = [super generateOTPForCounter:counter];
45 | [self setCounter:counter];
46 | return otp;
47 | }
48 |
49 | @end
50 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMLightweightProxy.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMLightweightProxy.h
3 | //
4 | // Copyright 2006-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 | #import "GTMDefines.h"
21 |
22 | //
23 | // GTMLightweightProxy
24 | //
25 | // An object which does nothing but stand in for another object and forward
26 | // messages (other than basic NSObject messages) to it, suitable for breaking
27 | // retain cycles. It does *not* retain the represented object, so the
28 | // represented object must be set to nil when that object is deallocated.
29 | //
30 | // Messages sent to a GTMLightweightProxy with no represented object set will
31 | // be silently discarded.
32 | //
33 | @interface GTMLightweightProxy : NSProxy {
34 | @private
35 | GTM_WEAK id representedObject_;
36 | }
37 |
38 | // Initializes the object to represent |object|.
39 | - (id)initWithRepresentedObject:(id)object;
40 |
41 | // Gets the object that the proxy represents.
42 | - (id)representedObject;
43 |
44 | // Changes the proxy to represent |object|
45 | - (void)setRepresentedObject:(id)object;
46 |
47 | @end
48 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSScanner+JSON.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSScanner+JSON.h
3 | //
4 | // Copyright 2009 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 |
21 | // Utilities for NSScanner containing JSON
22 | @interface NSScanner (GTMNSScannerJSONAdditions)
23 |
24 | // Grabs the first JSON Object (dictionary) that it finds and returns it
25 | // in jsonString. We don't parse the json, we just return the first valid JSON
26 | // dictionary we find. There are several other JSON parser packages that
27 | // will actually parse the json for you. We recommend json-framework
28 | // http://code.google.com/p/json-framework/
29 | - (BOOL)gtm_scanJSONObjectString:(NSString **)jsonString;
30 |
31 | // Grabs the first JSON Array (array) that it finds and returns it
32 | // in jsonString. We don't parse the json, we just return the first valid JSON
33 | // array we find. There are several other JSON parser packages that
34 | // will actually parse the json for you. We recommend json-framework
35 | // http://code.google.com/p/json-framework/
36 | - (BOOL)gtm_scanJSONArrayString:(NSString**)jsonString;
37 |
38 | @end
39 |
--------------------------------------------------------------------------------
/GoldenPassport/HTTPPortConfigWindow.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HTTPPortConfigWindow.swift
3 | // GoldenPassport
4 | //
5 | // Created by StanZhai on 2017/3/4.
6 | // Copyright © 2017年 StanZhai. All rights reserved.
7 | //
8 |
9 | import Cocoa
10 |
11 | class HTTPPortConfigWindow: NSWindowController {
12 |
13 | @IBOutlet weak var portTextField: NSTextField!
14 |
15 | override var windowNibName : String! {
16 | return "HTTPPortConfigWindow"
17 | }
18 |
19 | override func windowDidLoad() {
20 | super.windowDidLoad()
21 |
22 | self.window?.center()
23 | portTextField.stringValue = DataManager.shared.getHttpServerPort()
24 | }
25 |
26 | @IBAction func okClicked(_ sender: NSButton) {
27 | let alert: NSAlert = NSAlert()
28 | alert.addButton(withTitle: "确定")
29 | alert.alertStyle = NSAlert.Style.informational
30 |
31 | let port = portTextField.integerValue
32 | if port > 0 && port < 65535 {
33 | self.window?.close()
34 |
35 | let dataManager = DataManager.shared
36 | if port != Int(dataManager.getHttpServerPort()) {
37 | dataManager.saveHttpServerPort(port: "\(portTextField.integerValue)")
38 |
39 | let notificationCenter = NotificationCenter.default
40 | notificationCenter.post(name: NSNotification.Name(rawValue: "HTTPServerPortChanged"), object: nil)
41 |
42 | alert.messageText = "端口号已修改。"
43 | alert.runModal()
44 | }
45 | return
46 | }
47 |
48 | alert.messageText = "端口号必须是大于0小于65535的整数,请检查后重试!"
49 | alert.runModal()
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Xcode
2 | #
3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
4 |
5 | ## Build generated
6 | build/
7 | DerivedData/
8 |
9 | ## Various settings
10 | *.pbxuser
11 | !default.pbxuser
12 | *.mode1v3
13 | !default.mode1v3
14 | *.mode2v3
15 | !default.mode2v3
16 | *.perspectivev3
17 | !default.perspectivev3
18 | xcuserdata/
19 |
20 | ## Other
21 | *.moved-aside
22 | *.xcuserstate
23 |
24 | ## Obj-C/Swift specific
25 | *.hmap
26 | *.ipa
27 | *.dSYM.zip
28 | *.dSYM
29 |
30 | ## Playgrounds
31 | timeline.xctimeline
32 | playground.xcworkspace
33 |
34 | # Swift Package Manager
35 | #
36 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
37 | # Packages/
38 | .build/
39 |
40 | # CocoaPods
41 | #
42 | # We recommend against adding the Pods directory to your .gitignore. However
43 | # you should judge for yourself, the pros and cons are mentioned at:
44 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
45 | #
46 | # Pods/
47 |
48 | # Carthage
49 | #
50 | # Add this line if you want to avoid checking in source code from Carthage dependencies.
51 | # Carthage/Checkouts
52 |
53 | Carthage/Build
54 |
55 | # fastlane
56 | #
57 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
58 | # screenshots whenever they are needed.
59 | # For more information about the recommended setup visit:
60 | # https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md
61 |
62 | fastlane/report.xml
63 | fastlane/Preview.html
64 | fastlane/screenshots
65 | fastlane/test_output
66 |
67 | .DS_Store
68 | Pods/
69 | Packages/
70 | GoldenPassport.xcworkspace/
71 | *.lock
72 | .idea
73 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSString+Replace.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSString+Replace.h
3 | //
4 | // Copyright 2006-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 |
21 | /// Give easy search-n-replace functionality to NSString.
22 | @interface NSString (GTMStringReplaceAdditions)
23 |
24 | #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
25 | // 10.5 has stringByReplacingOccurrencesOfString:withString:, use that directly.
26 |
27 | /// Returns a new autoreleased string by replacing all occurrences of
28 | // |oldString| with |newString| (case sensitive). If |oldString| is nil or
29 | // @"" nothing is done and |self| is returned. If |newString| is nil, it's
30 | // treated as if |newString| were the empty string, thus effectively
31 | // deleting all occurrences of |oldString| from |self|.
32 | //
33 | // Args:
34 | // target - the NSString to search for
35 | // replacement - the NSString to replace |oldString| with
36 | //
37 | // Returns:
38 | // A new autoreleased NSString
39 | //
40 | - (NSString *)gtm_stringByReplacingString:(NSString *)target
41 | withString:(NSString *)replacement;
42 |
43 | #endif // MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
44 |
45 | @end
46 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSDictionary+URLArguments.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSDictionary+URLArguments.h
3 | //
4 | // Copyright 2006-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 |
21 | /// Utility for building a URL or POST argument string.
22 | @interface NSDictionary (GTMNSDictionaryURLArgumentsAdditions)
23 |
24 | /// Returns a dictionary of the decoded key-value pairs in a http arguments
25 | /// string of the form key1=value1&key2=value2&...&keyN=valueN.
26 | /// Keys and values will be unescaped automatically.
27 | /// Only the first value for a repeated key is returned.
28 | ///
29 | /// NOTE: Apps targeting iOS 8 or OS X 10.10 and later should use
30 | /// NSURLComponents and NSURLQueryItem to create URLs with
31 | /// query arguments instead of using these category methods.
32 | + (NSDictionary *)gtm_dictionaryWithHttpArgumentsString:(NSString *)argString;
33 |
34 | /// Gets a string representation of the dictionary in the form
35 | /// key1=value1&key2=value2&...&keyN=valueN, suitable for use as either
36 | /// URL arguments (after a '?') or POST body. Keys and values will be escaped
37 | /// automatically, so should be unescaped in the dictionary.
38 | - (NSString *)gtm_httpArgumentsString;
39 |
40 | @end
41 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSArray+Merge.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSArray+Merge.h
3 | //
4 | // Copyright 2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 |
21 | // Extension to NSArray to allow merging of arrays.
22 | //
23 | @interface NSArray (GTMNSArrayMergingAdditions)
24 |
25 | // Merge our array with |newArray| by sorting each array then merging the
26 | // two arrays. If |merger| is provided then call that method on any old
27 | // items that compare as equal to a new item, passing the new item as
28 | // the only argument. If |merger| is not provided, then insert new items
29 | // in front of matching old items. If neither array has any items then
30 | // nil is returned.
31 | //
32 | // The signature of the |merger| is:
33 | // - (id)merge:(id)newItem;
34 | //
35 | // Returns a new, sorted array.
36 | - (NSArray *)gtm_mergeArray:(NSArray *)newArray
37 | mergeSelector:(SEL)merger;
38 |
39 | // Same as above, only |comparer| is used to sort/compare the objects, just like
40 | // -[NSArray sortedArrayUsingSelector]. If |comparer| is nil, nil is returned.
41 | - (NSArray *)gtm_mergeArray:(NSArray *)newArray
42 | compareSelector:(SEL)comparer
43 | mergeSelector:(SEL)merger;
44 |
45 | @end
46 |
47 |
48 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSThread+Blocks.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSThread+Blocks.h
3 | //
4 | // Copyright 2012 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 | // Based on http://www.informit.com/blogs/blog.aspx?uk=Ask-Big-Nerd-Ranch-Blocks-in-Objective-C
19 |
20 | #import
21 | #import "GTMDefines.h"
22 |
23 | // Extension to NSThread to work with blocks.
24 |
25 | #if NS_BLOCKS_AVAILABLE
26 |
27 | @interface NSThread (GTMBlocksAdditions)
28 |
29 | // If self is not the current thread, the block will be called asynchronously
30 | // and this method returns immediately.
31 | // If self is the current thread, the block will be performed immediately, and
32 | // then this method will return.
33 | - (void)gtm_performBlock:(void (^)(void))block;
34 |
35 | - (void)gtm_performWaitingUntilDone:(BOOL)waitDone block:(void (^)(void))block;
36 | + (void)gtm_performBlockInBackground:(void (^)(void))block;
37 | @end
38 |
39 | #endif // NS_BLOCKS_AVAILABLE
40 |
41 | // A simple thread that does nothing but handle performBlock and
42 | // performSelector calls.
43 | @interface GTMSimpleWorkerThread : NSThread {
44 | @private
45 | CFRunLoopRef runLoop_;
46 | NSConditionLock *runLock_;
47 | }
48 |
49 | // Will stop the thread, blocking till the thread exits.
50 | - (void)stop;
51 |
52 | @end
53 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMDebugThreadValidation.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMDebugThreadValidation.h
3 | //
4 | // Copyright 2016 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMDefines.h"
20 | #import
21 |
22 | // GTMCheckCurrentQueue, GTMIsCurrentQueue
23 | //
24 | // GTMCheckCurrentQueue takes a target queue and uses _GTMDevAssert to
25 | // report if that is not the currently executing queue.
26 | //
27 | // GTMIsCurrentQueue takes a target queue and returns true if the target queue
28 | // is the currently executing dispatch queue. This can be passed to another
29 | // assertion call in debug builds; it should never be used in release code.
30 | //
31 | // The dispatch queue must have a label.
32 | #define GTMCheckCurrentQueue(targetQueue) \
33 | _GTMDevAssert(GTMIsCurrentQueue(targetQueue), \
34 | @"Current queue is %s (expected %s)", \
35 | _GTMQueueName(DISPATCH_CURRENT_QUEUE_LABEL), \
36 | _GTMQueueName(targetQueue))
37 |
38 | #define GTMIsCurrentQueue(targetQueue) \
39 | (strcmp(_GTMQueueName(DISPATCH_CURRENT_QUEUE_LABEL), \
40 | _GTMQueueName(targetQueue)) == 0)
41 |
42 | #define _GTMQueueName(queue) \
43 | (strlen(dispatch_queue_get_label(queue)) > 0 ? \
44 | dispatch_queue_get_label(queue) : "unnamed")
45 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSString+URLArguments.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSString+URLArguments.h
3 | //
4 | // Copyright 2006-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 |
21 | /// Utilities for encoding and decoding URL arguments.
22 | @interface NSString (GTMNSStringURLArgumentsAdditions)
23 |
24 | /// Returns a string that is escaped properly to be a URL argument.
25 | ///
26 | /// This differs from stringByAddingPercentEscapesUsingEncoding: in that it
27 | /// will escape all the reserved characters (per RFC 3986
28 | /// ) which
29 | /// stringByAddingPercentEscapesUsingEncoding would leave.
30 | ///
31 | /// This will also escape '%', so this should not be used on a string that has
32 | /// already been escaped unless double-escaping is the desired result.
33 | ///
34 | /// NOTE: Apps targeting iOS 8 or OS X 10.10 and later should use
35 | /// NSURLComponents and NSURLQueryItem to create properly-escaped
36 | /// URLs instead of using these category methods.
37 | - (NSString*)gtm_stringByEscapingForURLArgument;
38 |
39 | /// Returns the unescaped version of a URL argument
40 | ///
41 | /// This has the same behavior as stringByReplacingPercentEscapesUsingEncoding:,
42 | /// except that it will also convert '+' to space.
43 | - (NSString*)gtm_stringByUnescapingFromURLArgument;
44 |
45 | @end
46 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSString+XML.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSString+XML.h
3 | //
4 | // Copyright 2007-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 |
21 | /// Utilities for NSStrings containing XML
22 | @interface NSString (GTMNSStringXMLAdditions)
23 |
24 | /// Get a string where characters that need escaping for XML are escaped and invalid characters removed
25 | //
26 | /// This call escapes '&', '<, '>', '\'', '"' per the xml spec and removes all
27 | /// invalid characters as defined by Section 2.2 of the xml spec.
28 | ///
29 | /// For obvious reasons this call is only safe once.
30 | //
31 | // Returns:
32 | // Autoreleased NSString
33 | //
34 | - (NSString *)gtm_stringBySanitizingAndEscapingForXML;
35 |
36 | /// Get a string where characters that invalid characters per the XML spec have been removed
37 | //
38 | /// This call removes all invalid characters as defined by Section 2.2 of the
39 | /// xml spec. If you are writing XML yourself, you probably was to use the
40 | /// above api (gtm_stringBySanitizingAndEscapingForXML) so any entities also
41 | /// get escaped.
42 | //
43 | // Returns:
44 | // Autoreleased NSString
45 | //
46 | - (NSString *)gtm_stringBySanitizingToXMLSpec;
47 |
48 | // There is no stringByUnescapingFromXML because the XML parser will do this.
49 | // The above api is here just incase you need to create XML yourself.
50 |
51 | @end
52 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSFileManager+Path.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSFileManager+Path.h
3 | //
4 | // Copyright 2006-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 |
21 |
22 | /// A few useful methods for dealing with paths.
23 | @interface NSFileManager (GMFileManagerPathAdditions)
24 |
25 | /// Return an the paths for all resources in |directoryPath| that have the
26 | /// |extension| file extension.
27 | ///
28 | /// Args:
29 | /// extension - the file extension (excluding the leading ".") to match.
30 | /// If nil, all files are matched.
31 | /// directoryPath - the directory to look in. NOTE: Subdirectories are NOT
32 | /// traversed.
33 | ///
34 | /// Returns:
35 | /// An NSArray of absolute file paths that have |extension|. nil is returned
36 | /// if |directoryPath| doesn't exist or can't be opened, and returns an empty
37 | /// array if |directoryPath| is empty. ".", "..", and resource forks are never returned.
38 | ///
39 | - (NSArray *)gtm_filePathsWithExtension:(NSString *)extension
40 | inDirectory:(NSString *)directoryPath;
41 |
42 | /// Same as -filePathsWithExtension:inDirectory: except |extensions| is an
43 | /// NSArray of extensions to match.
44 | ///
45 | - (NSArray *)gtm_filePathsWithExtensions:(NSArray *)extensions
46 | inDirectory:(NSString *)directoryPath;
47 |
48 | @end
49 |
--------------------------------------------------------------------------------
/GoldenPassport/OTPAuth/TOTPGenerator.m:
--------------------------------------------------------------------------------
1 | //
2 | // TOTPGenerator.m
3 | //
4 | // Copyright 2011 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "TOTPGenerator.h"
20 | #import "GTMDefines.h"
21 |
22 | @interface TOTPGenerator ()
23 | @property(assign, nonatomic, readwrite) NSTimeInterval period;
24 | @end
25 |
26 | @implementation TOTPGenerator
27 | @synthesize period = period_;
28 |
29 | + (NSTimeInterval)defaultPeriod {
30 | return 30;
31 | }
32 |
33 | - (id)initWithSecret:(NSData *)secret
34 | algorithm:(NSString *)algorithm
35 | digits:(NSUInteger)digits
36 | period:(NSTimeInterval)period {
37 | if ((self = [super initWithSecret:secret
38 | algorithm:algorithm
39 | digits:digits])) {
40 |
41 | if (period <= 0 || period > 300) {
42 | _GTMDevLog(@"Bad Period: %f", period);
43 | [self release];
44 | self = nil;
45 | } else {
46 | self.period = period;
47 | }
48 | }
49 | return self;
50 | }
51 |
52 | - (NSString *)generateOTP {
53 | return [self generateOTPForDate:[NSDate date]];
54 | }
55 |
56 | - (NSString *)generateOTPForDate:(NSDate *)date {
57 | if (!date) {
58 | // If no now date specified, use the current date.
59 | date = [NSDate date];
60 | }
61 |
62 | NSTimeInterval seconds = [date timeIntervalSince1970];
63 | uint64_t counter = (uint64_t)(seconds / self.period);
64 | return [super generateOTPForCounter:counter];
65 | }
66 |
67 | @end
68 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSString+URLArguments.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSString+URLArguments.m
3 | //
4 | // Copyright 2006-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMNSString+URLArguments.h"
20 |
21 | @implementation NSString (GTMNSStringURLArgumentsAdditions)
22 |
23 | - (NSString *)gtm_stringByEscapingForURLArgument {
24 | // Encode all the reserved characters, per RFC 3986
25 | // ()
26 | CFStringRef escaped =
27 | CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
28 | (CFStringRef)self,
29 | NULL,
30 | (CFStringRef)@"!*'();:@&=+$,/?%#[]",
31 | kCFStringEncodingUTF8);
32 | #if defined(__has_feature) && __has_feature(objc_arc)
33 | return CFBridgingRelease(escaped);
34 | #else
35 | return [(NSString *)escaped autorelease];
36 | #endif
37 | }
38 |
39 | - (NSString *)gtm_stringByUnescapingFromURLArgument {
40 | NSMutableString *resultString = [NSMutableString stringWithString:self];
41 | [resultString replaceOccurrencesOfString:@"+"
42 | withString:@" "
43 | options:NSLiteralSearch
44 | range:NSMakeRange(0, [resultString length])];
45 | return [resultString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
46 | }
47 |
48 | @end
49 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSString+Replace.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSString+Replace.m
3 | //
4 | // Copyright 2006-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMNSString+Replace.h"
20 |
21 |
22 | @implementation NSString (GTMStringReplaceAdditions)
23 |
24 | #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
25 | // 10.5 has stringByReplacingOccurrencesOfString:withString:, use that directly.
26 |
27 | - (NSString *)gtm_stringByReplacingString:(NSString *)target
28 | withString:(NSString *)replacement {
29 | // If |target| was nil, then do nothing and return |self|
30 | //
31 | // We do the retain+autorelease dance here because of this use case:
32 | // NSString *s1 = [[NSString alloc] init...];
33 | // NSString *s2 = [s1 stringByReplacingString:@"foo" withString:@"bar"];
34 | // [s1 release]; // |s2| still needs to be valid after this line
35 | if (!target)
36 | return [[self retain] autorelease];
37 |
38 | // If |replacement| is nil we want it to be treated as if @"" was specified
39 | // ... effectively removing |target| from self
40 | if (!replacement)
41 | replacement = @"";
42 |
43 | NSMutableString *result = [[self mutableCopy] autorelease];
44 | [result replaceOccurrencesOfString:target
45 | withString:replacement
46 | options:0
47 | range:NSMakeRange(0, [result length])];
48 | return result;
49 | }
50 |
51 | #endif // MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
52 |
53 | @end
54 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # GoldenPassport
2 |
3 | A native implementation of Google Authenticator for Mac based on Swift3.
4 |
5 | # Screenshot
6 |
7 | 
8 |
9 | 
10 |
11 | 
12 |
13 | # Features
14 |
15 | - Recognize OTPAuth URL from a QRCode image
16 | - Authentication code management
17 | - Support RESTful API to obtain the verification code
18 | - Use a global hot key(`Shift+Cmd+[0-9]`) to direct fill out the verification code
19 | - Click an auth-menu to copy the verification code to the `PasteBoard`
20 | - Export/Import authentication codes
21 |
22 | # How to use
23 |
24 | 1. Download the latest version of GoldenPassport from the [releases](https://github.com/stanzhai/GoldenPassport/releases) page.
25 | 2. Unzip `GoldenPassport.zip` and put `GoldenPassport.app` to your `Application` folder then start it.
26 | 3. Add an auth URL from the status menu.
27 |
28 | Or you can install if from brew cask
29 |
30 | ```
31 | brew install --cask goldenpassport
32 | ```
33 |
34 | Now, you can get the verification code by:
35 |
36 | - From the status menu, copy the verification by clicking an auth-menu
37 | - Use a global hot key(`Shift+Cmd+[0-9]`) to direct fill out the verification code
38 |
39 | You can also use the RESTful API if you want to get the verification code from a shell script by the following way:
40 |
41 | ```
42 | # you can get the url from `http://localhost:17304/`
43 | code=$(curl 'http://localhost:17304/code/test@stanzhai.site')
44 | # ues the verification code
45 | echo $code
46 | ```
47 |
48 | # Building
49 |
50 | GoldenPassport uses `cocoapods` as the package manager tool, you should install it first.
51 |
52 | 1. `pod install` to install dependencies
53 | 2. Open `GoldenPassport.xcworkspace` with Xcode to build
54 |
55 | # Todo
56 |
57 | - Support auto startup with system
58 | - i18n
59 |
60 | # Resources
61 |
62 | - [Swift Resources](https://developer.apple.com/swift/resources/)
63 | - [macOS Development Tutorials](https://www.raywenderlich.com/category/macos)
64 | - [google-authenticator](https://github.com/google/google-authenticator)
65 | - [WeatherBar](http://footle.org/WeatherBar/)
66 | - [swifter](https://github.com/httpswift/swifter)
67 |
--------------------------------------------------------------------------------
/GoldenPassport/KeyboardMonitor.swift:
--------------------------------------------------------------------------------
1 | //
2 | // KeyboardMonitor.swift
3 | // GoldenPassport
4 | //
5 | // Created by StanZhai on 2017/3/4.
6 | // Copyright © 2017年 StanZhai. All rights reserved.
7 | //
8 |
9 | import Cocoa
10 |
11 | /* Monitor keyboard envent for Shift+Cmd+[0-9] to set auth code */
12 | class KeyboardMonitor {
13 | private var monitor: Any?
14 |
15 | func start() {
16 | let opts = NSDictionary(object: kCFBooleanTrue, forKey: kAXTrustedCheckOptionPrompt.takeUnretainedValue() as NSString) as CFDictionary
17 | guard AXIsProcessTrustedWithOptions(opts) == true else { return }
18 | monitor = NSEvent.addGlobalMonitorForEvents(matching: .keyDown, handler: self.handleKeydownEvent)
19 | }
20 |
21 | func stop() {
22 | if monitor != nil {
23 | NSEvent.removeMonitor(monitor!)
24 | monitor = nil
25 | }
26 | }
27 |
28 | private func handleKeydownEvent(_ event: NSEvent) {
29 | let flag = event.modifierFlags.rawValue
30 | // flag of: Shift + Cmd
31 | if flag != 1179924 && flag != 1179914 {
32 | return
33 | }
34 |
35 | if let char = event.characters {
36 | if let num = Int(char) {
37 | setAuthCode(idx: num)
38 | }
39 | }
40 | }
41 |
42 | private func setAuthCode(idx: Int) {
43 | if (idx >= DataManager.shared.dataCount()) {
44 | return
45 | }
46 |
47 | let authCodes = DataManager.shared.allAuthCode()
48 | var i = 0
49 | for codeInfo in authCodes {
50 | if i == idx {
51 | let pasteboard = NSPasteboard.general
52 | let oldData = pasteboard.string(forType: .string)
53 | pasteboard.clearContents()
54 | pasteboard.setString(codeInfo.value, forType: .string)
55 |
56 | SimulateKeyBoardEvent.paste()
57 |
58 | if (oldData != nil) {
59 | sleep(1)
60 | pasteboard.clearContents()
61 | pasteboard.setString(oldData!, forType: .string)
62 | }
63 |
64 | break
65 | }
66 | i = i + 1
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/GoldenPassport/OTPAuth/TOTPGenerator.h:
--------------------------------------------------------------------------------
1 | //
2 | // TOTPGenerator.h
3 | //
4 | // Copyright 2011 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 | #import "OTPGenerator.h"
21 |
22 | // The TOTPGenerator class generates a one-time password (OTP) using
23 | // the Time-based One-time Password Algorithm described in:
24 | // http://tools.ietf.org/html/draft-mraihi-totp-timebased
25 | //
26 | // Basically, we define TOTP as TOTP = HOTP(K, T) where T is an integer
27 | // and represents the number of time steps between the initial counter
28 | // time T0 and the current Unix time (i.e. the number of seconds elapsed
29 | // since midnight UTC of January 1, 1970).
30 | //
31 | // More specifically T = (Current Unix time - T0) / X where:
32 | //
33 | // - X represents the time step in seconds (default value X = 30
34 | // seconds) and is a system parameter;
35 | //
36 | // - T0 is the Unix time to start counting time steps (default value is
37 | // 0, Unix epoch) and is also a system parameter.
38 | //
39 | @interface TOTPGenerator : OTPGenerator
40 |
41 | // The period to use when calculating the counter.
42 | @property(assign, nonatomic, readonly) NSTimeInterval period;
43 |
44 | + (NSTimeInterval)defaultPeriod;
45 |
46 | // Designated initializer.
47 | - (id)initWithSecret:(NSData *)secret
48 | algorithm:(NSString *)algorithm
49 | digits:(NSUInteger)digits
50 | period:(NSTimeInterval)period;
51 |
52 | // Instance method to generate an OTP using the |algorithm|, |secret|,
53 | // |digits|, |period| and |now| values configured on the object.
54 | // The return value is an NSString of |digits| length, with leading
55 | // zero-padding as required.
56 | - (NSString *)generateOTPForDate:(NSDate *)date;
57 |
58 | @end
59 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSString+FindFolder.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSString+FindFolder.h
3 | //
4 | // Copyright 2006-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 |
21 | @interface NSString (GTMStringFindFolderAdditions)
22 |
23 | // Create a path to a folder located with FindFolder
24 | //
25 | // Args:
26 | // theFolderType: one of the folder types in Folders.h
27 | // (kPreferencesFolderType, etc)
28 | // theDomain: one of the domains in Folders.h (kLocalDomain, kUserDomain, etc)
29 | // doCreate: create the folder if it does not already exist
30 | //
31 | // Returns:
32 | // full path to folder, or nil if the folder doesn't exist or can't be created
33 | //
34 | + (NSString *)gtm_stringWithPathForFolder:(OSType)theFolderType
35 | inDomain:(short)theDomain
36 | doCreate:(BOOL)doCreate;
37 |
38 | // Create a path to a folder inside a folder located with FindFolder
39 | //
40 | // Args:
41 | // theFolderType: one of the folder types in Folders.h
42 | // (kPreferencesFolderType, etc)
43 | // subfolderName: name of directory inside the Apple folder to be located or created
44 | // theDomain: one of the domains in Folders.h (kLocalDomain, kUserDomain, etc)
45 | // doCreate: create the folder if it does not already exist
46 | //
47 | // Returns:
48 | // full path to subdirectory, or nil if the folder doesn't exist or can't be created
49 | //
50 | + (NSString *)gtm_stringWithPathForFolder:(OSType)theFolderType
51 | subfolderName:(NSString *)subfolderName
52 | inDomain:(short)theDomain
53 | doCreate:(BOOL)doCreate;
54 |
55 | @end
56 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSFileManager+Carbon.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSFileManager+Carbon.h
3 | //
4 | // Copyright 2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 |
21 |
22 | // A few useful methods for dealing with paths and carbon structures
23 | @interface NSFileManager (GTMFileManagerCarbonAdditions)
24 |
25 | // Converts a path to an alias
26 | // Args:
27 | // path - the path to convert
28 | //
29 | // Returns:
30 | // An alias wrapped up in an autoreleased NSData. Nil on failure.
31 | //
32 | - (NSData *)gtm_aliasDataForPath:(NSString *)path;
33 |
34 | // Converts an alias to a path
35 | // Args:
36 | // alias - an alias wrapped up in an NSData
37 | //
38 | // Returns:
39 | // The path. Nil on failure.
40 | //
41 | - (NSString *)gtm_pathFromAliasData:(NSData *)alias;
42 |
43 | // Converts an alias to a path without optional triggering of UI.
44 | // Args:
45 | // alias - an alias wrapped up in an NSData
46 | // resolve - whether to try to resolve the alias, or simply read path data
47 | // withUI - whether to show UI when trying to resolve
48 | //
49 | // Returns:
50 | // The path. Nil on failure.
51 | //
52 | - (NSString *)gtm_pathFromAliasData:(NSData *)alias
53 | resolve:(BOOL)resolve
54 | withUI:(BOOL)withUI;
55 |
56 | // Converts a path to an FSRef *
57 | // Args:
58 | // path - the path to convert
59 | //
60 | // Returns:
61 | // An autoreleased FSRef *. Nil on failure.
62 | //
63 | - (FSRef *)gtm_FSRefForPath:(NSString *)path;
64 |
65 | // Converts an FSRef to a path
66 | // Args:
67 | // fsRef - the FSRef to convert
68 | //
69 | // Returns:
70 | // The path. Nil on failure.
71 | //
72 | - (NSString *)gtm_pathFromFSRef:(FSRef *)fsRef;
73 | @end
74 |
--------------------------------------------------------------------------------
/GoldenPassport/SimulateKeyBoardEvent.swift:
--------------------------------------------------------------------------------
1 | //
2 | // SimulateKeyBoardEvent.swift
3 | // GoldenPassport
4 | //
5 | // Created by StanZhai on 2017/2/28.
6 | // Copyright © 2017年 StanZhai. All rights reserved.
7 | //
8 |
9 | import Cocoa
10 |
11 | class SimulateKeyBoardEvent {
12 |
13 | // simulate command+v
14 | class func paste() {
15 | let source = CGEventSource(stateID: CGEventSourceStateID.combinedSessionState)
16 | if let pressEvent = CGEvent(keyboardEventSource: source, virtualKey: CGKeyCode.init(9), keyDown: true) {
17 | pressEvent.flags = CGEventFlags.maskCommand
18 | pressEvent.post(tap: CGEventTapLocation.cghidEventTap)
19 | if let releaseEvent = CGEvent(keyboardEventSource: source, virtualKey: CGKeyCode.init(9), keyDown: false) {
20 | releaseEvent.flags = CGEventFlags.maskCommand
21 | releaseEvent.post(tap: CGEventTapLocation.cghidEventTap)
22 | }
23 | }
24 | }
25 |
26 | class func sendString(_ str: String) {
27 | // Loop through each character in the UTF16 representation of the string.
28 | for char in str {
29 | // for char in str.characters {
30 |
31 | let source = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)
32 | let keyCode = KeyCode.enumWith(char)
33 |
34 | guard let virtualKey: CGKeyCode = keyCode?.rawValue else {
35 | return
36 | }
37 |
38 | let keyDown = CGEvent(keyboardEventSource: source, virtualKey: virtualKey, keyDown: true)
39 | let keyUp = CGEvent(keyboardEventSource: source, virtualKey: virtualKey, keyDown: false)
40 |
41 | let loc = CGEventTapLocation.cghidEventTap
42 |
43 | keyDown!.post(tap: loc)
44 | keyUp!.post(tap: loc)
45 |
46 | /*
47 | if let pressEvent = CGEvent(keyboardEventSource: source, virtualKey: CGKeyCode.init(character), keyDown: true) {
48 | pressEvent.post(tap: CGEventTapLocation.cghidEventTap)
49 | if let releaseEvent = CGEvent(keyboardEventSource: source, virtualKey: CGKeyCode.init(character), keyDown: false) {
50 | releaseEvent.post(tap: CGEventTapLocation.cghidEventTap)
51 | }
52 | }
53 | */
54 |
55 |
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMTypeCasting.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMTypeCasting.h
3 | //
4 | // Copyright 2010 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 | #import "GTMDefines.h"
21 |
22 | // These are some basic macros for making down-casting safer in Objective C.
23 | // They are loosely based on the same cast types with similar names in C++.
24 | // A typical usage would look like this:
25 | //
26 | // Bar* b = [[Bar alloc] init];
27 | // Foo* a = GTM_STATIC_CAST(Foo, b);
28 | //
29 | // Note that it's GTM_STATIC_CAST(Foo, b) and not GTM_STATIC_CAST(Foo*, b).
30 | //
31 | // GTM_STATIC_CAST runs only in debug mode, and will assert if and only if:
32 | // - object is non nil
33 | // - [object isKindOfClass:[cls class]] returns nil
34 | //
35 | // otherwise it returns object.
36 | //
37 | // GTM_DYNAMIC_CAST runs in both debug and release and will return nil if
38 | // - object is nil
39 | // - [object isKindOfClass:[cls class]] returns nil
40 | //
41 | // otherwise it returns object.
42 | //
43 |
44 | // Support functions for dealing with casting.
45 | GTM_INLINE id GTMDynamicCastSupport(Class cls, id object) {
46 | _GTMDevAssert(cls, @"Nil Class");
47 | return [object isKindOfClass:cls] ? object : nil;
48 | }
49 |
50 | GTM_INLINE id GTMStaticCastSupport(Class cls, id object) {
51 | id value = nil;
52 | if (object) {
53 | value = GTMDynamicCastSupport(cls, object);
54 | _GTMDevAssert(value, @"Could not cast %@ to class %@", object, cls);
55 | }
56 | return value;
57 | }
58 |
59 | #ifndef GTM_STATIC_CAST
60 | #ifdef DEBUG
61 | #define GTM_STATIC_CAST(type, object) \
62 | ((type *) GTMStaticCastSupport([type class], object))
63 | #else
64 | #define GTM_STATIC_CAST(type, object) ((type *) (object))
65 | #endif
66 | #endif
67 |
68 | #ifndef GTM_DYNAMIC_CAST
69 | #define GTM_DYNAMIC_CAST(type, object) \
70 | ((type *) GTMDynamicCastSupport([type class], object))
71 | #endif
72 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMObjectSingleton.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMObjectSingleton.h
3 | // Macro to implement a creation method for a singleton
4 | //
5 | // Copyright 2005-2008 Google Inc.
6 | //
7 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
8 | // use this file except in compliance with the License. You may obtain a copy
9 | // of the License at
10 | //
11 | // http://www.apache.org/licenses/LICENSE-2.0
12 | //
13 | // Unless required by applicable law or agreed to in writing, software
14 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | // License for the specific language governing permissions and limitations under
17 | // the License.
18 | //
19 |
20 | //
21 | // This file has been kept around for compatibility with apps relying on its macro,
22 | // but given how simple this is, there is not a compelling reason for any app to
23 | // use this macro.
24 | //
25 | // For a reasonable discussion of Objective-C singletons, see
26 | // http://eschatologist.net/blog/?p=178
27 | //
28 | // Sample usage:
29 | //
30 | // GTMOBJECT_SINGLETON_BOILERPLATE(SomeUsefulManager, sharedSomeUsefulManager)
31 | // (with no trailing semicolon)
32 | //
33 |
34 | #include
35 |
36 | #if (defined(__IPHONE_7_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0)) \
37 | || (defined(MAC_OS_X_VERSION_10_9) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9))
38 | #error "GTMOBJECT_SINGLETON_BOILERPLATE is deprecated; change this in your sources to a class method using dispatch_once."
39 | #endif
40 |
41 | #if NS_BLOCKS_AVAILABLE
42 |
43 | #define GTMOBJECT_SINGLETON_BOILERPLATE(_object_name_, _shared_obj_name_) \
44 | + (_object_name_ *)_shared_obj_name_ { \
45 | static _object_name_ *obj; \
46 | static dispatch_once_t onceToken; \
47 | dispatch_once(&onceToken, ^{ \
48 | obj = [[self alloc] init]; \
49 | }); \
50 | return obj; \
51 | }
52 |
53 | #else
54 |
55 | #define GTMOBJECT_SINGLETON_BOILERPLATE(_object_name_, _shared_obj_name_) \
56 | + (_object_name_ *)_shared_obj_name_ { \
57 | static _object_name_ *obj; \
58 | if (obj == nil) { \
59 | obj = [[self alloc] init]; \
60 | } \
61 | return obj; \
62 | }
63 |
64 | #endif // NS_BLOCKS_AVAILABLE
65 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSString+HTML.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSString+HTML.h
3 | // Dealing with NSStrings that contain HTML
4 | //
5 | // Copyright 2006-2008 Google Inc.
6 | //
7 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
8 | // use this file except in compliance with the License. You may obtain a copy
9 | // of the License at
10 | //
11 | // http://www.apache.org/licenses/LICENSE-2.0
12 | //
13 | // Unless required by applicable law or agreed to in writing, software
14 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 | // License for the specific language governing permissions and limitations under
17 | // the License.
18 | //
19 |
20 | #import
21 |
22 | /// Utilities for NSStrings containing HTML
23 | @interface NSString (GTMNSStringHTMLAdditions)
24 |
25 | /// Get a string where internal characters that need escaping for HTML are escaped
26 | //
27 | /// For example, '&' become '&'. This will only cover characters from table
28 | /// A.2.2 of http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_Special_characters
29 | /// which is what you want for a unicode encoded webpage. If you have a ascii
30 | /// or non-encoded webpage, please use stringByEscapingAsciiHTML which will
31 | /// encode all characters.
32 | ///
33 | /// For obvious reasons this call is only safe once.
34 | //
35 | // Returns:
36 | // Autoreleased NSString
37 | //
38 | - (NSString *)gtm_stringByEscapingForHTML;
39 |
40 | /// Get a string where internal characters that need escaping for HTML are escaped
41 | //
42 | /// For example, '&' become '&'
43 | /// All non-mapped characters (unicode that don't have a &keyword; mapping)
44 | /// will be converted to the appropriate xx; value. If your webpage is
45 | /// unicode encoded (UTF16 or UTF8) use stringByEscapingHTML instead as it is
46 | /// faster, and produces less bloated and more readable HTML (as long as you
47 | /// are using a unicode compliant HTML reader).
48 | ///
49 | /// For obvious reasons this call is only safe once.
50 | //
51 | // Returns:
52 | // Autoreleased NSString
53 | //
54 | - (NSString *)gtm_stringByEscapingForAsciiHTML;
55 |
56 | /// Get a string where internal characters that are escaped for HTML are unescaped
57 | //
58 | /// For example, '&' becomes '&'
59 | /// Handles and 2 cases as well
60 | ///
61 | // Returns:
62 | // Autoreleased NSString
63 | //
64 | - (NSString *)gtm_stringByUnescapingFromHTML;
65 |
66 | @end
67 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSFileManager+Path.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSFileManager+Path.m
3 | //
4 | // Copyright 2006-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMNSFileManager+Path.h"
20 | #import "GTMDefines.h"
21 |
22 | @implementation NSFileManager (GMFileManagerPathAdditions)
23 |
24 | - (NSArray *)gtm_filePathsWithExtension:(NSString *)extension
25 | inDirectory:(NSString *)directoryPath {
26 | NSArray *extensions = nil;
27 |
28 | // Treat no extension and an empty extension as the user requesting all files
29 | if (extension != nil && ![extension isEqualToString:@""])
30 | extensions = [NSArray arrayWithObject:extension];
31 |
32 | return [self gtm_filePathsWithExtensions:extensions
33 | inDirectory:directoryPath];
34 | }
35 |
36 | - (NSArray *)gtm_filePathsWithExtensions:(NSArray *)extensions
37 | inDirectory:(NSString *)directoryPath {
38 | if (!directoryPath) {
39 | return nil;
40 | }
41 |
42 | // |basenames| will contain only the matching file names, not their full paths.
43 | NSArray *basenames = [self contentsOfDirectoryAtPath:directoryPath
44 | error:nil];
45 |
46 |
47 | // Check if dir doesn't exist or couldn't be opened.
48 | if (!basenames) {
49 | return nil;
50 | }
51 |
52 | // Check if dir is empty.
53 | if ([basenames count] == 0) {
54 | return basenames;
55 | }
56 |
57 | NSMutableArray *paths = [NSMutableArray arrayWithCapacity:[basenames count]];
58 | NSString *basename;
59 |
60 | // Convert all the |basenames| to full paths.
61 | for (basename in basenames) {
62 | NSString *fullPath = [directoryPath stringByAppendingPathComponent:basename];
63 | [paths addObject:fullPath];
64 | }
65 |
66 | // Check if caller wants all files, regardless of extension.
67 | if ([extensions count] == 0) {
68 | return paths;
69 | }
70 |
71 | return [paths pathsMatchingExtensions:extensions];
72 | }
73 |
74 | @end
75 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMMethodCheck.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMMethodCheck.h
3 | //
4 | // Copyright 2006-2016 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 | #import
21 | #import
22 |
23 | /// A macro for enforcing debug time checks to make sure all required methods are linked in
24 | //
25 | // When using categories, it can be very easy to forget to include the
26 | // implementation of a category.
27 | // Let's say you had a class foo that depended on method bar of class baz, and
28 | // method bar was implemented as a member of a category.
29 | // You could add the following code:
30 | //
31 | // GTM_METHOD_CHECK(baz, bar)
32 | //
33 | // and the code would check to make sure baz was implemented just before main
34 | // was called. This works for both dynamic libraries, and executables.
35 | //
36 | //
37 | // This is not compiled into release builds.
38 |
39 | #ifdef DEBUG
40 |
41 | // This is the "magic".
42 | // A) we need a multi layer define here so that the preprocessor expands
43 | // __LINE__ the way we want it. We need __LINE__ so that each of our
44 | // GTM_METHOD_CHECKs generates a unique function name.
45 | #define GTM_METHOD_CHECK(class, method) GTM_METHOD_CHECK_INNER(class, method, __LINE__)
46 | #define GTM_METHOD_CHECK_INNER(class, method, line) \
47 | GTM_METHOD_CHECK_INNER_INNER(class, method, line)
48 |
49 | // B) define a function that is called at startup to check that |class| has an
50 | // implementation for |method| (either a class method or an instance method).
51 | #define GTM_METHOD_CHECK_INNER_INNER(class, method, line) \
52 | __attribute__ ((constructor, visibility("hidden"))) \
53 | static void xxGTMMethodCheckMethod ## class ## line () { \
54 | @autoreleasepool { \
55 | if (![class instancesRespondToSelector:@selector(method)] \
56 | && ![class respondsToSelector:@selector(method)]) { \
57 | fprintf(stderr, "%s:%d: error: We need method '%s' to be linked in for class '%s'\n", \
58 | __FILE__, line, #method, #class); \
59 | exit(EX_SOFTWARE); \
60 | } \
61 | } \
62 | }
63 |
64 | #else // DEBUG
65 |
66 | // Do nothing in release.
67 | #define GTM_METHOD_CHECK(class, method)
68 |
69 | #endif // DEBUG
70 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSObject+KeyValueObserving.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSObject+KeyValueObserving.h
3 | //
4 | // Copyright 2009 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | //
20 | // MAKVONotificationCenter.h
21 | // MAKVONotificationCenter
22 | //
23 | // Created by Michael Ash on 10/15/08.
24 | //
25 |
26 | // This code is based on code by Michael Ash.
27 | // Please see his excellent writeup at
28 | // http://www.mikeash.com/?page=pyblog/key-value-observing-done-right.html
29 | // You may also be interested in this writeup:
30 | // http://www.dribin.org/dave/blog/archives/2008/09/24/proper_kvo_usage/
31 | // and the discussion on cocoa-dev that is linked to at the end of it.
32 |
33 | #import
34 |
35 | // If you read the articles above you will see that doing KVO correctly
36 | // is actually pretty tricky, and that Apple's documentation may not be
37 | // completely clear as to how things should be used. Use the methods below
38 | // to make things a little easier instead of the stock addObserver,
39 | // removeObserver methods.
40 | // Selector should have the following signature:
41 | // - (void)observeNotification:(GTMKeyValueChangeNotification *)notification
42 | @interface NSObject (GTMKeyValueObservingAdditions)
43 |
44 | // Use this instead of [NSObject addObserver:forKeyPath:options:context:]
45 | - (void)gtm_addObserver:(id)observer
46 | forKeyPath:(NSString *)keyPath
47 | selector:(SEL)selector
48 | userInfo:(id)userInfo
49 | options:(NSKeyValueObservingOptions)options;
50 | // Use this instead of [NSObject removeObserver:forKeyPath:]
51 | - (void)gtm_removeObserver:(id)observer
52 | forKeyPath:(NSString *)keyPath
53 | selector:(SEL)selector;
54 |
55 | // Use this to have |self| stop observing all keypaths on all objects.
56 | - (void)gtm_stopObservingAllKeyPaths;
57 |
58 | @end
59 |
60 | // This is the class that is sent to your notification selector as an
61 | // argument.
62 | @interface GTMKeyValueChangeNotification : NSObject {
63 | @private
64 | NSString *keyPath_;
65 | id object_;
66 | id userInfo_;
67 | NSDictionary *change_;
68 | }
69 |
70 | - (NSString *)keyPath;
71 | - (id)object;
72 | - (id)userInfo;
73 | - (NSDictionary *)change;
74 | @end
75 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMSystemVersion.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMSystemVersion.h
3 | //
4 | // Copyright 2007-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 | #import "GTMDefines.h"
21 |
22 | // A class for getting information about what system we are running on
23 | @interface GTMSystemVersion : NSObject
24 |
25 | // Returns the current system version major.minor.bugFix
26 | + (void)getMajor:(SInt32*)major minor:(SInt32*)minor bugFix:(SInt32*)bugFix;
27 |
28 | // Returns the build number of the OS. Useful when looking for bug fixes
29 | // in new OSes which all have a set system version.
30 | // eg 10.5.5's build number is 9F33. Easy way to check the build number
31 | // is to choose "About this Mac" from the Apple menu and click on the version
32 | // number.
33 | + (NSString*)build;
34 |
35 | + (BOOL)isBuildLessThan:(NSString*)build;
36 | + (BOOL)isBuildLessThanOrEqualTo:(NSString*)build;
37 | + (BOOL)isBuildGreaterThan:(NSString*)build;
38 | + (BOOL)isBuildGreaterThanOrEqualTo:(NSString*)build;
39 | + (BOOL)isBuildEqualTo:(NSString *)build;
40 |
41 | #if GTM_MACOS_SDK
42 | // Returns YES if running on 10.3, NO otherwise.
43 | + (BOOL)isPanther;
44 |
45 | // Returns YES if running on 10.4, NO otherwise.
46 | + (BOOL)isTiger;
47 |
48 | // Returns YES if running on 10.5, NO otherwise.
49 | + (BOOL)isLeopard;
50 |
51 | // Returns YES if running on 10.6, NO otherwise.
52 | + (BOOL)isSnowLeopard;
53 |
54 | // Returns a YES/NO if the system is 10.3 or better
55 | + (BOOL)isPantherOrGreater;
56 |
57 | // Returns a YES/NO if the system is 10.4 or better
58 | + (BOOL)isTigerOrGreater;
59 |
60 | // Returns a YES/NO if the system is 10.5 or better
61 | + (BOOL)isLeopardOrGreater;
62 |
63 | // Returns a YES/NO if the system is 10.6 or better
64 | + (BOOL)isSnowLeopardOrGreater;
65 | #endif // GTM_MACOS_SDK
66 |
67 | // Returns one of the achitecture strings below. Note that this is the
68 | // architecture that we are currently running as, not the hardware architecture.
69 | + (NSString *)runtimeArchitecture;
70 | @end
71 |
72 | // Architecture Strings
73 | // TODO: Should probably break iPhone up into iPhone_ARM and iPhone_Simulator
74 | // but haven't found a need yet.
75 | GTM_EXTERN NSString *const kGTMArch_iPhone;
76 | GTM_EXTERN NSString *const kGTMArch_ppc;
77 | GTM_EXTERN NSString *const kGTMArch_ppc64;
78 | GTM_EXTERN NSString *const kGTMArch_x86_64;
79 | GTM_EXTERN NSString *const kGTMArch_i386;
80 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMSignalHandler.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMSignalHandler.h
3 | //
4 | // Copyright 2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 | #import "GTMDefines.h"
21 |
22 | // GTMSignalHandler.
23 | //
24 | // This is a very simple, easy-to-use class for registering handlers that get
25 | // called when a specific signal is delivered. Also handy for ignoring
26 | // inconvenient signals. Ignoring SIGKILL is not support for what should be
27 | // obvious reasons. You can pass nil for target & action to ignore the signal.
28 | //
29 | // Example of how to catch SIGABRT and SIGTERM while ignring SIGWINCH:
30 | // GTMSignalHandler *abrt, *term, *winch;
31 | // abrt = [[GTMSignalHandler alloc]
32 | // initWithSignal:SIGABRT
33 | // target:self
34 | // action:@selector(handleAbort:)];
35 | //
36 | // term = [[GTMSignalHandler alloc]
37 | // initWithSignal:SIGTERM
38 | // target:self
39 | // action:@selector(handleTerm:)];
40 | //
41 | // winch = [[GTMSignalHandler alloc] initWithSignal:SIGWINCH
42 | // initWithSignal:SIGWINCH
43 | // target:nil
44 | // action:NULL
45 | //
46 | // -(void)handleTerm:(int)signo {
47 | // .. do stuff ..
48 | // }
49 | //
50 | // Release the handler when you're no longer interested in handling that signal.
51 | // Note that signal(SIG_IGN, signo) is performed on each signal handled by
52 | // objects of this class, and those do not get un-done.
53 | //
54 | // Multiple handlers for the same signal is NOT supported.
55 | //
56 | // kqueue() is used to handle the signals, and the default runloop for the first
57 | // signal handler is used for signal delivery, so keep that in mind when you're
58 | // using this class. This class explicitly does not handle arbitrary runloops
59 | // and threading.
60 | //
61 | @interface GTMSignalHandler : NSObject {
62 | @private
63 | int signo_;
64 | GTM_WEAK id target_;
65 | SEL action_;
66 | }
67 |
68 | // Returns a retained signal handler object that will invoke |handler| on the
69 | // |target| whenever a signal of number |signo| is delivered to the process.
70 | -(id)initWithSignal:(int)signo
71 | target:(id)target
72 | action:(SEL)action;
73 |
74 | // Invalidates the handler so that it isn't listening anymore.
75 | - (void)invalidate;
76 |
77 | @end
78 |
--------------------------------------------------------------------------------
/GoldenPassport/OTPAuth/OTPGenerator.h:
--------------------------------------------------------------------------------
1 | //
2 | // OTPGenerator.h
3 | //
4 | // Copyright 2011 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 |
21 | // The OTPGenerator class generates a one-time password (OTP) using
22 | // the HMAC-Based One-Time Password Algorithm described in RFC4226:
23 | // http://tools.ietf.org/html/rfc4226
24 | //
25 | // The HOTP algorithm is based on an increasing counter value and a
26 | // static symmetric key known only to the token and the validation
27 | // service. In order to create the HOTP value, we will use the HMAC-
28 | // SHA-1 algorithm, as defined in RFC 2104.
29 | //
30 | // As the output of the HMAC-SHA-1 calculation is 160 bits, we must
31 | // truncate this value to something that can be easily entered by a
32 | // user.
33 | //
34 | // HOTP(K,C) = Truncate(HMAC-SHA-1(K,C))
35 | //
36 | // Where:
37 | //
38 | // - Truncate represents the function that converts an HMAC-SHA-1
39 | // value into an HOTP value as defined in Section 5.3 of RFC4226.
40 | //
41 | // The Key (K), the Counter (C), and Data values are hashed high-order
42 | // byte first.
43 | //
44 | // The HOTP values generated by the HOTP generator are treated as big
45 | // endian.
46 | @interface OTPGenerator : NSObject
47 |
48 | @property (readonly, nonatomic, copy) NSString *algorithm;
49 | @property (readonly, nonatomic, copy) NSData *secret;
50 | @property (readonly, nonatomic) NSUInteger digits;
51 |
52 | // Some default values.
53 | + (NSString *)defaultAlgorithm;
54 | + (NSUInteger)defaultDigits;
55 |
56 | // Designated initializer.
57 | - (id)initWithSecret:(NSData *)secret
58 | algorithm:(NSString *)algorithm
59 | digits:(NSUInteger)digits;
60 |
61 |
62 | // Instance method to generate an OTP using the |algorithm|, |secret|,
63 | // |counter| and |digits| values configured on the object.
64 | // The return value is an NSString of |digits| length, with leading
65 | // zero-padding as required.
66 | - (NSString *)generateOTPForCounter:(uint64_t)counter;
67 |
68 |
69 | // Instance method to generate an OTP using the |algorithm|, |secret|,
70 | // |counter| and |digits| values configured on the object.
71 | // The return value is an NSString of |digits| length, with leading
72 | // zero-padding as required.
73 | - (NSString *)generateOTP;
74 |
75 | @end
76 |
77 | extern NSString *const kOTPGeneratorSHA1Algorithm;
78 | extern NSString *const kOTPGeneratorSHA256Algorithm;
79 | extern NSString *const kOTPGeneratorSHA512Algorithm;
80 | extern NSString *const kOTPGeneratorSHAMD5Algorithm;
81 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSDictionary+URLArguments.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSDictionary+URLArguments.m
3 | //
4 | // Copyright 2006-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMNSDictionary+URLArguments.h"
20 | #import "GTMNSString+URLArguments.h"
21 | #import "GTMMethodCheck.h"
22 | #import "GTMDefines.h"
23 |
24 |
25 | // Export a nonsense symbol to suppress a libtool warning when this is linked alone in a static lib.
26 | __attribute__((visibility("default")))
27 | char GTMNSDictionaryURLArgumentsExportToSuppressLibToolWarning = 0;
28 |
29 |
30 | @implementation NSDictionary (GTMNSDictionaryURLArgumentsAdditions)
31 |
32 | GTM_METHOD_CHECK(NSString, gtm_stringByEscapingForURLArgument);
33 | GTM_METHOD_CHECK(NSString, gtm_stringByUnescapingFromURLArgument);
34 |
35 | + (NSDictionary *)gtm_dictionaryWithHttpArgumentsString:(NSString *)argString {
36 | NSMutableDictionary* ret = [NSMutableDictionary dictionary];
37 | NSArray* components = [argString componentsSeparatedByString:@"&"];
38 | NSString* component;
39 | // Use reverse order so that the first occurrence of a key replaces
40 | // those subsequent.
41 | for (component in [components reverseObjectEnumerator]) {
42 | if ([component length] == 0)
43 | continue;
44 | NSRange pos = [component rangeOfString:@"="];
45 | NSString *key;
46 | NSString *val;
47 | if (pos.location == NSNotFound) {
48 | key = [component gtm_stringByUnescapingFromURLArgument];
49 | val = @"";
50 | } else {
51 | key = [[component substringToIndex:pos.location]
52 | gtm_stringByUnescapingFromURLArgument];
53 | val = [[component substringFromIndex:pos.location + pos.length]
54 | gtm_stringByUnescapingFromURLArgument];
55 | }
56 | // gtm_stringByUnescapingFromURLArgument returns nil on invalid UTF8
57 | // and NSMutableDictionary raises an exception when passed nil values.
58 | if (!key) key = @"";
59 | if (!val) val = @"";
60 | [ret setObject:val forKey:key];
61 | }
62 | return ret;
63 | }
64 |
65 | - (NSString *)gtm_httpArgumentsString {
66 | NSMutableArray* arguments = [NSMutableArray arrayWithCapacity:[self count]];
67 | NSString* key;
68 | for (key in self) {
69 | [arguments addObject:[NSString stringWithFormat:@"%@=%@",
70 | [key gtm_stringByEscapingForURLArgument],
71 | [[[self objectForKey:key] description] gtm_stringByEscapingForURLArgument]]];
72 | }
73 |
74 | return [arguments componentsJoinedByString:@"&"];
75 | }
76 |
77 | @end
78 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMURLBuilder.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMURLBuilder.h
3 | //
4 | // Copyright 2012 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations
16 | // under the License.
17 | //
18 |
19 | //
20 | // Class for creating URLs. It handles URL encoding of parameters.
21 | //
22 | // Usage example:
23 | //
24 | // GTMURLBuilder *URLBuilder =
25 | // [GTMURLBuilder builderWithString:@"http://www.google.com"];
26 | // [URLBuilder setValue:@"abc" forParameter:@"q"];
27 | // NSURL *URL = [URLBuilder URL];
28 | //
29 | // NOTE: Apps targeting iOS 8 or OS X 10.10 and later should use
30 | // NSURLComponents and NSURLQueryItem to create URLs with
31 | // query arguments instead of using this class.
32 |
33 |
34 | #import
35 | #import "GTMDefines.h"
36 |
37 | #if (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10) \
38 | || (TARGET_OS_IPHONE && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0)
39 | __deprecated_msg("GTMURLBuilder is obsolete; update your app to use NSURLComponents queryItems property instead.")
40 | #endif
41 | @interface GTMURLBuilder : NSObject {
42 | @private
43 | NSMutableDictionary *params_;
44 | }
45 |
46 | @property(nonatomic, readonly) NSString *baseURLString;
47 |
48 | // |URLString| is expected to be a valid URL with already escaped parameter
49 | // values.
50 | + (GTMURLBuilder *)builderWithString:(NSString *)URLString;
51 | + (GTMURLBuilder *)builderWithURL:(NSURL *)URL;
52 |
53 | // |URLString| The base URL to which parameters will be appended.
54 | // If the URL already contains parameters, they should already be encoded.
55 | - (id)initWithString:(NSString *)URLString;
56 | - (void)setValue:(NSString *)value forParameter:(NSString *)parameter;
57 | - (void)setIntegerValue:(NSInteger)value forParameter:(NSString *)parameter;
58 | - (NSString *)valueForParameter:(NSString *)parameter;
59 | // Returns 0 if there is no value for |parameter| or if the value cannot
60 | // be parsed into an NSInteger. Use valueForParameter if you want to make
61 | // sure that the value is set before attempting the parsing.
62 | - (NSInteger)integerValueForParameter:(NSString *)parameter;
63 | - (void)removeParameter:(NSString *)parameter;
64 | - (void)setParameters:(NSDictionary *)parameters;
65 | - (NSDictionary *)parameters;
66 | - (NSURL *)URL;
67 | - (NSString *)URLString;
68 |
69 | // Case-sensitive comparison of the URL. Also protocol and host are compared
70 | // as case-sensitive strings. The order of URL parameters is ignored.
71 | - (BOOL)isEqual:(GTMURLBuilder *)URLBuilder;
72 |
73 | @end
74 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSScanner+JSON.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSScanner+JSON.m
3 | //
4 | // Copyright 2009 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMDefines.h"
20 | #import "GTMNSScanner+JSON.h"
21 |
22 | // Export a nonsense symbol to suppress a libtool warning when this is linked
23 | // alone in a static lib.
24 | __attribute__((visibility("default")))
25 | char NSScanner_GTMNSScannerJSONAdditionsExportToSuppressLibToolWarning = 0;
26 |
27 | @implementation NSScanner (GTMNSScannerJSONAdditions)
28 |
29 | - (BOOL)gtm_scanJSONString:(NSString **)jsonString
30 | startChar:(unichar)startChar
31 | endChar:(unichar)endChar {
32 | BOOL isGood = NO;
33 | NSRange jsonRange = { NSNotFound, 0 };
34 | NSString *scanString = [self string];
35 | NSUInteger startLocation = [self scanLocation];
36 | NSUInteger length = [scanString length];
37 | NSUInteger blockOpen = 0;
38 | NSCharacterSet *charsToSkip = [self charactersToBeSkipped];
39 | BOOL inQuoteMode = NO;
40 | NSUInteger i;
41 | for (i = startLocation; i < length; ++i) {
42 | unichar jsonChar = [scanString characterAtIndex:i];
43 | if (jsonChar == startChar && !inQuoteMode) {
44 | if (blockOpen == 0) {
45 | jsonRange.location = i;
46 | }
47 | blockOpen += 1;
48 | } else if (blockOpen == 0) {
49 | // If we haven't opened our block skip over any characters in
50 | // charsToSkip.
51 | if (![charsToSkip characterIsMember:jsonChar]) {
52 | break;
53 | }
54 | } else if (jsonChar == endChar && !inQuoteMode) {
55 | blockOpen -= 1;
56 | if (blockOpen == 0) {
57 | i += 1; // Move onto next character
58 | jsonRange.length = i - jsonRange.location;
59 | break;
60 | }
61 | } else {
62 | if (jsonChar == '"') {
63 | inQuoteMode = !inQuoteMode;
64 | } else if (inQuoteMode && jsonChar == '\\') {
65 | // Skip the escaped character if it isn't the last one
66 | if (i < length - 1) ++i;
67 | }
68 | }
69 | }
70 | [self setScanLocation:i];
71 | if (blockOpen == 0 && jsonRange.location != NSNotFound) {
72 | isGood = YES;
73 | if (jsonString) {
74 | *jsonString = [scanString substringWithRange:jsonRange];
75 | }
76 | }
77 | return isGood;
78 | }
79 |
80 | - (BOOL)gtm_scanJSONObjectString:(NSString **)jsonString {
81 | return [self gtm_scanJSONString:jsonString startChar:'{' endChar:'}'];
82 | }
83 |
84 | - (BOOL)gtm_scanJSONArrayString:(NSString**)jsonString {
85 | return [self gtm_scanJSONString:jsonString startChar:'[' endChar:']'];
86 | }
87 |
88 | @end
89 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMServiceManagement.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMServiceManagement.h
3 | //
4 | // Copyright 2010 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #include "GTMDefines.h"
20 |
21 | #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
22 |
23 | #include
24 | #include
25 |
26 | GTM_EXTERN_C_BEGIN
27 |
28 | // Done in C as opposed to Objective-C as lots of services may not want
29 | // to bring in Obj-C libraries.
30 |
31 | // For rough documentation on these methods please see
32 | // from the 10.6 sdk.
33 | // This reimplements some of the ServiceManagement framework on 10.5.
34 | // Caller takes ownership of error if necessary.
35 |
36 | Boolean GTMSMJobSubmit(CFDictionaryRef job, CFErrorRef *error);
37 | Boolean GTMSMJobRemove(CFStringRef jobLabel, CFErrorRef *error);
38 |
39 | // Caller takes ownership of the returned type.
40 | // Note that the dictionary returned will have 0 for machports.
41 | // To get a machport, use bootstrap_look_up, or NSMachBootstrapServer.
42 | CFDictionaryRef GTMSMJobCopyDictionary(CFStringRef jobLabel);
43 |
44 | // This one is conspiciously absent from the ServiceManagement framework.
45 | // Performs a check-in for the running process and returns its dictionary with
46 | // the appropriate sockets and machports filled in.
47 | // Caller takes ownership of the returned type.
48 | CFDictionaryRef GTMSMCopyJobCheckInDictionary(CFErrorRef *error);
49 |
50 | // The official ServiceManagement version returns an array of job dictionaries.
51 | // This returns a dictionary of job dictionaries where the key is the label
52 | // of the job, and the value is the dictionary for the job of that label.
53 | // Caller takes ownership of the returned type.
54 | CFDictionaryRef GTMSMCopyAllJobDictionaries(void);
55 |
56 |
57 | // Convert a CFType (and any of it's subitems) into a launch_data_t.
58 | // Caller takes ownership of the returned type if it isn't added to a launch
59 | // data container type.
60 | launch_data_t GTMLaunchDataCreateFromCFType(CFTypeRef cf_type_ref,
61 | CFErrorRef *error);
62 |
63 | // Convert a launch_data_t (and any of it's subitems) into a CFType.
64 | // If |convert_non_standard_objects| is true, file descriptors and machports
65 | // will be included in the returned dictionary, otherwise they will be ignored.
66 | // Caller is takes ownership of the returned type.
67 | CFTypeRef GTMCFTypeCreateFromLaunchData(launch_data_t ldata,
68 | bool convert_non_standard_objects,
69 | CFErrorRef *error);
70 |
71 | GTM_EXTERN_C_END
72 |
73 | #endif // if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
74 |
--------------------------------------------------------------------------------
/GoldenPassport/KeyCode.swift:
--------------------------------------------------------------------------------
1 | //
2 | // KeyCode.swift
3 | // GoldenPassport
4 | //
5 | // Created by StanZhai on 2017/2/28.
6 | // Copyright © 2017年 StanZhai. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | enum KeyCode: CGKeyCode {
12 | case a = 0
13 | case s = 1
14 | case d = 2
15 | case f = 3
16 | case h = 4
17 | case g = 5
18 | case z = 6
19 | case x = 7
20 | case c = 8
21 | case v = 9
22 | case b = 11
23 | case q = 12
24 | case w = 13
25 | case e = 14
26 | case r = 15
27 | case y = 16
28 | case t = 17
29 | case one = 18
30 | case two = 19
31 | case three = 20
32 | case four = 21
33 | case six = 22
34 | case five = 23
35 | case equal = 24 // =
36 | case nine = 25
37 | case seven = 26
38 | case dash = 27 // -
39 | case eight = 28
40 | case zero = 29
41 | case squareBracketClose = 30 // ]
42 | case o = 31
43 | case u = 32
44 | case squareBracketOpen = 33 // [
45 | case i = 34
46 | case p = 35
47 | case return36 = 36
48 | case l = 37
49 | case j = 38
50 | case singleQuote = 39 // '
51 | case k = 40
52 | case semicolon = 41 // ;
53 | case forwardSlash = 42 // \
54 | case comma = 43 // ,
55 | case backslash = 44 // /
56 | case n = 45
57 | case m = 46
58 | case period = 47 // .
59 | case tab = 48
60 | case space = 49
61 | case tick = 50 // `
62 | case delete = 51
63 | case enter = 52
64 | case escape = 53
65 | case period65 = 65 // .
66 | case asterisk = 67 // *
67 | case plus = 69 // +
68 | case clear = 71
69 | case backslash75 = 75 // /
70 | case enter76 = 76
71 | case equal78 = 78
72 | case equal81 = 81
73 | case zero82 = 82
74 | case one83 = 83
75 | case two84 = 84
76 | case three85 = 85
77 | case four86 = 86
78 | case five87 = 87
79 | case six88 = 88
80 | case seven89 = 89
81 | case eight91 = 91
82 | case nine92 = 92
83 | case f5 = 96
84 | case f6 = 97
85 | case f7 = 98
86 | case f3 = 99
87 | case f8 = 100
88 | case f9 = 101
89 | case f11 = 103
90 | case f13 = 105
91 | case f14 = 107
92 | case f10 = 109
93 | case f12 = 111
94 | case f15 = 113
95 | case help = 114
96 | case home = 115
97 | case pgup = 116
98 | case delete117 = 117
99 | case f4 = 118
100 | case end = 119
101 | case f2 = 120
102 | case pgdn = 121
103 | case f1 = 122
104 | case left = 123
105 | case right = 124
106 | case down = 125
107 | case up = 126
108 |
109 | static func enumWith(_ char: Character) -> KeyCode? {
110 | if let num = Int(String(char)) {
111 | if num == 0 {
112 | return KeyCode(rawValue: CGKeyCode(29))
113 | }
114 | if num <= 9 && num > 0 {
115 | return KeyCode(rawValue: CGKeyCode(17 + num))
116 | }
117 | }
118 |
119 | var i = 126
120 | repeat {
121 | if let item = KeyCode(rawValue: CGKeyCode(i)) {
122 | if String(describing: item) == String(char) { return item }
123 | }
124 | i -= 1
125 | } while i >= 0
126 |
127 | return nil
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMFileSystemKQueue.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMFileSystemKQueue.h
3 | //
4 | // Copyright 2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 | #import "GTMDefines.h"
21 |
22 | #import // for kqueue() and kevent and the NOTE_* constants
23 |
24 | // Event constants
25 | enum {
26 | kGTMFileSystemKQueueDeleteEvent = NOTE_DELETE,
27 | kGTMFileSystemKQueueWriteEvent = NOTE_WRITE,
28 | kGTMFileSystemKQueueExtendEvent = NOTE_EXTEND,
29 | kGTMFileSystemKQueueAttributeChangeEvent = NOTE_ATTRIB,
30 | kGTMFileSystemKQueueLinkChangeEvent = NOTE_LINK,
31 | kGTMFileSystemKQueueRenameEvent = NOTE_RENAME,
32 | kGTMFileSystemKQueueRevokeEvent = NOTE_REVOKE,
33 | kGTMFileSystemKQueueAllEvents = NOTE_DELETE | NOTE_WRITE | NOTE_EXTEND |
34 | NOTE_ATTRIB | NOTE_LINK | NOTE_RENAME |
35 | NOTE_REVOKE,
36 | };
37 | typedef unsigned int GTMFileSystemKQueueEvents;
38 |
39 | // GTMFileSystemKQueue.
40 | //
41 | // This is a very simple, easy-to-use class for registering handlers that get
42 | // called when a events happen to a given file system path.
43 | //
44 | // The default runloop for the first path kqueued is used for notification
45 | // delivery, so keep that in mind when you're using this class. This class
46 | // explicitly does not handle arbitrary runloops and threading.
47 | //
48 | @interface GTMFileSystemKQueue : NSObject {
49 | @private
50 | NSString *path_;
51 | int fd_;
52 | GTMFileSystemKQueueEvents events_;
53 | BOOL acrossReplace_;
54 | GTM_WEAK id target_;
55 | SEL action_;
56 | }
57 |
58 | // |path| is the full path to monitor. |events| is a combination of events
59 | // listed above that you want notification of. |acrossReplace| will cause this
60 | // object to reattach when a the file is deleted & recreated or moved out of the
61 | // way and a new one put in place. |selector| should be of the signature:
62 | // - (void)fileSystemKQueue:(GTMFileSystemKQueue *)fskq
63 | // events:(GTMFileSystemKQueueEvents)events;
64 | // where the events can be one or more of the events listed above ORed together.
65 | //
66 | // NOTE: |acrossReplace| is not fool proof. If the file is renamed/deleted,
67 | // then the object will make one attempt at the time it gets the rename/delete
68 | // to reopen the file. If the new file has not been created, no more action is
69 | // taken. To handle the file coming into existance later, you need to monitor
70 | // the directory in some other way.
71 | - (id)initWithPath:(NSString *)path
72 | forEvents:(GTMFileSystemKQueueEvents)events
73 | acrossReplace:(BOOL)acrossReplace
74 | target:(id)target
75 | action:(SEL)action;
76 |
77 | - (NSString *)path;
78 |
79 | @end
80 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMStackTrace.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMStackTrace.h
3 | //
4 | // Copyright 2007-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 | #import "GTMDefines.h"
21 |
22 | #ifdef __cplusplus
23 | extern "C" {
24 | #endif
25 |
26 | struct GTMAddressDescriptor {
27 | const void *address; // address
28 | const char *symbol; // nearest symbol to address
29 | const char *class_name; // if it is an obj-c method, the method's class
30 | BOOL is_class_method; // if it is an obj-c method, type of method
31 | const char *filename; // file that the method came from.
32 | };
33 |
34 | // Returns a string containing a nicely formatted stack trace.
35 | //
36 | // This function gets the stack trace for the current thread. It will
37 | // be from the caller of GTMStackTrace upwards to the top the calling stack.
38 | // Typically this function will be used along with some logging,
39 | // as in the following:
40 | //
41 | // MyAppLogger(@"Should never get here:\n%@", GTMStackTrace());
42 | //
43 | // Here is a sample stack trace returned from this function:
44 | //
45 | // #0 0x00002d92 D () [/Users/me/./StackLog]
46 | // #1 0x00002e45 C () [/Users/me/./StackLog]
47 | // #2 0x00002e53 B () [/Users/me/./StackLog]
48 | // #3 0x00002e61 A () [/Users/me/./StackLog]
49 | // #4 0x00002e6f main () [/Users/me/./StackLog]
50 | // #5 0x00002692 tart () [/Users/me/./StackLog]
51 | // #6 0x000025b9 tart () [/Users/me/./StackLog]
52 | //
53 |
54 | NSString *GTMStackTrace(void);
55 |
56 | // Returns a string containing a nicely formatted stack trace from the
57 | // exception. Only available on 10.5 or later, uses
58 | // -[NSException callStackReturnAddresses].
59 | //
60 | NSString *GTMStackTraceFromException(NSException *e);
61 |
62 | // Returns an array of GTMAddressDescriptors from the current thread's stack.
63 | // *** You should probably use GTMStackTrace() instead of this function ***
64 | // However, if you actually want all the PCs with symbols, this is the way
65 | // to get them. There is no memory allocations done, so no clean up is required
66 | // except for the caller to free outDescs if they allocated it themselves.
67 | // This will include PCs of GTMStaceTrace and its inner utility functions that
68 | // you may want to strip out.
69 | //
70 | // Args:
71 | // outDescs - an array of "struct GTMAddressDescriptor" pointers corresponding
72 | // to the program counters found on the current thread's stack.
73 | // count - the number of entries in the outDescs array
74 | //
75 | // Returns:
76 | // The number of program counters actually added to outPcs.
77 | //
78 | NSUInteger GTMGetStackAddressDescriptors(struct GTMAddressDescriptor outDescs[],
79 | NSUInteger count);
80 |
81 | #ifdef __cplusplus
82 | }
83 | #endif
84 |
--------------------------------------------------------------------------------
/GoldenPassport/OTPAuth/OTPAuthURL.h:
--------------------------------------------------------------------------------
1 | //
2 | // OTPAuthURL.h
3 | //
4 | // Copyright 2011 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 |
21 | @class OTPGenerator;
22 |
23 | // This class encapsulates the parsing of otpauth:// urls, the creation of
24 | // either HOTPGenerator or TOTPGenerator objects, and the persistence of the
25 | // objects state to the iPhone keychain in a secure fashion.
26 | //
27 | // The secret key is stored as the "password" in the keychain item, and the
28 | // re-constructed URL is stored in an attribute.
29 | @interface OTPAuthURL : NSObject
30 |
31 | // |name| is an arbitrary UTF8 text string extracted from the url path.
32 | @property(readwrite, copy, nonatomic) NSString *name;
33 | @property(readonly, nonatomic) NSString *otpCode;
34 | @property(readonly, nonatomic) NSString *checkCode;
35 | @property(readonly, retain, nonatomic) NSData *keychainItemRef;
36 |
37 | // Standard base32 alphabet.
38 | // Input is case insensitive.
39 | // No padding is used.
40 | // Ignore space and hyphen (-).
41 | // For details on use, see android app:
42 | // http://google3/security/strongauth/mobile/android/StrongAuth/src/org/strongauth/Base32String.java
43 | + (NSData *)base32Decode:(NSString *)string;
44 | + (NSString *)encodeBase32:(NSData *)data;
45 |
46 | + (OTPAuthURL *)authURLWithURL:(NSURL *)url
47 | secret:(NSData *)secret;
48 | + (OTPAuthURL *)authURLWithKeychainItemRef:(NSData *)keychainItemRef;
49 |
50 | // Returns a reconstructed NSURL object representing the current state of the
51 | // |generator|.
52 | - (NSURL *)url;
53 |
54 | // Saves the current object state to the keychain.
55 | - (BOOL)saveToKeychain;
56 |
57 | // Removes the current object state from the keychain.
58 | - (BOOL)removeFromKeychain;
59 |
60 | // Returns true if the object was loaded from or subsequently added to the
61 | // iPhone keychain.
62 | // It does not assert that the keychain is up to date with the latest
63 | // |generator| state.
64 | - (BOOL)isInKeychain;
65 |
66 | - (NSString*)checkCode;
67 |
68 | @end
69 |
70 | @interface TOTPAuthURL : OTPAuthURL {
71 | @private
72 | NSTimeInterval generationAdvanceWarning_;
73 | NSTimeInterval lastProgress_;
74 | BOOL warningSent_;
75 | }
76 |
77 | @property(readwrite, assign, nonatomic) NSTimeInterval generationAdvanceWarning;
78 |
79 | - (id)initWithSecret:(NSData *)secret name:(NSString *)name;
80 |
81 | @end
82 |
83 | @interface HOTPAuthURL : OTPAuthURL {
84 | @private
85 | NSString *otpCode_;
86 | }
87 | - (id)initWithSecret:(NSData *)secret name:(NSString *)name;
88 | - (void)generateNextOTPCode;
89 | @end
90 |
91 | // Notification sent out |otpGenerationAdvanceWarning_| before a new OTP is
92 | // generated. Only applies to TOTP Generators. Has a
93 | // |OTPAuthURLSecondsBeforeNewOTPKey| key which is a NSNumber with the
94 | // number of seconds remaining before the new OTP is generated.
95 | extern NSString *const OTPAuthURLWillGenerateNewOTPWarningNotification;
96 | extern NSString *const OTPAuthURLSecondsBeforeNewOTPKey;
97 | extern NSString *const OTPAuthURLDidGenerateNewOTPNotification;
98 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMLocalizedString.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMLocalizedString.h
3 | //
4 | // Copyright (c) 2010 Google Inc. All rights reserved.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 | #import "GTMDefines.h"
21 |
22 | // The NSLocalizedString macros do not have NS_FORMAT_ARGUMENT modifiers put
23 | // on them which means you get warnings on Snow Leopard with when
24 | // GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES and you do things like:
25 | // NSString *foo
26 | // = [NSString stringWithFormat:NSLocalizedString(@"blah %@", nil), @"bar"];
27 | // The GTMLocalizedString functions fix that for you so you can do:
28 | // NSString *foo
29 | // = [NSString stringWithFormat:GTMLocalizedString(@"blah %@", nil), @"bar"];
30 | // and you will compile cleanly.
31 | // If you use genstrings you can call it with
32 | // genstrings -s GTMLocalizedString ...
33 | // and it should work as expected.
34 | // You can override how GTM gets its localized strings (if you are using
35 | // something other than NSLocalizedString) by redefining
36 | // GTMLocalizedStringWithDefaultValueInternal.
37 |
38 | #ifndef GTMLocalizedStringWithDefaultValueInternal
39 | #define GTMLocalizedStringWithDefaultValueInternal \
40 | NSLocalizedStringWithDefaultValue
41 | #endif
42 |
43 | GTM_INLINE NS_FORMAT_ARGUMENT(1) NSString *GTMLocalizedString(
44 | NSString *key, NSString *comment) {
45 | return GTMLocalizedStringWithDefaultValueInternal(key,
46 | nil,
47 | [NSBundle mainBundle],
48 | @"",
49 | comment);
50 | }
51 |
52 | GTM_INLINE NS_FORMAT_ARGUMENT(1) NSString *GTMLocalizedStringFromTable(
53 | NSString *key, NSString *tableName, NSString *comment) {
54 | return GTMLocalizedStringWithDefaultValueInternal(key,
55 | tableName,
56 | [NSBundle mainBundle],
57 | @"",
58 | comment);
59 | }
60 |
61 | GTM_INLINE NS_FORMAT_ARGUMENT(1) NSString *GTMLocalizedStringFromTableInBundle(
62 | NSString *key, NSString *tableName, NSBundle *bundle, NSString *comment) {
63 | return GTMLocalizedStringWithDefaultValueInternal(key,
64 | tableName,
65 | bundle,
66 | @"",
67 | comment);
68 | }
69 |
70 | GTM_INLINE NS_FORMAT_ARGUMENT(1) NSString *GTMLocalizedStringWithDefaultValue(
71 | NSString *key, NSString *tableName, NSBundle *bundle, NSString *value,
72 | NSString *comment) {
73 | return GTMLocalizedStringWithDefaultValueInternal(key,
74 | tableName,
75 | bundle,
76 | value,
77 | comment);
78 | }
79 |
80 |
--------------------------------------------------------------------------------
/GoldenPassport/AddVerifyKeyWindow.swift:
--------------------------------------------------------------------------------
1 | //
2 | // AddVerifyKeyController.swift
3 | // GoldenPassport
4 | //
5 | // Created by StanZhai on 2017/2/25.
6 | // Copyright © 2017年 StanZhai. All rights reserved.
7 | //
8 |
9 | import Cocoa
10 | import CoreImage
11 |
12 | class AddVerifyKeyWindow: NSWindowController, NSWindowDelegate {
13 | @IBOutlet weak var otpTextField: NSTextField!
14 | @IBOutlet weak var tagTextField: NSTextField!
15 |
16 | override var windowNibName : String! {
17 | return "AddVerifyKeyWindow"
18 | }
19 |
20 | override func windowDidLoad() {
21 | super.windowDidLoad()
22 | self.window?.isOpaque = false
23 | //self.window?.titlebarAppearsTransparent = true
24 | //self.window?.styleMask = [window!.styleMask, .fullSizeContentView]
25 | let color = NSColor(calibratedRed: 0.0, green: 0.0, blue: 0.0, alpha: 0.75)
26 | //self.window?.backgroundColor = color
27 | self.window?.isMovableByWindowBackground = true
28 | self.window?.center()
29 | }
30 |
31 | func clearTextField() {
32 | otpTextField.stringValue = ""
33 | tagTextField.stringValue = ""
34 | }
35 |
36 | @IBAction func selectPicClicked(_ sender: NSButton) {
37 | let openPanel = NSOpenPanel()
38 | openPanel.allowedFileTypes = NSImage.imageTypes
39 | openPanel.allowsMultipleSelection = false
40 | openPanel.canChooseDirectories = false
41 | openPanel.canCreateDirectories = false
42 | openPanel.canChooseFiles = true
43 |
44 | let i = openPanel.runModal()
45 | if i == NSApplication.ModalResponse.cancel {
46 | return
47 | }
48 |
49 | let ciImage = CIImage(contentsOf: openPanel.url!)
50 | let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyLow])
51 | let results = detector?.features(in: ciImage!)
52 | if (results?.count)! > 0 {
53 | let qrFeature = results?.last as! CIQRCodeFeature
54 | let data = qrFeature.messageString
55 | otpTextField.stringValue = data!
56 |
57 | let otpInfo = OTPAuthURLParser(data!)!
58 | if (otpInfo.user != nil) {
59 | tagTextField.stringValue = otpInfo.user! + "@" + otpInfo.host
60 | } else {
61 | tagTextField.stringValue = otpInfo.host
62 | }
63 |
64 | }
65 | }
66 |
67 | @IBAction func okBtnClicked(_ sender: NSButton) {
68 | let url = otpTextField.stringValue
69 | let tag = tagTextField.stringValue
70 |
71 | let alert: NSAlert = NSAlert()
72 | alert.addButton(withTitle: "确定")
73 | alert.alertStyle = NSAlert.Style.informational
74 |
75 | var isValid = false
76 | if let otpInfo = OTPAuthURLParser(url) {
77 | isValid = OTPAuthURL.base32Decode(otpInfo.secret) != nil
78 | }
79 |
80 | if isValid {
81 | DataManager.shared.addOTPAuthURL(tag: tag, url: url)
82 |
83 | let notificationCenter = NotificationCenter.default
84 | notificationCenter.post(name: NSNotification.Name(rawValue: "VerifyKeyAdded"), object: nil)
85 | self.window?.close()
86 |
87 | alert.messageText = "添加成功,请到状态栏菜单查看。"
88 | } else {
89 | alert.messageText = "无法解析密钥,请检查OTPAuth URL。"
90 | alert.alertStyle = NSAlert.Style.warning
91 | }
92 |
93 | alert.runModal()
94 | }
95 |
96 | @IBAction func cancelBtnClicked(_ sender: NSButton) {
97 | self.window?.close()
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMLightweightProxy.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMLightweightProxy.m
3 | //
4 | // Copyright 2006-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMLightweightProxy.h"
20 | #import "GTMDefines.h"
21 |
22 | @implementation GTMLightweightProxy
23 |
24 | - (id)initWithRepresentedObject:(id)object {
25 | // it's weak, we don't retain
26 | representedObject_ = object;
27 | return self;
28 | }
29 |
30 | - (id)init {
31 | return [self initWithRepresentedObject:nil];
32 | }
33 |
34 | - (void)dealloc {
35 | // it's weak, we don't release
36 | representedObject_ = nil;
37 | [super dealloc];
38 | }
39 |
40 | - (id)representedObject {
41 | // Use a local variable to avoid a bogus compiler warning.
42 | id repObject = nil;
43 | @synchronized(self) {
44 | // Even though we don't retain this object, we hang it on the lifetime
45 | // of the calling threads pool so it's lifetime is safe for at least that
46 | // long.
47 | repObject = [representedObject_ retain];
48 | }
49 | return [repObject autorelease];
50 | }
51 |
52 | - (void)setRepresentedObject:(id)object {
53 | @synchronized(self) {
54 | representedObject_ = object;
55 | }
56 | }
57 |
58 | // Passes any unhandled method to the represented object if it responds to that
59 | // method.
60 | - (void)forwardInvocation:(NSInvocation*)invocation {
61 | id target = [self representedObject];
62 | // Silently discard all messages when there's no represented object
63 | if (!target)
64 | return;
65 |
66 | SEL aSelector = [invocation selector];
67 | if ([target respondsToSelector:aSelector])
68 | [invocation invokeWithTarget:target];
69 | }
70 |
71 | // Gets the represented object's method signature for |selector|; necessary for
72 | // forwardInvocation.
73 | - (NSMethodSignature*)methodSignatureForSelector:(SEL)selector {
74 | id target = [self representedObject];
75 | if (target) {
76 | return [target methodSignatureForSelector:selector];
77 | } else {
78 | // Apple's underlying forwarding code crashes if we return nil here.
79 | // Since we are not going to use the invocation being constructed
80 | // if there's no representedObject, a random valid NSMethodSignature is fine.
81 | return [NSObject methodSignatureForSelector:@selector(alloc)];
82 | }
83 | }
84 |
85 | // Prevents exceptions from unknown selectors if there is no represented
86 | // object, and makes the exception come from the right place if there is one.
87 | - (void)doesNotRecognizeSelector:(SEL)selector {
88 | id target = [self representedObject];
89 | if (target)
90 | [target doesNotRecognizeSelector:selector];
91 | }
92 |
93 | // Checks the represented object's selectors to allow clients of the proxy to
94 | // do respondsToSelector: tests.
95 | - (BOOL)respondsToSelector:(SEL)selector {
96 | if ([super respondsToSelector:selector] ||
97 | selector == @selector(initWithRepresentedObject:) ||
98 | selector == @selector(representedObject) ||
99 | selector == @selector(setRepresentedObject:))
100 | {
101 | return YES;
102 | }
103 |
104 | id target = [self representedObject];
105 | return target && [target respondsToSelector:selector];
106 | }
107 |
108 | @end
109 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMLoggerRingBufferWriter.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMLoggerRingBufferWriter.h
3 | //
4 | // Copyright 2007-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMLogger.h"
20 | #import "GTMDefines.h"
21 |
22 | typedef struct GTMRingBufferPair GTMRingBufferPair;
23 |
24 | // GTMLoggerRingBufferWriter is a GTMLogWriter that accumulates logged Info
25 | // and Debug messages (when they're not compiled out in a release build)
26 | // into a ring buffer. If an Error or Assert message is
27 | // logged, all of the previously logged messages (up to the size of the
28 | // buffer) are then logged. At that point the buffer resets itself.
29 | //
30 | // How to use:
31 | //
32 | // * Create a logger writer that you want to use to do the ultimate writing,
33 | // such as to stdErr, or a log file, or an NSArray that aggregates other
34 | // writers.
35 | // id someWriter = ...
36 | //
37 | // * Make a new ring buffer with this writer, along with the buffer's
38 | // capacity (which must be >= 1):
39 | // rbw =
40 | // [GTMLoggerRingBufferWriter ringBufferWriterWithCapacity:32
41 | // writer:someWriter];
42 | //
43 | // * Set your logger's writer to be the ring buffer writer:
44 | // [[GTMLogger sharedLogger] setWriter:rbw];
45 | //
46 | // Note that this writer is at the end of the GTMLogger food chain, where the
47 | // default filter removes Info messages in Release mode (Debug messages are
48 | // compiled out). You can pass nil to GTMLogger's -setFilter to have it pass
49 | // along all the messages.
50 | //
51 | @interface GTMLoggerRingBufferWriter : NSObject {
52 | @private
53 | id writer_;
54 | GTMRingBufferPair *buffer_;
55 | NSUInteger capacity_;
56 | NSUInteger nextIndex_; // Index of the next element of |buffer_| to fill.
57 | NSUInteger totalLogged_; // This > 0 and |nextIndex_| == 0 means we've wrapped.
58 | }
59 |
60 | // Returns an autoreleased ring buffer writer. If |writer| is nil,
61 | // then nil is returned.
62 | + (id)ringBufferWriterWithCapacity:(NSUInteger)capacity
63 | writer:(id)loggerWriter;
64 |
65 | // Designated initializer. If |writer| is nil, then nil is returned.
66 | // If you just use -init, nil will be returned.
67 | - (id)initWithCapacity:(NSUInteger)capacity
68 | writer:(id)loggerWriter;
69 |
70 | // How many messages will be logged before older messages get dropped
71 | // on the floor.
72 | - (NSUInteger)capacity;
73 |
74 | // The log writer that will get the buffered log messages if/when they
75 | // need to be displayed.
76 | - (id)writer;
77 |
78 | // How many log messages are currently in the buffer.
79 | - (NSUInteger)count;
80 |
81 | // How many have been dropped on the floor since creation, or the last
82 | // reset.
83 | - (NSUInteger)droppedLogCount;
84 |
85 | // The total number of messages processed since creation, or the last
86 | // reset.
87 | - (NSUInteger)totalLogged;
88 |
89 | // Purge the contents and reset the counters.
90 | - (void)reset;
91 |
92 | // Print out the contents without resetting anything.
93 | // Contents are automatically printed and reset when an error-level
94 | // message comes through.
95 | - (void)dumpContents;
96 |
97 | @end // GTMLoggerRingBufferWriter
98 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSFileHandle+UniqueName.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSFileHandle+UniqueName.h
3 | //
4 | // Copyright 2010 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 | #import "GTMDefines.h"
21 |
22 | @interface NSFileHandle (GTMFileHandleUniqueNameAdditions)
23 |
24 | // Creates a read/write temporary file in NSTemporaryDirectory with mode 0600.
25 | // The template should be similar to the template passed to mkstemp.
26 | // If there is an extension on the nameTemplate it will remain. An example
27 | // template is "MyAppXXXXXX.txt".
28 | // If |path| is not nil, it will contain the derived path for the file.
29 | // The file descriptor wrapped by the NSFileHandle will be closed on dealloc.
30 | + (id)gtm_fileHandleForTemporaryFileBasedOn:(NSString *)nameTemplate
31 | finalPath:(NSString **)path;
32 |
33 | // Return an opened read/write file handle with mode 0600 based on a template.
34 | // The template should be similar to the template passed to mkstemp.
35 | // If there is an extension on the pathTemplate it will remain. An example
36 | // template is "/Applications/MyAppXXXXXX.txt".
37 | // If |path| is not nil, it will contain the derived path for the file.
38 | // The file descriptor wrapped by the NSFileHandle will be closed on dealloc.
39 | + (id)gtm_fileHandleWithUniqueNameBasedOn:(NSString *)pathTemplate
40 | finalPath:(NSString **)path;
41 |
42 | // Same as fileHandleWithUniqueNameBasedOn:finalName: but splits up the
43 | // template from the directory.
44 | + (id)gtm_fileHandleWithUniqueNameBasedOn:(NSString *)nameTemplate
45 | inDirectory:(NSString *)directory
46 | finalPath:(NSString **)path;
47 |
48 |
49 | // Same as fileHandleWithUniqueNameBasedOn:inDirectory:finalName: but finds
50 | // the directory using the |directory| and |mask| arguments.
51 | + (id)gtm_fileHandleWithUniqueNameBasedOn:(NSString *)nameTemplate
52 | inDirectory:(NSSearchPathDirectory)directory
53 | domainMask:(NSSearchPathDomainMask)mask
54 | finalPath:(NSString **)path;
55 | @end
56 |
57 | @interface NSFileManager (GTMFileManagerUniqueNameAdditions)
58 |
59 | // Creates a new directory in NSTemporaryDirectory with mode 0700.
60 | // The template should be similar to the template passed to mkdtemp.
61 | - (NSString *)gtm_createTemporaryDirectoryBasedOn:(NSString *)nameTemplate;
62 |
63 | // Return the path to a directory with mode 0700 based on a template.
64 | // The template should be similar to the template passed to mkdtemp.
65 | - (NSString *)gtm_createDirectoryWithUniqueNameBasedOn:(NSString *)nameTemplate;
66 |
67 | // Same as createDirectoryWithUniqueNameBasedOn: but splits up the
68 | // template from the directory.
69 | - (NSString *)gtm_createDirectoryWithUniqueNameBasedOn:(NSString *)pathTemplate
70 | inDirectory:(NSString *)directory;
71 |
72 | // Same as createDirectoryWithUniqueNameBasedOn:inDirectory: but finds
73 | // the directory using the |directory| and |mask| arguments.
74 | - (NSString *)gtm_createDirectoryWithUniqueNameBasedOn:(NSString *)pathTemplate
75 | inDirectory:(NSSearchPathDirectory)directory
76 | domainMask:(NSSearchPathDomainMask)mask;
77 | @end
78 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMSynchronizationAsserts.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMSyncAsserts.m
3 | //
4 | // Copyright 2016 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMSynchronizationAsserts.h"
20 |
21 | #if DEBUG
22 |
23 | @implementation GTMSyncMonitorInternal
24 |
25 | - (instancetype)initWithSynchronizationObject:(id)object
26 | allowRecursive:(BOOL)allowRecursive
27 | functionName:(const char *)functionName {
28 | self = [super init];
29 | if (self) {
30 | // In the thread's dictionary, we keep a counted set of the names
31 | // of functions that are synchronizing on the object.
32 | Class threadKey = [GTMSyncMonitorInternal class];
33 | _objectKey = [NSValue valueWithNonretainedObject:object];
34 | _functionName = functionName;
35 |
36 | NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary;
37 | NSMutableDictionary *counters = threadDict[threadKey];
38 | if (counters == nil) {
39 | counters = [NSMutableDictionary dictionary];
40 | threadDict[(id)threadKey] = counters;
41 | }
42 | NSCountedSet *functionNamesCounter = counters[_objectKey];
43 | NSUInteger numberOfSyncingFunctions = functionNamesCounter.count;
44 |
45 | if (!allowRecursive) {
46 | BOOL isTopLevelSyncScope = (numberOfSyncingFunctions == 0);
47 | NSArray *stack = [NSThread callStackSymbols];
48 | _GTMDevAssert(isTopLevelSyncScope,
49 | @"*** Recursive sync on %@ at %s; previous sync at %@\n%@",
50 | [object class], functionName, functionNamesCounter.allObjects,
51 | [stack subarrayWithRange:NSMakeRange(1, stack.count - 1)]);
52 | }
53 |
54 | if (!functionNamesCounter) {
55 | functionNamesCounter = [NSCountedSet set];
56 | counters[_objectKey] = functionNamesCounter;
57 | }
58 | [functionNamesCounter addObject:@(functionName)];
59 | }
60 | return self;
61 | }
62 |
63 | - (void)dealloc {
64 | Class threadKey = [GTMSyncMonitorInternal class];
65 |
66 | NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary;
67 | NSMutableDictionary *counters = threadDict[threadKey];
68 | NSCountedSet *functionNamesCounter = counters[_objectKey];
69 | NSString *functionNameStr = @(_functionName);
70 | NSUInteger numberOfSyncsByThisFunction = [functionNamesCounter countForObject:functionNameStr];
71 | NSArray *stack = [NSThread callStackSymbols];
72 | _GTMDevAssert(numberOfSyncsByThisFunction > 0, @"Sync not found on %@ at %s\n%@",
73 | [_objectKey.nonretainedObjectValue class], _functionName,
74 | [stack subarrayWithRange:NSMakeRange(1, stack.count - 1)]);
75 | [functionNamesCounter removeObject:functionNameStr];
76 | if (functionNamesCounter.count == 0) {
77 | [counters removeObjectForKey:_objectKey];
78 | }
79 | }
80 |
81 | + (NSArray *)functionsHoldingSynchronizationOnObject:(id)object {
82 | Class threadKey = [GTMSyncMonitorInternal class];
83 | NSValue *localObjectKey = [NSValue valueWithNonretainedObject:object];
84 |
85 | NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary;
86 | NSMutableDictionary *counters = threadDict[threadKey];
87 | NSCountedSet *functionNamesCounter = counters[localObjectKey];
88 | return functionNamesCounter.count > 0 ? functionNamesCounter.allObjects : nil;
89 | }
90 |
91 | @end
92 |
93 | #endif // DEBUG
94 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSString+FindFolder.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSString+FindFolder.m
3 | //
4 | // Copyright 2006-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMNSString+FindFolder.h"
20 | #import "GTMDefines.h"
21 |
22 | @implementation NSString (GTMStringFindFolderAdditions)
23 |
24 | + (NSString *)gtm_stringWithPathForFolder:(OSType)theFolderType
25 | inDomain:(short)theDomain
26 | doCreate:(BOOL)doCreate {
27 |
28 | NSString* folderPath = nil;
29 | FSRef folderRef;
30 |
31 | OSErr err = FSFindFolder(theDomain, theFolderType, doCreate, &folderRef);
32 | if (err == noErr) {
33 |
34 | CFURLRef folderURL = CFURLCreateFromFSRef(kCFAllocatorSystemDefault,
35 | &folderRef);
36 | if (folderURL) {
37 | folderPath = GTMCFAutorelease(CFURLCopyFileSystemPath(folderURL,
38 | kCFURLPOSIXPathStyle));
39 | CFRelease(folderURL);
40 | }
41 | }
42 | return folderPath;
43 | }
44 |
45 | + (NSString *)gtm_stringWithPathForFolder:(OSType)theFolderType
46 | subfolderName:(NSString *)subfolderName
47 | inDomain:(short)theDomain
48 | doCreate:(BOOL)doCreate {
49 | NSString *resultPath = nil;
50 | NSString *subdirPath = nil;
51 | NSString *parentFolderPath = [self gtm_stringWithPathForFolder:theFolderType
52 | inDomain:theDomain
53 | doCreate:doCreate];
54 | if (parentFolderPath) {
55 |
56 | // find the path to the subdirectory
57 | subdirPath = [parentFolderPath stringByAppendingPathComponent:subfolderName];
58 |
59 | NSFileManager* fileMgr = [NSFileManager defaultManager];
60 | BOOL isDir = NO;
61 | if ([fileMgr fileExistsAtPath:subdirPath isDirectory:&isDir] && isDir) {
62 | // it already exists
63 | resultPath = subdirPath;
64 | } else if (doCreate) {
65 | parentFolderPath = [parentFolderPath stringByResolvingSymlinksInPath];
66 | NSDictionary* attrs = nil;
67 | BOOL createdSubDir = NO;
68 | // create the subdirectory with the parent folder's attributes
69 | #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
70 | NSError *error = nil;
71 | attrs = [fileMgr attributesOfItemAtPath:parentFolderPath error:&error];
72 | if (error) {
73 | _GTMDevLog(@"Error %@ getting attributes of %@",
74 | error, parentFolderPath);
75 | }
76 | createdSubDir = [fileMgr createDirectoryAtPath:subdirPath
77 | withIntermediateDirectories:YES
78 | attributes:attrs
79 | error:&error];
80 | if (error) {
81 | _GTMDevLog(@"Error %@ creating directory at %@", error, subdirPath);
82 | }
83 | #else
84 | attrs = [fileMgr fileAttributesAtPath:parentFolderPath traverseLink:YES];
85 | createdSubDir = [fileMgr createDirectoryAtPath:subdirPath
86 | attributes:attrs];
87 | #endif // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
88 | if (createdSubDir) {
89 | resultPath = subdirPath;
90 | }
91 | }
92 | }
93 | return resultPath;
94 | }
95 |
96 | @end
97 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSFileManager+Carbon.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSFileManager+Carbon.m
3 | //
4 | // Copyright 2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMNSFileManager+Carbon.h"
20 | #import
21 | #import
22 | #import "GTMDefines.h"
23 |
24 | @implementation NSFileManager (GTMFileManagerCarbonAdditions)
25 |
26 | - (NSData *)gtm_aliasDataForPath:(NSString *)path {
27 | NSData *data = nil;
28 | FSRef ref;
29 | AliasHandle alias = NULL;
30 |
31 | __Require_Quiet([path length], CantUseParams);
32 | __Require_noErr(FSPathMakeRef((UInt8 *)[path fileSystemRepresentation],
33 | &ref, NULL), CantMakeRef);
34 | __Require_noErr(FSNewAlias(NULL, &ref, &alias), CantMakeAlias);
35 |
36 | Size length = GetAliasSize(alias);
37 | data = [NSData dataWithBytes:*alias length:length];
38 |
39 | DisposeHandle((Handle)alias);
40 |
41 | CantMakeAlias:
42 | CantMakeRef:
43 | CantUseParams:
44 | return data;
45 | }
46 |
47 | - (NSString *)gtm_pathFromAliasData:(NSData *)data {
48 | return [self gtm_pathFromAliasData:data resolve:YES withUI:YES];
49 | }
50 |
51 | - (NSString *)gtm_pathFromAliasData:(NSData *)data
52 | resolve:(BOOL)resolve
53 | withUI:(BOOL)withUI {
54 | NSString *path = nil;
55 | __Require_Quiet(data, CantUseParams);
56 |
57 | AliasHandle alias;
58 | const void *bytes = [data bytes];
59 | NSUInteger length = [data length];
60 | __Require_noErr(PtrToHand(bytes, (Handle *)&alias, length), CantMakeHandle);
61 |
62 | FSRef ref;
63 | Boolean wasChanged;
64 | // we don't use a require here because it is quite legitimate for an alias
65 | // resolve to fail.
66 |
67 | if (resolve) {
68 | OSStatus err
69 | = FSResolveAliasWithMountFlags(NULL, alias, &ref, &wasChanged,
70 | withUI ? kResolveAliasFileNoUI : 0);
71 | if (err == noErr) {
72 | path = [self gtm_pathFromFSRef:&ref];
73 | }
74 | } else {
75 | OSStatus err
76 | = FSCopyAliasInfo(alias, NULL, NULL, (CFStringRef *)(&path), NULL, NULL);
77 | if (err != noErr) path = nil;
78 | GTMCFAutorelease(path);
79 | }
80 | DisposeHandle((Handle)alias);
81 | CantMakeHandle:
82 | CantUseParams:
83 | return path;
84 | }
85 |
86 | - (FSRef *)gtm_FSRefForPath:(NSString *)path {
87 | FSRef* fsRef = NULL;
88 | __Require_Quiet([path length], CantUseParams);
89 | NSMutableData *fsRefData = [NSMutableData dataWithLength:sizeof(FSRef)];
90 | __Require(fsRefData, CantAllocateFSRef);
91 | fsRef = (FSRef*)[fsRefData mutableBytes];
92 | Boolean isDir = FALSE;
93 | const UInt8 *filePath = (const UInt8 *)[path fileSystemRepresentation];
94 | __Require_noErr_Action(FSPathMakeRef(filePath, fsRef, &isDir),
95 | CantMakeRef, fsRef = NULL);
96 | CantMakeRef:
97 | CantAllocateFSRef:
98 | CantUseParams:
99 | return fsRef;
100 | }
101 |
102 | - (NSString *)gtm_pathFromFSRef:(FSRef *)fsRef {
103 | NSString *nsPath = nil;
104 | __Require_Quiet(fsRef, CantUseParams);
105 |
106 | char path[MAXPATHLEN];
107 | __Require_noErr(FSRefMakePath(fsRef, (UInt8 *)path, MAXPATHLEN),
108 | CantMakePath);
109 | nsPath = [self stringWithFileSystemRepresentation:path length:strlen(path)];
110 | nsPath = [nsPath stringByStandardizingPath];
111 |
112 | CantMakePath:
113 | CantUseParams:
114 | return nsPath;
115 | }
116 |
117 | @end
118 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMLogger+ASL.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMLogger+ASL.h
3 | //
4 | // Copyright 2007-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 | #import
21 | #import "GTMLogger.h"
22 |
23 |
24 | // GTMLogger (GTMLoggerASLAdditions)
25 | //
26 | // Adds a convenience creation method that allows you to get a standard
27 | // GTMLogger object that is configured to write to ASL (Apple System Log) using
28 | // the GTMLogASLWriter (declared below).
29 | //
30 | @interface GTMLogger (GTMLoggerASLAdditions)
31 |
32 | // Returns a new autoreleased GTMLogger instance that will log to ASL, using
33 | // the GTMLogASLFormatter, and the GTMLogLevelFilter filter.
34 | + (id)standardLoggerWithASL;
35 |
36 | @end
37 |
38 |
39 | @class GTMLoggerASLClient;
40 |
41 | // GTMLogASLWriter
42 | //
43 | // A GTMLogWriter implementation that will send log messages to ASL (Apple
44 | // System Log facility). To use with GTMLogger simply set the "writer" for a
45 | // GTMLogger to be an instance of this class. The following example sets the
46 | // shared system logger to lot to ASL.
47 | //
48 | // [[GTMLogger sharedLogger] setWriter:[GTMLogASLWriter aslWriter]];
49 | // GTMLoggerInfo(@"Hi"); // This is sent to ASL
50 | //
51 | // See GTMLogger.h for more details and a higher-level view.
52 | //
53 | @interface GTMLogASLWriter : NSObject {
54 | @private
55 | GTM_WEAK Class aslClientClass_;
56 | NSString *facility_;
57 | }
58 |
59 | // Returns an autoreleased GTMLogASLWriter instance that uses an instance of
60 | // GTMLoggerASLClient and the default ASL facility.
61 | + (id)aslWriter;
62 |
63 | // Returns an autoreleased GTMLogASLWriter instance that uses an instance of
64 | // GTMLoggerASLClient and the supplied facility. See asl_open(3) for a
65 | // discusssion of ASL facility strings.
66 | + (id)aslWriterWithFacility:(NSString *)facility;
67 |
68 | // Designated initializer. Uses instances of the specified |clientClass| to talk
69 | // to the ASL system. All logs from this method will use |facility| as the ASL
70 | // log facility. This method is typically only useful for testing. Users
71 | // should generally NOT use this method to get an instance. Instead, simply use
72 | // the +aslWriter or +aslWriterWithFacility: methods to obtain an instance.
73 | - (id)initWithClientClass:(Class)clientClass facility:(NSString *)facility;
74 |
75 | @end // GTMLogASLWriter
76 |
77 |
78 | // An ASL-specific log formatter that replicates the same fields as
79 | // GTMLogStandardFormatter except for those (date, process name) that ASL
80 | // records independently.
81 | @interface GTMLogASLFormatter : GTMLogBasicFormatter
82 | @end // GTMLogASLFormatter
83 |
84 |
85 | // Helper class used by GTMLogASLWriter to create an ASL client and write to the
86 | // ASL log. This class is need to make management/cleanup of the aslclient work
87 | // in a multithreaded environment. You'll need one of these GTMLoggerASLClient
88 | // per thread (this is automatically handled by GTMLogASLWriter).
89 | //
90 | // This class should rarely (if EVER) be used directly. It's designed to be used
91 | // internally by GTMLogASLWriter, and by some unit tests. It should not be
92 | // used externally.
93 | @interface GTMLoggerASLClient : NSObject {
94 | @private
95 | aslclient client_;
96 | aslmsg msgOptions_;
97 | }
98 |
99 | // Designated initializer, |facility| is supplied to asl_open().
100 | - (id)initWithFacility:(NSString *)facility;
101 |
102 | // Sends the given string to ASL at the specified ASL log |level|.
103 | - (void)log:(NSString *)msg level:(int)level;
104 |
105 | @end
106 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMURLBuilder.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMURLBuilder.m
3 | //
4 | // Copyright 2012 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations
16 | // under the License.
17 | //
18 |
19 | #import "GTMURLBuilder.h"
20 |
21 | #import "GTMDefines.h"
22 | #import "GTMLogger.h"
23 | #import "GTMNSDictionary+URLArguments.h"
24 | #import "GTMNSString+URLArguments.h"
25 |
26 | @implementation GTMURLBuilder
27 |
28 | @synthesize baseURLString = baseURLString_;
29 |
30 | + (GTMURLBuilder *)builderWithString:(NSString *)URLString {
31 | GTMURLBuilder *URLBuilder =
32 | [[[GTMURLBuilder alloc] initWithString:URLString] autorelease];
33 | return URLBuilder;
34 | }
35 |
36 | + (GTMURLBuilder *)builderWithURL:(NSURL *)URL {
37 | return [self builderWithString:[URL absoluteString]];
38 | }
39 |
40 | - (id)init {
41 | self = [super init];
42 | [self release];
43 | _GTMDevAssert(NO, @"Invalid initialization.");
44 | return nil;
45 | }
46 |
47 | - (id)initWithString:(NSString *)URLString {
48 | self = [super init];
49 | if (self) {
50 | _GTMDevAssert(URLString, @"URL must not be nil");
51 | NSURL *URL = [NSURL URLWithString:URLString];
52 | _GTMDevAssert(URL, @"URL is invalid");
53 |
54 | // NSURL does not work with ports.
55 | baseURLString_ = [URL absoluteString];
56 | if ([URL query]) {
57 | NSRange pathRange =
58 | [baseURLString_ rangeOfString:[URL query] options:NSBackwardsSearch];
59 | if (pathRange.location != NSNotFound) {
60 | baseURLString_ = [baseURLString_ substringToIndex:pathRange.location-1];
61 | }
62 | }
63 | [baseURLString_ retain];
64 | params_ = [[NSDictionary gtm_dictionaryWithHttpArgumentsString:[URL query]]
65 | mutableCopy];
66 | }
67 | return self;
68 | }
69 |
70 | - (void)dealloc {
71 | [baseURLString_ release];
72 | [params_ release];
73 | [super dealloc];
74 | }
75 |
76 | - (void)setValue:(NSString *)value forParameter:(NSString *)parameter {
77 | [params_ setObject:value forKey:parameter];
78 | }
79 |
80 | - (void)setIntegerValue:(NSInteger)value forParameter:(NSString *)parameter {
81 | [params_ setObject:[NSString stringWithFormat:@"%ld", (long)value] forKey:parameter];
82 | }
83 |
84 | - (NSString *)valueForParameter:(NSString *)parameter {
85 | return [params_ objectForKey:parameter];
86 | }
87 |
88 | - (NSInteger)integerValueForParameter:(NSString *)parameter {
89 | return [[params_ objectForKey:parameter] integerValue];
90 | }
91 |
92 | - (void)removeParameter:(NSString *)parameter {
93 | [params_ removeObjectForKey:parameter];
94 | }
95 |
96 | - (void)setParameters:(NSDictionary *)parameters {
97 | [params_ autorelease];
98 | params_ = [[NSDictionary dictionaryWithDictionary:parameters] mutableCopy];
99 | }
100 |
101 | - (NSDictionary *)parameters {
102 | return params_;
103 | }
104 |
105 | - (NSURL *)URL {
106 | if (![params_ count]) {
107 | return [NSURL URLWithString:baseURLString_];
108 | } else {
109 | return [NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
110 | baseURLString_, [params_ gtm_httpArgumentsString]]];
111 | }
112 | }
113 |
114 | - (NSString *)URLString {
115 | return [[self URL] absoluteString];
116 | }
117 |
118 | - (BOOL)isEqual:(GTMURLBuilder *)URLBuilder {
119 | if (!URLBuilder) {
120 | return NO;
121 | }
122 |
123 | if (!([[self baseURLString] isEqualToString:[URLBuilder baseURLString]])) {
124 | return NO;
125 | }
126 |
127 | if (![[self parameters] isEqualToDictionary:[URLBuilder parameters]]) {
128 | return NO;
129 | }
130 |
131 | return YES;
132 | }
133 |
134 | - (NSUInteger)hash {
135 | return [baseURLString_ hash] * 17 + [params_ hash] * 37;
136 | }
137 |
138 | @end
139 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMGeometryUtils.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMGeometryUtils.m
3 | //
4 | // Copyright 2006-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMGeometryUtils.h"
20 |
21 | /// Align rectangles
22 | //
23 | // Args:
24 | // alignee - rect to be aligned
25 | // aligner - rect to be aligned to
26 | // alignment - alignment to be applied to alignee based on aligner
27 |
28 | CGRect GTMCGAlignRectangles(CGRect alignee, CGRect aligner, GTMRectAlignment alignment) {
29 | switch (alignment) {
30 | case GTMRectAlignTop:
31 | alignee.origin.x = aligner.origin.x + (CGRectGetWidth(aligner) * .5f - CGRectGetWidth(alignee) * .5f);
32 | alignee.origin.y = aligner.origin.y + CGRectGetHeight(aligner) - CGRectGetHeight(alignee);
33 | break;
34 |
35 | case GTMRectAlignTopLeft:
36 | alignee.origin.x = aligner.origin.x;
37 | alignee.origin.y = aligner.origin.y + CGRectGetHeight(aligner) - CGRectGetHeight(alignee);
38 | break;
39 |
40 | case GTMRectAlignTopRight:
41 | alignee.origin.x = aligner.origin.x + CGRectGetWidth(aligner) - CGRectGetWidth(alignee);
42 | alignee.origin.y = aligner.origin.y + CGRectGetHeight(aligner) - CGRectGetHeight(alignee);
43 | break;
44 |
45 | case GTMRectAlignLeft:
46 | alignee.origin.x = aligner.origin.x;
47 | alignee.origin.y = aligner.origin.y + (CGRectGetHeight(aligner) * .5f - CGRectGetHeight(alignee) * .5f);
48 | break;
49 |
50 | case GTMRectAlignBottomLeft:
51 | alignee.origin.x = aligner.origin.x;
52 | alignee.origin.y = aligner.origin.y;
53 | break;
54 |
55 | case GTMRectAlignBottom:
56 | alignee.origin.x = aligner.origin.x + (CGRectGetWidth(aligner) * .5f - CGRectGetWidth(alignee) * .5f);
57 | alignee.origin.y = aligner.origin.y;
58 | break;
59 |
60 | case GTMRectAlignBottomRight:
61 | alignee.origin.x = aligner.origin.x + CGRectGetWidth(aligner) - CGRectGetWidth(alignee);
62 | alignee.origin.y = aligner.origin.y;
63 | break;
64 |
65 | case GTMRectAlignRight:
66 | alignee.origin.x = aligner.origin.x + CGRectGetWidth(aligner) - CGRectGetWidth(alignee);
67 | alignee.origin.y = aligner.origin.y + (CGRectGetHeight(aligner) * .5f - CGRectGetHeight(alignee) * .5f);
68 | break;
69 |
70 | default:
71 | case GTMRectAlignCenter:
72 | alignee.origin.x = aligner.origin.x + (CGRectGetWidth(aligner) * .5f - CGRectGetWidth(alignee) * .5f);
73 | alignee.origin.y = aligner.origin.y + (CGRectGetHeight(aligner) * .5f - CGRectGetHeight(alignee) * .5f);
74 | break;
75 | }
76 | return alignee;
77 | }
78 |
79 | CGRect GTMCGScaleRectangleToSize(CGRect scalee, CGSize size, GTMScaling scaling) {
80 | switch (scaling) {
81 |
82 | case GTMScaleToFillProportionally:
83 | case GTMScaleProportionally: {
84 | CGFloat height = CGRectGetHeight(scalee);
85 | CGFloat width = CGRectGetWidth(scalee);
86 | if (isnormal(height) && isnormal(width) &&
87 | (height > size.height || width > size.width)) {
88 | CGFloat horiz = size.width / width;
89 | CGFloat vert = size.height / height;
90 | BOOL expand = (scaling == GTMScaleToFillProportionally);
91 | // We use the smaller scale unless expand is true. In that case, larger.
92 | CGFloat newScale = ((horiz < vert) ^ expand) ? horiz : vert;
93 | scalee = GTMCGRectScale(scalee, newScale, newScale);
94 | }
95 | break;
96 | }
97 |
98 | case GTMScaleToFit:
99 | scalee.size = size;
100 | break;
101 |
102 | case GTMScaleNone:
103 | default:
104 | // Do nothing
105 | break;
106 | }
107 | return scalee;
108 | }
109 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMDebugSelectorValidation.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMDebugSelectorValidation.h
3 | //
4 | // This file should only be included within an implimation file. In any
5 | // function that takes an object and selector to invoke, you should call:
6 | //
7 | // GTMAssertSelectorNilOrImplementedWithArguments(obj, sel, @encode(arg1type), ..., NULL)
8 | // or
9 | // GTMAssertSelectorNilOrImplementedWithReturnTypeAndArguments(obj, sel, @encode(returnType), @encode(arg1type), ..., NULL)
10 | //
11 | // This will then validate that the selector is defined and using the right
12 | // type(s), this can help catch errors much earlier then waiting for the
13 | // selector to actually fire (and in the case of error selectors, might never
14 | // really be tested until in the field).
15 | //
16 | // Copyright 2007-2008 Google Inc.
17 | //
18 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
19 | // use this file except in compliance with the License. You may obtain a copy
20 | // of the License at
21 | //
22 | // http://www.apache.org/licenses/LICENSE-2.0
23 | //
24 | // Unless required by applicable law or agreed to in writing, software
25 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
26 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
27 | // License for the specific language governing permissions and limitations under
28 | // the License.
29 | //
30 |
31 | #if DEBUG
32 |
33 | #import
34 | #import "GTMDefines.h"
35 |
36 | static void GTMAssertSelectorNilOrImplementedWithReturnTypeAndArguments(id obj, SEL sel, const char *retType, ...) {
37 |
38 | // verify that the object's selector is implemented with the proper
39 | // number and type of arguments
40 | va_list argList;
41 | va_start(argList, retType);
42 |
43 | if (obj && sel) {
44 | // check that the selector is implemented
45 | _GTMDevAssert([obj respondsToSelector:sel],
46 | @"\"%@\" selector \"%@\" is unimplemented or misnamed",
47 | NSStringFromClass([obj class]),
48 | NSStringFromSelector(sel));
49 |
50 | const char *expectedArgType;
51 | NSUInteger argCount = 2; // skip self and _cmd
52 | NSMethodSignature *sig = [obj methodSignatureForSelector:sel];
53 |
54 | // check that each expected argument is present and of the correct type
55 | while ((expectedArgType = va_arg(argList, const char*)) != 0) {
56 |
57 | if ([sig numberOfArguments] > argCount) {
58 | const char *foundArgType = [sig getArgumentTypeAtIndex:argCount];
59 |
60 | _GTMDevAssert(0 == strncmp(foundArgType, expectedArgType, strlen(expectedArgType)),
61 | @"\"%@\" selector \"%@\" argument %u should be type %s",
62 | NSStringFromClass([obj class]),
63 | NSStringFromSelector(sel),
64 | (uint32_t)(argCount - 2),
65 | expectedArgType);
66 | }
67 | argCount++;
68 | }
69 |
70 | // check that the proper number of arguments are present in the selector
71 | _GTMDevAssert(argCount == [sig numberOfArguments],
72 | @"\"%@\" selector \"%@\" should have %u arguments",
73 | NSStringFromClass([obj class]),
74 | NSStringFromSelector(sel),
75 | (uint32_t)(argCount - 2));
76 |
77 | // if asked, validate the return type
78 | if (retType && (strcmp("gtm_skip_return_test", retType) != 0)) {
79 | const char *foundRetType = [sig methodReturnType];
80 | _GTMDevAssert(0 == strncmp(foundRetType, retType, strlen(retType)),
81 | @"\"%@\" selector \"%@\" return type should be type %s",
82 | NSStringFromClass([obj class]),
83 | NSStringFromSelector(sel),
84 | retType);
85 | }
86 | }
87 |
88 | va_end(argList);
89 | }
90 |
91 | #define GTMAssertSelectorNilOrImplementedWithArguments(obj, sel, ...) \
92 | GTMAssertSelectorNilOrImplementedWithReturnTypeAndArguments((obj), (sel), "gtm_skip_return_test", __VA_ARGS__)
93 |
94 | #else // DEBUG
95 |
96 | // make it go away if not debug
97 | #define GTMAssertSelectorNilOrImplementedWithReturnTypeAndArguments(obj, sel, retType, ...) do { } while (0)
98 | #define GTMAssertSelectorNilOrImplementedWithArguments(obj, sel, ...) do { } while (0)
99 |
100 | #endif // DEBUG
101 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSArray+Merge.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSArray+Merge.m
3 | //
4 | // Copyright 2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations
16 | // under the License.
17 | //
18 |
19 | #import "GTMNSArray+Merge.h"
20 |
21 | #import "GTMDefines.h"
22 |
23 | #if GTM_IPHONE_SDK
24 | #import
25 | #else // GTM_IPHONE_SDK
26 | #import
27 | #endif // GTM_IPHONE_SDK
28 |
29 | @implementation NSArray (GTMNSArrayMergingAdditions)
30 |
31 | - (NSArray *)gtm_mergeArray:(NSArray *)newArray
32 | mergeSelector:(SEL)merger {
33 | return [self gtm_mergeArray:newArray
34 | compareSelector:@selector(compare:)
35 | mergeSelector:merger];
36 | }
37 |
38 | - (NSArray *)gtm_mergeArray:(NSArray *)newArray
39 | compareSelector:(SEL)comparer
40 | mergeSelector:(SEL)merger {
41 | // must have a compare selector
42 | if (!comparer) return nil;
43 |
44 | // Sort and merge the contents of |self| with |newArray|.
45 | NSArray *sortedMergedArray = nil;
46 | if ([self count] && [newArray count]) {
47 | NSMutableArray *mergingArray = [NSMutableArray arrayWithArray:self];
48 | [mergingArray sortUsingSelector:comparer];
49 | NSArray *sortedNewArray
50 | = [newArray sortedArrayUsingSelector:comparer];
51 |
52 | NSUInteger oldIndex = 0;
53 | NSUInteger oldCount = [mergingArray count];
54 | id oldItem = (oldIndex < oldCount)
55 | ? [mergingArray objectAtIndex:0]
56 | : nil;
57 |
58 | id newItem = nil;
59 | for (newItem in sortedNewArray) {
60 | BOOL stillLooking = YES;
61 | while (oldIndex < oldCount && stillLooking) {
62 | // We must take care here, since Intel leaves junk in high bytes of
63 | // return register for predicates that return BOOL.
64 | // For details see:
65 | // http://developer.apple.com/documentation/MacOSX/Conceptual/universal_binary/universal_binary_tips/chapter_5_section_23.html
66 | // and
67 | // http://www.red-sweater.com/blog/320/abusing-objective-c-with-class#comment-83187
68 | NSComparisonResult result
69 | = ((NSComparisonResult (*)(id, SEL, id))objc_msgSend)(newItem, comparer, oldItem);
70 | if (result == NSOrderedSame && merger) {
71 | // It's a match!
72 | id repItem = [oldItem performSelector:merger
73 | withObject:newItem];
74 | [mergingArray replaceObjectAtIndex:oldIndex
75 | withObject:repItem];
76 | ++oldIndex;
77 | oldItem = (oldIndex < oldCount)
78 | ? [mergingArray objectAtIndex:oldIndex]
79 | : nil;
80 | stillLooking = NO;
81 | } else if (result == NSOrderedAscending
82 | || (result == NSOrderedSame && !merger)) {
83 | // This is either a new item and belongs right here, or it's
84 | // a match to an existing item but we're not merging.
85 | [mergingArray insertObject:newItem
86 | atIndex:oldIndex];
87 | ++oldIndex;
88 | ++oldCount;
89 | stillLooking = NO;
90 | } else {
91 | ++oldIndex;
92 | oldItem = (oldIndex < oldCount)
93 | ? [mergingArray objectAtIndex:oldIndex]
94 | : nil;
95 | }
96 | }
97 | if (stillLooking) {
98 | // Once we get here, the rest of the new items get appended.
99 | [mergingArray addObject:newItem];
100 | }
101 | }
102 | sortedMergedArray = mergingArray;
103 | } else if ([self count]) {
104 | sortedMergedArray = [self sortedArrayUsingSelector:comparer];
105 | } else if ([newArray count]) {
106 | sortedMergedArray = [newArray sortedArrayUsingSelector:comparer];
107 | }
108 | return sortedMergedArray;
109 | }
110 |
111 | @end
112 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMStringEncoding.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMStringEncoding.h
3 | //
4 | // Copyright 2010 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 | #import "GTMDefines.h"
21 |
22 | // A generic class for arbitrary base-2 to 128 string encoding and decoding.
23 | @interface GTMStringEncoding : NSObject {
24 | @private
25 | NSData *charMapData_;
26 | char *charMap_;
27 | int reverseCharMap_[128];
28 | int shift_;
29 | int mask_;
30 | BOOL doPad_;
31 | char paddingChar_;
32 | int padLen_;
33 | }
34 |
35 | // Create a new, autoreleased GTMStringEncoding object with a standard encoding.
36 | + (id)binaryStringEncoding;
37 | + (id)hexStringEncoding;
38 | + (id)rfc4648Base32StringEncoding;
39 | + (id)rfc4648Base32HexStringEncoding;
40 | + (id)crockfordBase32StringEncoding;
41 | + (id)rfc4648Base64StringEncoding;
42 | + (id)rfc4648Base64WebsafeStringEncoding;
43 |
44 | // Create a new, autoreleased GTMStringEncoding object with the given string,
45 | // as described below.
46 | + (id)stringEncodingWithString:(NSString *)string;
47 |
48 | // Initialize a new GTMStringEncoding object with the string.
49 | //
50 | // The length of the string must be a power of 2, at least 2 and at most 128.
51 | // Only 7-bit ASCII characters are permitted in the string.
52 | //
53 | // These characters are the canonical set emitted during encoding.
54 | // If the characters have alternatives (e.g. case, easily transposed) then use
55 | // addDecodeSynonyms: to configure them.
56 | - (id)initWithString:(NSString *)string;
57 |
58 | // Add decoding synonyms as specified in the synonyms argument.
59 | //
60 | // It should be a sequence of one previously reverse mapped character,
61 | // followed by one or more non-reverse mapped character synonyms.
62 | // Only 7-bit ASCII characters are permitted in the string.
63 | //
64 | // e.g. If a GTMStringEncoder object has already been initialised with a set
65 | // of characters excluding I, L and O (to avoid confusion with digits) and you
66 | // want to accept them as digits you can call addDecodeSynonyms:@"0oO1iIlL".
67 | - (void)addDecodeSynonyms:(NSString *)synonyms;
68 |
69 | // A sequence of characters to ignore if they occur during encoding.
70 | // Only 7-bit ASCII characters are permitted in the string.
71 | - (void)ignoreCharacters:(NSString *)chars;
72 |
73 | // Indicates whether padding is performed during encoding.
74 | - (BOOL)doPad;
75 | - (void)setDoPad:(BOOL)doPad;
76 |
77 | // Sets the padding character to use during encoding.
78 | - (void)setPaddingChar:(char)c;
79 |
80 | // Encode a raw binary buffer to a 7-bit ASCII string.
81 | - (NSString *)encode:(NSData *)data __attribute__((deprecated("Use encode:error:")));
82 | - (NSString *)encodeString:(NSString *)string __attribute__((deprecated("Use encodeString:error:")));
83 |
84 | - (NSString *)encode:(NSData *)data error:(NSError **)error;
85 | - (NSString *)encodeString:(NSString *)string error:(NSError **)error;
86 |
87 | // Decode a 7-bit ASCII string to a raw binary buffer.
88 | - (NSData *)decode:(NSString *)string __attribute__((deprecated("Use decode:error:")));
89 | - (NSString *)stringByDecoding:(NSString *)string __attribute__((deprecated("Use stringByDecoding:error:")));
90 |
91 | - (NSData *)decode:(NSString *)string error:(NSError **)error;
92 | - (NSString *)stringByDecoding:(NSString *)string error:(NSError **)error;
93 |
94 | @end
95 |
96 | FOUNDATION_EXPORT NSString *const GTMStringEncodingErrorDomain;
97 | FOUNDATION_EXPORT NSString *const GTMStringEncodingBadCharacterIndexKey; // NSNumber
98 |
99 | typedef NS_ENUM(NSInteger, GTMStringEncodingError) {
100 | // Unable to convert a buffer to NSASCIIStringEncoding.
101 | GTMStringEncodingErrorUnableToConverToAscii = 1024,
102 | // Unable to convert a buffer to NSUTF8StringEncoding.
103 | GTMStringEncodingErrorUnableToConverToUTF8,
104 | // Encountered a bad character.
105 | // GTMStringEncodingBadCharacterIndexKey will have the index of the character.
106 | GTMStringEncodingErrorUnknownCharacter,
107 | // The data had a padding character in the middle of the data. Padding characters
108 | // can only be at the end.
109 | GTMStringEncodingErrorExpectedPadding,
110 | // There is unexpected data at the end of the data that could not be decoded.
111 | GTMStringEncodingErrorIncompleteTrailingData,
112 | };
113 |
--------------------------------------------------------------------------------
/GoldenPassport/OTPAuth/OTPGenerator.m:
--------------------------------------------------------------------------------
1 | //
2 | // HOTPGenerator.m
3 | //
4 | // Copyright 2011 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "OTPGenerator.h"
20 |
21 | #import
22 | #import
23 |
24 | #import "GTMDefines.h"
25 |
26 | static NSUInteger kPinModTable[] = {
27 | 0,
28 | 10,
29 | 100,
30 | 1000,
31 | 10000,
32 | 100000,
33 | 1000000,
34 | 10000000,
35 | 100000000,
36 | };
37 |
38 | NSString *const kOTPGeneratorSHA1Algorithm = @"SHA1";
39 | NSString *const kOTPGeneratorSHA256Algorithm = @"SHA256";
40 | NSString *const kOTPGeneratorSHA512Algorithm = @"SHA512";
41 | NSString *const kOTPGeneratorSHAMD5Algorithm = @"MD5";
42 |
43 | @interface OTPGenerator ()
44 | @property (readwrite, nonatomic, copy) NSString *algorithm;
45 | @property (readwrite, nonatomic, copy) NSData *secret;
46 | @end
47 |
48 | @implementation OTPGenerator
49 |
50 | + (NSString *)defaultAlgorithm {
51 | return kOTPGeneratorSHA1Algorithm;
52 | }
53 |
54 | + (NSUInteger)defaultDigits {
55 | return 6;
56 | }
57 |
58 | @synthesize algorithm = algorithm_;
59 | @synthesize secret = secret_;
60 | @synthesize digits = digits_;
61 |
62 | - (id)init {
63 | [self doesNotRecognizeSelector:_cmd];
64 | return nil;
65 | }
66 |
67 | - (id)initWithSecret:(NSData *)secret
68 | algorithm:(NSString *)algorithm
69 | digits:(NSUInteger)digits {
70 | if ((self = [super init])) {
71 | algorithm_ = [algorithm copy];
72 | secret_ = [secret copy];
73 | digits_ = digits;
74 |
75 | BOOL goodAlgorithm
76 | = ([algorithm isEqualToString:kOTPGeneratorSHA1Algorithm] ||
77 | [algorithm isEqualToString:kOTPGeneratorSHA256Algorithm] ||
78 | [algorithm isEqualToString:kOTPGeneratorSHA512Algorithm] ||
79 | [algorithm isEqualToString:kOTPGeneratorSHAMD5Algorithm]);
80 | if (!goodAlgorithm || digits_ > 8 || digits_ < 6 || !secret_) {
81 | _GTMDevLog(@"Bad args digits(min 6, max 8): %d secret: %@ algorithm: %@",
82 | digits_, secret_, algorithm_);
83 | [self release];
84 | self = nil;
85 | }
86 | }
87 | return self;
88 | }
89 |
90 | - (void)dealloc {
91 | self.algorithm = nil;
92 | self.secret = nil;
93 | [super dealloc];
94 | }
95 |
96 | // Must be overriden by subclass.
97 | - (NSString *)generateOTP {
98 | [self doesNotRecognizeSelector:_cmd];
99 | return nil;
100 | }
101 |
102 | - (NSString *)generateOTPForCounter:(uint64_t)counter {
103 | CCHmacAlgorithm alg;
104 | NSUInteger hashLength = 0;
105 | if ([algorithm_ isEqualToString:kOTPGeneratorSHA1Algorithm]) {
106 | alg = kCCHmacAlgSHA1;
107 | hashLength = CC_SHA1_DIGEST_LENGTH;
108 | } else if ([algorithm_ isEqualToString:kOTPGeneratorSHA256Algorithm]) {
109 | alg = kCCHmacAlgSHA256;
110 | hashLength = CC_SHA256_DIGEST_LENGTH;
111 | } else if ([algorithm_ isEqualToString:kOTPGeneratorSHA512Algorithm]) {
112 | alg = kCCHmacAlgSHA512;
113 | hashLength = CC_SHA512_DIGEST_LENGTH;
114 | } else if ([algorithm_ isEqualToString:kOTPGeneratorSHAMD5Algorithm]) {
115 | alg = kCCHmacAlgMD5;
116 | hashLength = CC_MD5_DIGEST_LENGTH;
117 | } else {
118 | _GTMDevAssert(NO, @"Unknown algorithm");
119 | return nil;
120 | }
121 |
122 | NSMutableData *hash = [NSMutableData dataWithLength:hashLength];
123 |
124 | counter = NSSwapHostLongLongToBig(counter);
125 | NSData *counterData = [NSData dataWithBytes:&counter
126 | length:sizeof(counter)];
127 | CCHmacContext ctx;
128 | CCHmacInit(&ctx, alg, [secret_ bytes], [secret_ length]);
129 | CCHmacUpdate(&ctx, [counterData bytes], [counterData length]);
130 | CCHmacFinal(&ctx, [hash mutableBytes]);
131 |
132 | const char *ptr = [hash bytes];
133 | unsigned char offset = ptr[hashLength-1] & 0x0f;
134 | uint32_t truncatedHash =
135 | NSSwapBigIntToHost(*((uint32_t *)&ptr[offset])) & 0x7fffffff;
136 | uint32_t pinValue = truncatedHash % kPinModTable[digits_];
137 |
138 | // _GTMDevLog(@"secret: %@", secret_);
139 | // _GTMDevLog(@"counter: %llu", counter);
140 | // _GTMDevLog(@"hash: %@", hash);
141 | // _GTMDevLog(@"offset: %d", offset);
142 | // _GTMDevLog(@"truncatedHash: %d", truncatedHash);
143 | // _GTMDevLog(@"pinValue: %d", pinValue);
144 |
145 | return [NSString stringWithFormat:@"%0*u", (int)digits_, pinValue];
146 | }
147 |
148 | @end
149 |
--------------------------------------------------------------------------------
/GoldenPassport/DataManager.swift:
--------------------------------------------------------------------------------
1 | //
2 | // DataManager.swift
3 | // GoldenPassport
4 | //
5 | // Created by StanZhai on 2017/2/26.
6 | // Copyright © 2017年 StanZhai. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | final class DataManager {
12 | static let shared = DataManager()
13 | private let authDataFile = "gp.secrets"
14 | private let configFile = "config.plist"
15 |
16 | private var authData: [String: String]
17 | private var config: [String: String]
18 |
19 | private init() {
20 | authData = [:]
21 | config = [:]
22 | authData = loadData(authDataFile)
23 | config = loadData(configFile)
24 | }
25 |
26 | func addOTPAuthURL(tag: String, url: String) {
27 | authData[tag] = url
28 | saveData(authDataFile, data: authData)
29 | }
30 |
31 | func removeOTPAuthURL(tag: String) {
32 | authData.removeValue(forKey: tag)
33 | saveData(authDataFile, data: authData)
34 | }
35 |
36 | func allAuthCode() -> [(key: String, value: String)] {
37 | var result: [(key: String, value: String)] = []
38 | for d in authData {
39 | let url = d.value
40 | let otpData = OTPAuthURLParser(url)!
41 |
42 | let data = OTPAuthURL.base32Decode(otpData.secret)
43 | let gen = TOTPGenerator(secret: data,
44 | algorithm: TOTPGenerator.defaultAlgorithm(),
45 | digits: TOTPGenerator.defaultDigits(),
46 | period: TOTPGenerator.defaultPeriod())
47 | let code = gen?.generateOTP(for: Date())
48 |
49 | result.append((key: d.key, value: code ?? ""))
50 | }
51 | return result
52 | }
53 |
54 | func dataCount() -> Int {
55 | return authData.count
56 | }
57 |
58 | func getHttpServerAutoStart() -> Bool {
59 | let auto = getConfig("http_server_auto_start")
60 | if (auto == nil || auto == "true") {
61 | return true;
62 | } else {
63 | return false;
64 | }
65 | }
66 |
67 | func saveHttpServerAutoStart(auto: Bool) {
68 | saveConfig(key: "http_server_auto_start", value: "\(auto)")
69 | }
70 |
71 | func getHttpServerPort() -> String {
72 | return getConfig("http_server_port") ?? "\(DEFAULT_HTTP_PORT)"
73 | }
74 |
75 | func saveHttpServerPort(port: String) {
76 | saveConfig(key: "http_server_port", value: port)
77 | }
78 |
79 | func getConfig(_ key: String) -> String? {
80 | return config[key]
81 | }
82 |
83 | func saveConfig(key: String, value: String) {
84 | config[key] = value
85 | saveData(configFile, data: config)
86 | }
87 |
88 | func importData(dist: URL) -> Int {
89 | let d = NSKeyedUnarchiver.unarchiveObject(withFile: dist.path)
90 | if d == nil {
91 | return 0
92 | }
93 | let data = d as! [String: String]
94 | var count = 0;
95 | for k in data {
96 | if authData[k.key] == nil {
97 | authData[k.key] = k.value
98 | count = count + 1
99 | }
100 | }
101 | saveData(authDataFile, data: authData)
102 | return count
103 | }
104 |
105 | func exportData(dist: URL) {
106 | let fileLocation = "\(dataFilePath)\(authDataFile)"
107 | let fileUrl = URL(fileURLWithPath: fileLocation)
108 | let manager = FileManager.default
109 | try? manager.copyItem(at: fileUrl, to: dist)
110 | }
111 |
112 | private func saveData(_ dataFile: String, data: [String: String]) {
113 | let fileLocation = "\(dataFilePath)\(dataFile)"
114 | let fileUrl = URL(fileURLWithPath: fileLocation)
115 | try? NSKeyedArchiver.archivedData(withRootObject: data).write(to: fileUrl)
116 | }
117 |
118 | private func loadData(_ dataFile: String) -> [String: String] {
119 | let fileLocation = "\(dataFilePath)\(dataFile)"
120 | let d = NSKeyedUnarchiver.unarchiveObject(withFile: fileLocation)
121 | if d != nil {
122 | return d as! [String: String]
123 | }
124 | return [:]
125 | }
126 |
127 | private var dataFilePath: String {
128 | let fileManager = FileManager.default
129 | let path = NSSearchPathForDirectoriesInDomains(
130 | Foundation.FileManager.SearchPathDirectory.applicationSupportDirectory,
131 | Foundation.FileManager.SearchPathDomainMask.userDomainMask,
132 | true).first! + "/GoldenPassport/"
133 | if !fileManager.fileExists(atPath: path) {
134 | do {
135 | try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
136 | } catch {
137 | print(error)
138 | }
139 | }
140 |
141 | return path
142 | }
143 |
144 | }
145 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSFileHandle+UniqueName.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSFileHandle+UniqueName.m
3 | //
4 | // Copyright 2010 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMNSFileHandle+UniqueName.h"
20 |
21 | #include
22 |
23 | // Export a nonsense symbol to suppress a libtool warning when this is linked alone in a static lib.
24 | __attribute__((visibility("default")))
25 | char GTMFileHandleUniqueNameExportToSuppressLibToolWarning = 0;
26 |
27 |
28 | @implementation NSFileHandle (GTMFileHandleUniqueNameAdditions)
29 |
30 | + (id)gtm_fileHandleWithUniqueNameBasedOn:(NSString *)pathTemplate
31 | finalPath:(NSString **)path {
32 | if (!pathTemplate) return nil;
33 | NSString *extension = [pathTemplate pathExtension];
34 | char *pathTemplateCString = strdup([pathTemplate fileSystemRepresentation]);
35 | if (!pathTemplateCString) return nil;
36 | int len = (int)[extension length];
37 | if (len > 0) {
38 | // Suffix length needs to include a period.
39 | len++;
40 | }
41 | int fileDescriptor = mkstemps(pathTemplateCString, len);
42 | if (fileDescriptor == -1) {
43 | free(pathTemplateCString);
44 | return nil;
45 | }
46 | NSFileHandle *handle
47 | = [[[NSFileHandle alloc] initWithFileDescriptor:fileDescriptor
48 | closeOnDealloc:YES] autorelease];
49 | if (handle && path) {
50 | *path = [NSString stringWithUTF8String:pathTemplateCString];
51 | }
52 | free(pathTemplateCString);
53 | return handle;
54 | }
55 |
56 | + (id)gtm_fileHandleWithUniqueNameBasedOn:(NSString *)nameTemplate
57 | inDirectory:(NSString *)directory
58 | finalPath:(NSString **)path {
59 | NSString *fullPath = [directory stringByAppendingPathComponent:nameTemplate];
60 | return [self gtm_fileHandleWithUniqueNameBasedOn:fullPath finalPath:path];
61 | }
62 |
63 | + (id)gtm_fileHandleWithUniqueNameBasedOn:(NSString *)nameTemplate
64 | inDirectory:(NSSearchPathDirectory)directory
65 | domainMask:(NSSearchPathDomainMask)mask
66 | finalPath:(NSString **)path {
67 | NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(directory,
68 | mask,
69 | YES);
70 | if ([searchPaths count] == 0) return nil;
71 | NSString *searchPath = [searchPaths objectAtIndex:0];
72 | return [self gtm_fileHandleWithUniqueNameBasedOn:nameTemplate
73 | inDirectory:searchPath
74 | finalPath:path];
75 | }
76 |
77 | + (id)gtm_fileHandleForTemporaryFileBasedOn:(NSString *)nameTemplate
78 | finalPath:(NSString **)path {
79 | return [self gtm_fileHandleWithUniqueNameBasedOn:nameTemplate
80 | inDirectory:NSTemporaryDirectory()
81 | finalPath:path];
82 | }
83 |
84 | @end
85 |
86 | @implementation NSFileManager (GTMFileManagerUniqueNameAdditions)
87 |
88 | - (NSString *)gtm_createDirectoryWithUniqueNameBasedOn:(NSString *)pathTemplate {
89 | if (!pathTemplate) return nil;
90 | char *pathTemplateCString = strdup([pathTemplate fileSystemRepresentation]);
91 | if (!pathTemplateCString) return nil;
92 | char *outCName = mkdtemp(pathTemplateCString);
93 | NSString *outName = outCName ? [NSString stringWithUTF8String:outCName] : nil;
94 | free(pathTemplateCString);
95 | return outName;
96 | }
97 |
98 | - (NSString *)gtm_createDirectoryWithUniqueNameBasedOn:(NSString *)nameTemplate
99 | inDirectory:(NSString *)directory {
100 | NSString *fullPath = [directory stringByAppendingPathComponent:nameTemplate];
101 | return [self gtm_createDirectoryWithUniqueNameBasedOn:fullPath];
102 | }
103 |
104 | - (NSString *)gtm_createDirectoryWithUniqueNameBasedOn:(NSString *)nameTemplate
105 | inDirectory:(NSSearchPathDirectory)directory
106 | domainMask:(NSSearchPathDomainMask)mask {
107 | NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(directory,
108 | mask,
109 | YES);
110 | if ([searchPaths count] == 0) return nil;
111 | NSString *searchPath = [searchPaths objectAtIndex:0];
112 | return [self gtm_createDirectoryWithUniqueNameBasedOn:nameTemplate
113 | inDirectory:searchPath];
114 | }
115 |
116 | - (NSString *)gtm_createTemporaryDirectoryBasedOn:(NSString *)nameTemplate {
117 | return [self gtm_createDirectoryWithUniqueNameBasedOn:nameTemplate
118 | inDirectory:NSTemporaryDirectory()];
119 | }
120 |
121 | @end
122 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMPath.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMPath.h
3 | //
4 | // Copyright 2007-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import
20 |
21 | #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
22 | // NSFileManager has improved substantially in Leopard and beyond, so GTMPath
23 | // is now deprecated.
24 |
25 | // GTMPath
26 | //
27 | // This class represents a single, absolute file system path. The represented
28 | // path must exist at the time of creation. This class also allows you to easily
29 | // create new paths (or full hierarchies) based on existing GTMPath instances.
30 | //
31 | // Given a GTMPath instance, new files and directories can be created inside
32 | // that path providing the instance refers to a directory. It is an error to try
33 | // to create a file/directory from a GTMPath that represents a file (this should
34 | // be common sense: clearly mkdir /etc/passwd/foo won't work).
35 | //
36 | // === Examples ===
37 | //
38 | // 1. This sample creates a GTMPath that references /tmp, then gets the
39 | // attributes for that directory.
40 | //
41 | // GTMPath *tmp = [GTMPath pathWithFullPath:@"/tmp"];
42 | // NSDictionary *attr = [tmp attributes];
43 | //
44 | //
45 | // 2. This sample creates a new directory inside /tmp named "foo".
46 | //
47 | // GTMPath *tmp = [GTMPath pathWithFullPath:@"/tmp"];
48 | // GTMPath *foo = [tmp createDirectoryName:@"foo" mode:0755];
49 | //
50 | //
51 | // 3. This sample creates a GTMPath instance that represents a user's ~/Library
52 | // folder.
53 | //
54 | // GTMPath *library = [GTMPath pathWithFullPath:@"/Users/bob/Library"];
55 | // ...
56 | //
57 | //
58 | // 4. This sample creates a directory hierarchy, where each level has its own
59 | // mode. Notice that the return value from these -create* methods is the
60 | // GTMPath that was just created. This allows these creation calls to be
61 | // chained together enabling easy creation of directory hierarchies.
62 | // This is one of the big benefits of this class.
63 | //
64 | // GTMPath *tmp = [GTMPath pathWithFullPath:@"/tmp"];
65 | // GTMPath *baz = [[[tmp createDirectoryName:@"foo" mode:0755]
66 | // createDirectoryName:@"bar" mode:0756]
67 | // createDirectoryName:@"baz" mode:0757];
68 | //
69 | @interface GTMPath : NSObject {
70 | @private
71 | NSString *fullPath_;
72 | }
73 |
74 | // Returns a GTMPath instance that represents the full path specified by
75 | // |fullPath|. Note that |fullPath| MUST be an absolute path.
76 | + (id)pathWithFullPath:(NSString *)fullPath;
77 |
78 | // Returns a GTMPath instance that represents the full path specified by
79 | // |fullPath|. Note that |fullPath| MUST be an absolute path. This method is the
80 | // designated initializer.
81 | - (id)initWithFullPath:(NSString *)fullPath;
82 |
83 | // Returns the name of this GTMPath instance. This is not the full path. It is
84 | // just the component name of this GTMPath instance. This is equivalent to
85 | // the Unix basename(3) function.
86 | - (NSString *)name;
87 |
88 | // Returns this path's parent GTMPath. This method will ONLY (and always) return
89 | // nil when |name| is "/". In otherwords, parent will be nil IFF this GTMPath
90 | // instance represents the root path, because "/" doesn't really have a parent.
91 | - (GTMPath *)parent;
92 |
93 | // Returns YES if this GTMPath represents a directory.
94 | - (BOOL)isDirectory;
95 |
96 | // Returns YES if this GTMPath instance represents the root path "/".
97 | - (BOOL)isRoot;
98 |
99 | // Returns the file system attributes of the path represented by this GTMPath
100 | // instance. See -[NSFileManager fileAttributesAtPath:...] for details.
101 | - (NSDictionary *)attributes;
102 |
103 | // Returns a string representation of the absolute path represented by this
104 | // GTMPath instance.
105 | - (NSString *)fullPath;
106 |
107 | @end
108 |
109 |
110 | // Methods for creating files and directories inside a GTMPath instance. These
111 | // methods are only allowed to be called on GTMPath instances that represent
112 | // directories. See the NSFileManager documentation for details about the
113 | // |attributes| parameters.
114 | @interface GTMPath (GTMPathGeneration)
115 |
116 | // Creates a new directory with the specified mode or attributes inside the
117 | // current GTMPath instance. If the creation is successful, a GTMPath for the
118 | // newly created directory is returned. Otherwise, nil is returned.
119 | - (GTMPath *)createDirectoryName:(NSString *)name mode:(mode_t)mode;
120 | - (GTMPath *)createDirectoryName:(NSString *)name
121 | attributes:(NSDictionary *)attributes;
122 |
123 | // Creates a new file with the specified mode or attributes inside the
124 | // current GTMPath instance. If the creation is successful, a GTMPath for the
125 | // newly created file is returned. Otherwise, nil is returned. |data| is the
126 | // data to put in the file when created.
127 | - (GTMPath *)createFileName:(NSString *)name mode:(mode_t)mode;
128 | - (GTMPath *)createFileName:(NSString *)name
129 | attributes:(NSDictionary *)attributes;
130 | - (GTMPath *)createFileName:(NSString *)name
131 | attributes:(NSDictionary *)attributes
132 | data:(NSData *)data;
133 |
134 | @end
135 |
136 | #endif // MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
137 |
--------------------------------------------------------------------------------
/GoldenPassport/HTTPPortConfigWindow.xib:
--------------------------------------------------------------------------------
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 |
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 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMSynchronizationAsserts.h:
--------------------------------------------------------------------------------
1 | //
2 | // GTMSynchronizationAsserts.h
3 | //
4 | // Copyright 2016 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | /*
20 | #if !__has_feature(objc_arc)
21 | #error "This file needs to be compiled with ARC enabled."
22 | #endif
23 | */
24 |
25 | #import
26 |
27 | #import "GTMDefines.h" // For _GTMDevAssert.
28 |
29 | // Macros to monitor synchronization blocks in debug builds.
30 | //
31 | // These report problems using _GTMDevAssert, which may be defined by the
32 | // project or by GTMDefines.h
33 | //
34 | // GTMMonitorSynchronized Start monitoring a top-level-only @sync scope.
35 | // Asserts if already inside a monitored @sync scope.
36 | // GTMMonitorRecursiveSynchronized Start monitoring a top-level or recursive @sync
37 | // scope.
38 | // GTMCheckSynchronized Assert that the current execution is inside a monitored @sync
39 | // scope.
40 | // GTMCheckNotSynchronized Assert that the current execution is not inside a monitored
41 | // @sync scope.
42 | //
43 | // Example usage:
44 | //
45 | // - (void)myExternalMethod {
46 | // @synchronized(self) {
47 | // GTMMonitorSynchronized(self)
48 | //
49 | // - (void)myInternalMethod {
50 | // GTMCheckSynchronized(self);
51 | //
52 | // - (void)callMyCallbacks {
53 | // GTMCheckNotSynchronized(self);
54 | //
55 | // GTMCheckNotSynchronized is available for verifying the code isn't
56 | // in a deadlockable @sync state, important when posting notifications and
57 | // invoking callbacks.
58 | //
59 | // Don't use GTMCheckNotSynchronized immediately before a @sync scope; the
60 | // normal recursiveness check of GTMMonitorSynchronized can catch those.
61 |
62 | #if DEBUG
63 |
64 | #define __GTMMonitorSynchronizedVariableInner(varname, counter) \
65 | varname ## counter
66 | #define __GTMMonitorSynchronizedVariable(varname, counter) \
67 | __GTMMonitorSynchronizedVariableInner(varname, counter)
68 |
69 | #define GTMMonitorSynchronized(obj) \
70 | NS_VALID_UNTIL_END_OF_SCOPE id \
71 | __GTMMonitorSynchronizedVariable(__monitor, __COUNTER__) = \
72 | [[GTMSyncMonitorInternal alloc] initWithSynchronizationObject:obj \
73 | allowRecursive:NO \
74 | functionName:__func__]
75 |
76 | #define GTMMonitorRecursiveSynchronized(obj) \
77 | NS_VALID_UNTIL_END_OF_SCOPE id \
78 | __GTMMonitorSynchronizedVariable(__monitor, __COUNTER__) = \
79 | [[GTMSyncMonitorInternal alloc] initWithSynchronizationObject:obj \
80 | allowRecursive:YES \
81 | functionName:__func__]
82 |
83 | #define GTMCheckSynchronized(obj) { \
84 | _GTMDevAssert( \
85 | [GTMSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \
86 | @"GTMCheckSynchronized(" #obj ") failed: not sync'd" \
87 | @" on " #obj " in %s. Call stack:\n%@", \
88 | __func__, [NSThread callStackSymbols]); \
89 | }
90 |
91 | #define GTMCheckNotSynchronized(obj) { \
92 | _GTMDevAssert( \
93 | ![GTMSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \
94 | @"GTMCheckNotSynchronized(" #obj ") failed: was sync'd" \
95 | @" on " #obj " in %s by %@. Call stack:\n%@", __func__, \
96 | [GTMSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \
97 | [NSThread callStackSymbols]); \
98 | }
99 |
100 | // GTMSyncMonitorInternal is a private class that keeps track of the
101 | // beginning and end of synchronized scopes, relying on ARC to release
102 | // it at the end of a scope.
103 | //
104 | // This class should not be used directly, but only via the
105 | // GTMMonitorSynchronized macro.
106 | @interface GTMSyncMonitorInternal : NSObject {
107 | NSValue *_objectKey; // The synchronize target object.
108 | const char *_functionName; // The function containing the monitored sync block.
109 | }
110 |
111 | - (instancetype)initWithSynchronizationObject:(id)object
112 | allowRecursive:(BOOL)allowRecursive
113 | functionName:(const char *)functionName;
114 | // Return the names of the functions that hold sync on the object, or nil if none.
115 | + (NSArray *)functionsHoldingSynchronizationOnObject:(id)object;
116 | @end
117 |
118 | #else
119 |
120 | // !DEBUG
121 | #define GTMMonitorSynchronized(obj) do { } while (0)
122 | #define GTMMonitorRecursiveSynchronized(obj) do { } while (0)
123 | #define GTMCheckSynchronized(obj) do { } while (0)
124 | #define GTMCheckNotSynchronized(obj) do { } while (0)
125 |
126 | #endif // DEBUG
127 |
--------------------------------------------------------------------------------
/GoldenPassport/Base.lproj/MainMenu.xib:
--------------------------------------------------------------------------------
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 |
100 |
101 |
102 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMLogger+ASL.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMLogger+ASL.m
3 | //
4 | // Copyright 2007-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMLogger+ASL.h"
20 | #import "GTMDefines.h"
21 |
22 |
23 | @implementation GTMLogger (GTMLoggerASLAdditions)
24 |
25 | + (id)standardLoggerWithASL {
26 | id me = [self standardLogger];
27 | [me setWriter:[[[GTMLogASLWriter alloc] init] autorelease]];
28 | [me setFormatter:[[[GTMLogASLFormatter alloc] init] autorelease]];
29 | return me;
30 | }
31 |
32 | @end
33 |
34 |
35 | @implementation GTMLogASLWriter
36 |
37 | + (id)aslWriter {
38 | return [[[self alloc] initWithClientClass:nil facility:nil] autorelease];
39 | }
40 |
41 | + (id)aslWriterWithFacility:(NSString *)facility {
42 | return [[[self alloc] initWithClientClass:nil facility:facility] autorelease];
43 | }
44 |
45 | - (id)init {
46 | return [self initWithClientClass:nil facility:nil];
47 | }
48 |
49 | - (id)initWithClientClass:(Class)clientClass facility:(NSString *)facility {
50 | if ((self = [super init])) {
51 | aslClientClass_ = clientClass;
52 | if (aslClientClass_ == nil) {
53 | aslClientClass_ = [GTMLoggerASLClient class];
54 | }
55 | facility_ = [facility copy];
56 | }
57 | return self;
58 | }
59 |
60 | - (void)dealloc {
61 | [facility_ release];
62 | [super dealloc];
63 | }
64 |
65 | - (void)logMessage:(NSString *)msg level:(GTMLoggerLevel)level {
66 | // Because |facility_| is an argument to asl_open() we must store a separate
67 | // one for each facility in thread-local storage.
68 | static NSString *const kASLClientKey = @"GTMLoggerASLClient";
69 | NSString *key = kASLClientKey;
70 | if (facility_) {
71 | key = [NSString stringWithFormat:@"GTMLoggerASLClient-%@", facility_];
72 | }
73 |
74 | // Lookup the ASL client in the thread-local storage dictionary
75 | NSMutableDictionary *tls = [[NSThread currentThread] threadDictionary];
76 | GTMLoggerASLClient *client = [tls objectForKey:key];
77 |
78 | // If the ASL client wasn't found (e.g., the first call from this thread),
79 | // then create it and store it in the thread-local storage dictionary
80 | if (client == nil) {
81 | client = [[[aslClientClass_ alloc] initWithFacility:facility_] autorelease];
82 | [tls setObject:client forKey:key];
83 | }
84 |
85 | // Map the GTMLoggerLevel level to an ASL level.
86 | int aslLevel = ASL_LEVEL_INFO;
87 | switch (level) {
88 | case kGTMLoggerLevelUnknown:
89 | case kGTMLoggerLevelDebug:
90 | case kGTMLoggerLevelInfo:
91 | aslLevel = ASL_LEVEL_NOTICE;
92 | break;
93 | case kGTMLoggerLevelError:
94 | aslLevel = ASL_LEVEL_ERR;
95 | break;
96 | case kGTMLoggerLevelAssert:
97 | aslLevel = ASL_LEVEL_ALERT;
98 | break;
99 | }
100 |
101 | [client log:msg level:aslLevel];
102 | }
103 |
104 | @end // GTMLogASLWriter
105 |
106 |
107 | @implementation GTMLogASLFormatter
108 |
109 | #if !defined(__clang__) && (__GNUC__*10+__GNUC_MINOR__ >= 42)
110 | // Some versions of GCC (4.2 and below AFAIK) aren't great about supporting
111 | // -Wmissing-format-attribute
112 | // when the function is anything more complex than foo(NSString *fmt, ...).
113 | // You see the error inside the function when you turn ... into va_args and
114 | // attempt to call another function (like vsprintf for example).
115 | // So we just shut off the warning for this function.
116 | #pragma GCC diagnostic ignored "-Wmissing-format-attribute"
117 | #endif // !__clang__
118 |
119 | - (NSString *)stringForFunc:(NSString *)func
120 | withFormat:(NSString *)fmt
121 | valist:(va_list)args
122 | level:(GTMLoggerLevel)level {
123 | return [NSString stringWithFormat:@"%@ %@",
124 | [self prettyNameForFunc:func],
125 | // |super| has guard for nil |fmt| and |args|
126 | [super stringForFunc:func withFormat:fmt valist:args level:level]];
127 | }
128 |
129 | #if !defined(__clang__) && (__GNUC__*10+__GNUC_MINOR__ >= 42)
130 | #pragma GCC diagnostic error "-Wmissing-format-attribute"
131 | #endif // !__clang__
132 |
133 | @end // GTMLogASLFormatter
134 |
135 |
136 | @implementation GTMLoggerASLClient
137 |
138 | - (id)init {
139 | return [self initWithFacility:nil];
140 | }
141 |
142 | - (id)initWithFacility:(NSString *)facility {
143 | if ((self = [super init])) {
144 | client_ = asl_open(NULL, [facility UTF8String], 0);
145 | if (client_ == NULL) {
146 | // COV_NF_START - no real way to test this
147 | [self release];
148 | return nil;
149 | // COV_NF_END
150 | }
151 | #if TARGET_OS_IPHONE
152 | // On iOS we need to flag the messages as available for read so
153 | // asl_search() can see our own output.
154 | msgOptions_ = asl_new(ASL_TYPE_MSG);
155 | if ((msgOptions_ == NULL) ||
156 | (asl_set(msgOptions_,
157 | ASL_KEY_READ_UID,
158 | [[NSString stringWithFormat:@"%d", getuid()] UTF8String]) != 0)) {
159 | // COV_NF_START - no real way to test this
160 | [self release];
161 | return nil;
162 | // COV_NF_END
163 | }
164 | #endif
165 | }
166 | return self;
167 | }
168 |
169 | - (void)dealloc {
170 | if (msgOptions_ != NULL) asl_free(msgOptions_);
171 | if (client_ != NULL) asl_close(client_);
172 | [super dealloc];
173 | }
174 |
175 | // We don't test this one line because we don't want to pollute actual system
176 | // logs with test messages.
177 | // COV_NF_START
178 | - (void)log:(NSString *)msg level:(int)level {
179 | asl_log(client_, msgOptions_, level, "%s", [msg UTF8String]);
180 | }
181 | // COV_NF_END
182 |
183 | @end // GTMLoggerASLClient
184 |
--------------------------------------------------------------------------------
/GoldenPassport/google-toolbox-for-mac/GTMNSString+XML.m:
--------------------------------------------------------------------------------
1 | //
2 | // GTMNSString+XML.m
3 | //
4 | // Copyright 2007-2008 Google Inc.
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 | // use this file except in compliance with the License. You may obtain a copy
8 | // of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 | // License for the specific language governing permissions and limitations under
16 | // the License.
17 | //
18 |
19 | #import "GTMDefines.h"
20 | #import "GTMNSString+XML.h"
21 |
22 | // Export a nonsense symbol to suppress a libtool warning when this is linked alone in a static lib.
23 | __attribute__((visibility("default")))
24 | char NSString_GTMNSStringXMLAdditionsExportToSuppressLibToolWarning = 0;
25 |
26 | enum {
27 | kGTMXMLCharModeEncodeQUOT = 0,
28 | kGTMXMLCharModeEncodeAMP = 1,
29 | kGTMXMLCharModeEncodeAPOS = 2,
30 | kGTMXMLCharModeEncodeLT = 3,
31 | kGTMXMLCharModeEncodeGT = 4,
32 | kGTMXMLCharModeValid = 99,
33 | kGTMXMLCharModeInvalid = 100,
34 | };
35 | typedef NSUInteger GTMXMLCharMode;
36 |
37 | static NSString *gXMLEntityList[] = {
38 | // this must match the above order
39 | @""",
40 | @"&",
41 | @"'",
42 | @"<",
43 | @">",
44 | };
45 |
46 | GTM_INLINE GTMXMLCharMode XMLModeForUnichar(UniChar c) {
47 |
48 | // Per XML spec Section 2.2 Characters
49 | // ( http://www.w3.org/TR/REC-xml/#charsets )
50 | //
51 | // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
52 | // [#x10000-#x10FFFF]
53 |
54 | if (c <= 0xd7ff) {
55 | if (c >= 0x20) {
56 | switch (c) {
57 | case 34:
58 | return kGTMXMLCharModeEncodeQUOT;
59 | case 38:
60 | return kGTMXMLCharModeEncodeAMP;
61 | case 39:
62 | return kGTMXMLCharModeEncodeAPOS;
63 | case 60:
64 | return kGTMXMLCharModeEncodeLT;
65 | case 62:
66 | return kGTMXMLCharModeEncodeGT;
67 | default:
68 | return kGTMXMLCharModeValid;
69 | }
70 | } else {
71 | if (c == '\n')
72 | return kGTMXMLCharModeValid;
73 | if (c == '\r')
74 | return kGTMXMLCharModeValid;
75 | if (c == '\t')
76 | return kGTMXMLCharModeValid;
77 | return kGTMXMLCharModeInvalid;
78 | }
79 | }
80 |
81 | if (c < 0xE000)
82 | return kGTMXMLCharModeInvalid;
83 |
84 | if (c <= 0xFFFD)
85 | return kGTMXMLCharModeValid;
86 |
87 | // UniChar can't have the following values
88 | // if (c < 0x10000)
89 | // return kGTMXMLCharModeInvalid;
90 | // if (c <= 0x10FFFF)
91 | // return kGTMXMLCharModeValid;
92 |
93 | return kGTMXMLCharModeInvalid;
94 | } // XMLModeForUnichar
95 |
96 |
97 | static NSString *AutoreleasedCloneForXML(NSString *src, BOOL escaping) {
98 | //
99 | // NOTE:
100 | // We don't use CFXMLCreateStringByEscapingEntities because it's busted in
101 | // 10.3 (http://lists.apple.com/archives/Cocoa-dev/2004/Nov/msg00059.html) and
102 | // it doesn't do anything about the chars that are actually invalid per the
103 | // xml spec.
104 | //
105 |
106 | // we can't use the CF call here because it leaves the invalid chars
107 | // in the string.
108 | NSUInteger length = [src length];
109 | if (!length) {
110 | return src;
111 | }
112 |
113 | NSMutableString *finalString = [NSMutableString string];
114 |
115 | // this block is common between GTMNSString+HTML and GTMNSString+XML but
116 | // it's so short that it isn't really worth trying to share.
117 | const UniChar *buffer = CFStringGetCharactersPtr((CFStringRef)src);
118 | if (!buffer) {
119 | // We want this buffer to be autoreleased.
120 | NSMutableData *data = [NSMutableData dataWithLength:length * sizeof(UniChar)];
121 | if (!data) {
122 | // COV_NF_START - Memory fail case
123 | _GTMDevLog(@"couldn't alloc buffer");
124 | return nil;
125 | // COV_NF_END
126 | }
127 | [src getCharacters:[data mutableBytes]];
128 | buffer = [data bytes];
129 | }
130 |
131 | const UniChar *goodRun = buffer;
132 | NSUInteger goodRunLength = 0;
133 |
134 | for (NSUInteger i = 0; i < length; ++i) {
135 |
136 | GTMXMLCharMode cMode = XMLModeForUnichar(buffer[i]);
137 |
138 | // valid chars go as is, and if we aren't doing entities, then
139 | // everything goes as is.
140 | if ((cMode == kGTMXMLCharModeValid) ||
141 | (!escaping && (cMode != kGTMXMLCharModeInvalid))) {
142 | // goes as is
143 | goodRunLength += 1;
144 | } else {
145 | // it's something we have to encode or something invalid
146 |
147 | // start by adding what we already collected (if anything)
148 | if (goodRunLength) {
149 | CFStringAppendCharacters((CFMutableStringRef)finalString,
150 | goodRun,
151 | goodRunLength);
152 | goodRunLength = 0;
153 | }
154 |
155 | // if it wasn't invalid, add the encoded version
156 | if (cMode != kGTMXMLCharModeInvalid) {
157 | // add this encoded
158 | [finalString appendString:gXMLEntityList[cMode]];
159 | }
160 |
161 | // update goodRun to point to the next UniChar
162 | goodRun = buffer + i + 1;
163 | }
164 | }
165 |
166 | // anything left to add?
167 | if (goodRunLength) {
168 | CFStringAppendCharacters((CFMutableStringRef)finalString,
169 | goodRun,
170 | goodRunLength);
171 | }
172 | return finalString;
173 | } // AutoreleasedCloneForXML
174 |
175 | @implementation NSString (GTMNSStringXMLAdditions)
176 |
177 | - (NSString *)gtm_stringBySanitizingAndEscapingForXML {
178 | return AutoreleasedCloneForXML(self, YES);
179 | } // gtm_stringBySanitizingAndEscapingForXML
180 |
181 | - (NSString *)gtm_stringBySanitizingToXMLSpec {
182 | return AutoreleasedCloneForXML(self, NO);
183 | } // gtm_stringBySanitizingToXMLSpec
184 |
185 | @end
186 |
--------------------------------------------------------------------------------