diff --git a/attic/Buffer.hpp b/attic/Buffer.hpp deleted file mode 100644 index 6696dea8c..000000000 --- a/attic/Buffer.hpp +++ /dev/null @@ -1,463 +0,0 @@ -/* - * Copyright (c)2013-2020 ZeroTier, Inc. - * - * Use of this software is governed by the Business Source License included - * in the LICENSE.TXT file in the project's root directory. - * - * Change Date: 2024-01-01 - * - * On the date above, in accordance with the Business Source License, use - * of this software will be governed by version 2.0 of the Apache License. - */ -/****/ - -#ifndef ZT_BUFFER_HPP -#define ZT_BUFFER_HPP - -#include -#include - -#include -#include -#include -#include - -#include "Constants.hpp" -#include "Utils.hpp" - -#if defined(__GNUC__) && (!defined(ZT_NO_UNALIGNED_ACCESS)) -#define ZT_VAR_MAY_ALIAS __attribute__((__may_alias__)) -#else -#define ZT_VAR_MAY_ALIAS -#endif - -namespace ZeroTier { - -/** - * A variable length but statically allocated buffer - * - * Bounds-checking is done everywhere, since this is used in security - * critical code. This supports construction and assignment from buffers - * of differing capacities, provided the data actually in them fits. - * It throws std::out_of_range on any boundary violation. - * - * The at(), append(), etc. methods encode integers larger than 8-bit in - * big-endian (network) byte order. - * - * @tparam C Total capacity - */ -template -class Buffer -{ - // I love me! - template friend class Buffer; - -public: - // STL container idioms - typedef unsigned char value_type; - typedef unsigned char * pointer; - typedef const char * const_pointer; - typedef char & reference; - typedef const char & const_reference; - typedef char * iterator; - typedef const char * const_iterator; - typedef unsigned int size_type; - typedef int difference_type; - typedef std::reverse_iterator reverse_iterator; - typedef std::reverse_iterator const_reverse_iterator; - - inline iterator begin() { return _b; } - inline iterator end() { return (_b + _l); } - inline const_iterator begin() const { return _b; } - inline const_iterator end() const { return (_b + _l); } - inline reverse_iterator rbegin() { return reverse_iterator(begin()); } - inline reverse_iterator rend() { return reverse_iterator(end()); } - inline const_reverse_iterator rbegin() const { return const_reverse_iterator(begin()); } - inline const_reverse_iterator rend() const { return const_reverse_iterator(end()); } - - inline Buffer() : - _l(0) - { - } - - inline Buffer(const unsigned int l) - { - if (l > C) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - _l = l; - } - - template - inline Buffer(const Buffer &b) - { - *this = b; - } - - inline Buffer(const void *b,unsigned int l) - { - copyFrom(b,l); - } - - template - inline Buffer &operator=(const Buffer &b) - { - if (unlikely(b._l > C)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - if (C2 == C) { - memcpy(this,&b,sizeof(Buffer)); - } else { - memcpy(_b,b._b,_l = b._l); - } - return *this; - } - - inline void copyFrom(const void *b,unsigned int l) - { - if (unlikely(l > C)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - memcpy(_b,b,l); - _l = l; - } - - unsigned char operator[](const unsigned int i) const - { - if (unlikely(i >= _l)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - return (unsigned char)_b[i]; - } - - unsigned char &operator[](const unsigned int i) - { - if (unlikely(i >= _l)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - return ((unsigned char *)_b)[i]; - } - - /** - * Get a raw pointer to a field with bounds checking - * - * This isn't perfectly safe in that the caller could still overflow - * the pointer, but its use provides both a sanity check and - * documentation / reminder to the calling code to treat the returned - * pointer as being of size [l]. - * - * @param i Index of field in buffer - * @param l Length of field in bytes - * @return Pointer to field data - * @throws std::out_of_range Field extends beyond data size - */ - unsigned char *field(unsigned int i,unsigned int l) - { - if (unlikely((i + l) > _l)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - return (unsigned char *)(_b + i); - } - const unsigned char *field(unsigned int i,unsigned int l) const - { - if (unlikely((i + l) > _l)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - return (const unsigned char *)(_b + i); - } - - /** - * Place a primitive integer value at a given position - * - * @param i Index to place value - * @param v Value - * @tparam T Integer type (e.g. uint16_t, int64_t) - */ - template - inline void setAt(unsigned int i,const T v) - { - if (unlikely((i + sizeof(T)) > _l)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; -#ifdef ZT_NO_UNALIGNED_ACCESS - uint8_t *p = reinterpret_cast(_b + i); - for(unsigned int x=1;x<=sizeof(T);++x) - *(p++) = (uint8_t)(v >> (8 * (sizeof(T) - x))); -#else - T *const ZT_VAR_MAY_ALIAS p = reinterpret_cast(_b + i); - *p = Utils::hton(v); -#endif - } - - /** - * Get a primitive integer value at a given position - * - * @param i Index to get integer - * @tparam T Integer type (e.g. uint16_t, int64_t) - * @return Integer value - */ - template - inline T at(unsigned int i) const - { - if (unlikely((i + sizeof(T)) > _l)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; -#ifdef ZT_NO_UNALIGNED_ACCESS - T v = 0; - const uint8_t *p = reinterpret_cast(_b + i); - for(unsigned int x=0;x(_b + i); - return Utils::ntoh(*p); -#endif - } - - /** - * Append an integer type to this buffer - * - * @param v Value to append - * @tparam T Integer type (e.g. uint16_t, int64_t) - * @throws std::out_of_range Attempt to append beyond capacity - */ - template - inline void append(const T v) - { - if (unlikely((_l + sizeof(T)) > C)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; -#ifdef ZT_NO_UNALIGNED_ACCESS - uint8_t *p = reinterpret_cast(_b + _l); - for(unsigned int x=1;x<=sizeof(T);++x) - *(p++) = (uint8_t)(v >> (8 * (sizeof(T) - x))); -#else - T *const ZT_VAR_MAY_ALIAS p = reinterpret_cast(_b + _l); - *p = Utils::hton(v); -#endif - _l += sizeof(T); - } - - /** - * Append a run of bytes - * - * @param c Character value to append - * @param n Number of times to append - * @throws std::out_of_range Attempt to append beyond capacity - */ - inline void append(uint8_t c,unsigned int n) - { - if (unlikely((_l + n) > C)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - for(unsigned int i=0;i C)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - Utils::getSecureRandom(_b + _l,n); - _l += n; - } - - /** - * Append a C-array of bytes - * - * @param b Data - * @param l Length - * @throws std::out_of_range Attempt to append beyond capacity - */ - inline void append(const void *b,unsigned int l) - { - if (unlikely((_l + l) > C)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - memcpy(_b + _l,b,l); - _l += l; - } - - /** - * Append a C string including null termination byte - * - * @param s C string - * @throws std::out_of_range Attempt to append beyond capacity - */ - inline void appendCString(const char *s) - { - for(;;) { - if (unlikely(_l >= C)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - if (!(_b[_l++] = *(s++))) - break; - } - } - - /** - * Append a buffer - * - * @param b Buffer to append - * @tparam C2 Capacity of second buffer (typically inferred) - * @throws std::out_of_range Attempt to append beyond capacity - */ - template - inline void append(const Buffer &b) - { - append(b._b,b._l); - } - - /** - * Increment size and return pointer to field of specified size - * - * Nothing is actually written to the memory. This is a shortcut - * for addSize() followed by field() to reference the previous - * position and the new size. - * - * @param l Length of field to append - * @return Pointer to beginning of appended field of length 'l' - */ - inline char *appendField(unsigned int l) - { - if (unlikely((_l + l) > C)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - char *r = _b + _l; - _l += l; - return r; - } - - /** - * Increment size by a given number of bytes - * - * The contents of new space are undefined. - * - * @param i Bytes to increment - * @throws std::out_of_range Capacity exceeded - */ - inline void addSize(unsigned int i) - { - if (unlikely((i + _l) > C)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - _l += i; - } - - /** - * Set size of data in buffer - * - * The contents of new space are undefined. - * - * @param i New size - * @throws std::out_of_range Size larger than capacity - */ - inline void setSize(const unsigned int i) - { - if (unlikely(i > C)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - _l = i; - } - - /** - * Move everything after 'at' to the buffer's front and truncate - * - * @param at Truncate before this position - * @throws std::out_of_range Position is beyond size of buffer - */ - inline void behead(const unsigned int at) - { - if (!at) - return; - if (unlikely(at > _l)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - ::memmove(_b,_b + at,_l -= at); - } - - /** - * Erase something from the middle of the buffer - * - * @param start Starting position - * @param length Length of block to erase - * @throws std::out_of_range Position plus length is beyond size of buffer - */ - inline void erase(const unsigned int at,const unsigned int length) - { - const unsigned int endr = at + length; - if (unlikely(endr > _l)) - throw ZT_EXCEPTION_OUT_OF_BOUNDS; - ::memmove(_b + at,_b + endr,_l - endr); - _l -= length; - } - - /** - * Set buffer data length to zero - */ - inline void clear() { _l = 0; } - - /** - * Zero buffer up to size() - */ - inline void zero() { memset(_b,0,_l); } - - /** - * Zero unused capacity area - */ - inline void zeroUnused() { memset(_b + _l,0,C - _l); } - - /** - * Unconditionally and securely zero buffer's underlying memory - */ - inline void burn() { Utils::burn(_b,sizeof(_b)); } - - /** - * @return Constant pointer to data in buffer - */ - inline const void *data() const { return _b; } - - /** - * @return Non-constant pointer to data in buffer - */ - inline void *unsafeData() { return _b; } - - /** - * @return Size of data in buffer - */ - inline unsigned int size() const { return _l; } - - /** - * @return Capacity of buffer - */ - inline unsigned int capacity() const { return C; } - - template - inline bool operator==(const Buffer &b) const - { - return ((_l == b._l)&&(!memcmp(_b,b._b,_l))); - } - template - inline bool operator!=(const Buffer &b) const - { - return ((_l != b._l)||(memcmp(_b,b._b,_l))); - } - template - inline bool operator<(const Buffer &b) const - { - return (memcmp(_b,b._b,std::min(_l,b._l)) < 0); - } - template - inline bool operator>(const Buffer &b) const - { - return (b < *this); - } - template - inline bool operator<=(const Buffer &b) const - { - return !(b < *this); - } - template - inline bool operator>=(const Buffer &b) const - { - return !(*this < b); - } - -private: - char ZT_VAR_MAY_ALIAS _b[C]; - unsigned int _l; -}; - -} // namespace ZeroTier - -#endif diff --git a/attic/Fingerprint.hpp b/attic/Fingerprint.hpp deleted file mode 100644 index 27d344c88..000000000 --- a/attic/Fingerprint.hpp +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c)2013-2020 ZeroTier, Inc. - * - * Use of this software is governed by the Business Source License included - * in the LICENSE.TXT file in the project's root directory. - * - * Change Date: 2024-01-01 - * - * On the date above, in accordance with the Business Source License, use - * of this software will be governed by version 2.0 of the Apache License. - */ -/****/ - -#ifndef ZT_FINGERPRINT_HPP -#define ZT_FINGERPRINT_HPP - -#include "Constants.hpp" -#include "Identity.hpp" - -namespace ZeroTier { - -/** - * A short address and a longer identity hash for extra confirmation of a node's identity. - */ -struct Fingerprint -{ - ZT_ALWAYS_INLINE Fingerprint() : address() { memset(hash,0,ZT_IDENTITY_HASH_SIZE); } - explicit ZT_ALWAYS_INLINE Fingerprint(const Identity &id) : address(id.address()) { memcpy(hash,id.hash(),ZT_IDENTITY_HASH_SIZE); } - - ZT_ALWAYS_INLINE Fingerprint &operator=(const Identity &id) - { - address = id.address(); - memcpy(hash,id.hash(),ZT_IDENTITY_HASH_SIZE); - return *this; - } - - ZT_ALWAYS_INLINE bool operator==(const Fingerprint &fp) const { return ((address == fp.address)&&(memcmp(hash,fp.hash,ZT_IDENTITY_HASH_SIZE) == 0)); } - ZT_ALWAYS_INLINE bool operator!=(const Fingerprint &fp) const { return ((address != fp.address)||(memcmp(hash,fp.hash,ZT_IDENTITY_HASH_SIZE) != 0)); } - ZT_ALWAYS_INLINE bool operator<(const Fingerprint &fp) const { return ((address < fp.address)||((address == fp.address)&&(memcmp(hash,fp.hash,ZT_IDENTITY_HASH_SIZE) < 0))); } - ZT_ALWAYS_INLINE bool operator>(const Fingerprint &fp) const { return (fp < *this); } - ZT_ALWAYS_INLINE bool operator<=(const Fingerprint &fp) const { return !(fp < *this); } - ZT_ALWAYS_INLINE bool operator>=(const Fingerprint &fp) const { return !(*this < fp); } - - ZT_ALWAYS_INLINE bool operator==(const Identity &id) const { return ((address == id.address())&&(memcmp(hash,id.hash(),ZT_IDENTITY_HASH_SIZE) == 0)); } - ZT_ALWAYS_INLINE bool operator!=(const Identity &id) const { return ((address != id.address())||(memcmp(hash,id.hash(),ZT_IDENTITY_HASH_SIZE) != 0)); } - ZT_ALWAYS_INLINE bool operator<(const Identity &id) const { return ((address < id.address())||((address == id.address())&&(memcmp(hash,id.hash(),ZT_IDENTITY_HASH_SIZE) < 0))); } - ZT_ALWAYS_INLINE bool operator>(const Identity &id) const { return (Fingerprint(id) < *this); } - ZT_ALWAYS_INLINE bool operator<=(const Identity &id) const { return !(Fingerprint(id) < *this); } - ZT_ALWAYS_INLINE bool operator>=(const Identity &id) const { return !(*this < id); } - - ZT_ALWAYS_INLINE operator bool() const { return (address); } - - /** - * Short ZeroTier address - */ - Address address; - - /** - * SHA-384 hash of public portions of identity key(s) - */ - uint8_t hash[ZT_IDENTITY_HASH_SIZE]; -}; - -} // namespace ZeroTier - -#endif diff --git a/attic/RingBuffer.hpp b/attic/RingBuffer.hpp deleted file mode 100644 index de086fe88..000000000 --- a/attic/RingBuffer.hpp +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (c)2013-2020 ZeroTier, Inc. - * - * Use of this software is governed by the Business Source License included - * in the LICENSE.TXT file in the project's root directory. - * - * Change Date: 2024-01-01 - * - * On the date above, in accordance with the Business Source License, use - * of this software will be governed by version 2.0 of the Apache License. - */ -/****/ - -#ifndef ZT_RINGBUFFER_H -#define ZT_RINGBUFFER_H - -#include -#include -#include -#include -#include - -namespace ZeroTier { - -/** - * A circular buffer - * - * For fast handling of continuously-evolving variables (such as path quality metrics). - * Using this, we can maintain longer sliding historical windows for important path - * metrics without the need for potentially expensive calls to memcpy/memmove. - * - * Some basic statistical functionality is implemented here in an attempt - * to reduce the complexity of code needed to interact with this type of buffer. - */ -template -class RingBuffer -{ -private: - T buf[S]; - size_t begin; - size_t end; - bool wrap; - -public: - inline RingBuffer() : - begin(0), - end(0), - wrap(false) - { - memset(buf,0,sizeof(T)*S); - } - - /** - * @return A pointer to the underlying buffer - */ - inline T *get_buf() - { - return buf + begin; - } - - /** - * Adjust buffer index pointer as if we copied data in - * @param n Number of elements to copy in - * @return Number of elements we copied in - */ - inline size_t produce(size_t n) - { - n = std::min(n, getFree()); - if (n == 0) { - return n; - } - const size_t first_chunk = std::min(n, S - end); - end = (end + first_chunk) % S; - if (first_chunk < n) { - const size_t second_chunk = n - first_chunk; - end = (end + second_chunk) % S; - } - if (begin == end) { - wrap = true; - } - return n; - } - - /** - * Fast erase, O(1). - * Merely reset the buffer pointer, doesn't erase contents - */ - inline void reset() { consume(count()); } - - /** - * adjust buffer index pointer as if we copied data out - * @param n Number of elements we copied from the buffer - * @return Number of elements actually available from the buffer - */ - inline size_t consume(size_t n) - { - n = std::min(n, count()); - if (n == 0) { - return n; - } - if (wrap) { - wrap = false; - } - const size_t first_chunk = std::min(n, S - begin); - begin = (begin + first_chunk) % S; - if (first_chunk < n) { - const size_t second_chunk = n - first_chunk; - begin = (begin + second_chunk) % S; - } - return n; - } - - /** - * @param data Buffer that is to be written to the ring - * @param n Number of elements to write to the buffer - */ - inline size_t write(const T * data, size_t n) - { - n = std::min(n, getFree()); - if (n == 0) { - return n; - } - const size_t first_chunk = std::min(n, S - end); - memcpy(buf + end, data, first_chunk * sizeof(T)); - end = (end + first_chunk) % S; - if (first_chunk < n) { - const size_t second_chunk = n - first_chunk; - memcpy(buf + end, data + first_chunk, second_chunk * sizeof(T)); - end = (end + second_chunk) % S; - } - if (begin == end) { - wrap = true; - } - return n; - } - - /** - * Place a single value on the buffer. If the buffer is full, consume a value first. - * - * @param value A single value to be placed in the buffer - */ - inline void push(const T value) - { - if (count() == S) { - consume(1); - } - const size_t first_chunk = std::min((size_t)1, S - end); - *(buf + end) = value; - end = (end + first_chunk) % S; - if (begin == end) { - wrap = true; - } - } - - /** - * @return The most recently pushed element on the buffer - */ - inline T get_most_recent() { return *(buf + end); } - - /** - * @param dest Destination buffer - * @param n Size (in terms of number of elements) of the destination buffer - * @return Number of elements read from the buffer - */ - inline size_t read(T *dest,size_t n) - { - n = std::min(n, count()); - if (n == 0) { - return n; - } - if (wrap) { - wrap = false; - } - const size_t first_chunk = std::min(n, S - begin); - memcpy(dest, buf + begin, first_chunk * sizeof(T)); - begin = (begin + first_chunk) % S; - if (first_chunk < n) { - const size_t second_chunk = n - first_chunk; - memcpy(dest + first_chunk, buf + begin, second_chunk * sizeof(T)); - begin = (begin + second_chunk) % S; - } - return n; - } - - /** - * Return how many elements are in the buffer, O(1). - * - * @return The number of elements in the buffer - */ - inline size_t count() - { - if (end == begin) { - return wrap ? S : 0; - } - else if (end > begin) { - return end - begin; - } - else { - return S + end - begin; - } - } - - /** - * @return The number of slots that are unused in the buffer - */ - inline size_t getFree() { return S - count(); } - - /** - * @return The arithmetic mean of the contents of the buffer - */ - inline float mean() - { - size_t iterator = begin; - float subtotal = 0; - size_t curr_cnt = count(); - for (size_t i=0; i -#include -#include - -namespace ZeroTier { - -/** - * Tiny vector with a static base capacity for allocation-free operation at small sizes - * - * This doesn't support all of std::vector, uses low-level memcpy to relocate things, and - * lacks bounds checking. It's only intended for uses where a minimal subset of the vector - * container is needed, the objects are primitive or safe to handle in this way, and the - * number of items is typically less than or equal to some statically definable value. - * - * Examples of safe objects for this include primitive types, Str, SharedPtr, InetAddress, - * Address, MAC, etc. - * - * @tparam T Type to encapsulate - * @tparam BASE Base number of items to allocate storage inside the object itself (default: 4) - */ -template -class TinyVector -{ -public: - typedef unsigned long size_t; - typedef T * iterator; - typedef const T * const_iterator; - typedef T & reference; - typedef const T & const_reference; - - ZT_ALWAYS_INLINE TinyVector() : - _v((void *)_baseMem), - _c(BASE), - _l(0) - { - } - - ZT_ALWAYS_INLINE TinyVector(const TinyVector &vec) : - _v((void *)_baseMem), - _c(BASE), - _l(0) - { - *this = vec; - } - - ZT_ALWAYS_INLINE ~TinyVector() - { - clear(); - if (_v != (void *)_baseMem) - free(_v); - } - - ZT_ALWAYS_INLINE TinyVector &operator=(const TinyVector &vec) - { - unsigned long i = 0; - if (_l < vec._l) { - while (i < _l) { - reinterpret_cast(_v)[i] = reinterpret_cast(vec._v)[i]; - ++i; - } - - if (vec._l > _c) { - unsigned long nc = vec._c; - void *nv; - if (_v == (void *)_baseMem) { - nv = malloc(nc); - memcpy(nv,_v,sizeof(T) * _l); - } else { - nv = realloc(_v,nc); - if (!nv) - throw std::bad_alloc(); - } - _v = nv; - _c = nc; - } - - while (i < vec._l) { - new (reinterpret_cast(_v) + i) T(reinterpret_cast(vec._v)[i]); - ++i; - } - } else { - while (i < vec._l) { - reinterpret_cast(_v)[i] = reinterpret_cast(vec._v)[i]; - ++i; - } - if (!Utils::isPrimitiveType()) { - while (i < _l) - reinterpret_cast(_v)[i++]->~T(); - } - } - _l = vec._l; - } - - ZT_ALWAYS_INLINE void clear() - { - if (!Utils::isPrimitiveType()) { - for (unsigned long i = 0; i < _l; ++i) - reinterpret_cast(_v)[i]->~T(); - } - _l = 0; - } - - ZT_ALWAYS_INLINE void push_back(const T &v) - { - if (_l >= _c) { - unsigned long nc = _c << 1U; - void *nv; - if (_v == (void *)_baseMem) { - nv = malloc(sizeof(T) * nc); - memcpy(nv,_v,sizeof(T) * _l); - } else { - nv = realloc(_v,sizeof(T) * nc); - if (!nv) - throw std::bad_alloc(); - } - _v = nv; - _c = nc; - } - new (reinterpret_cast(_v) + _l++) T(v); - } - - ZT_ALWAYS_INLINE void pop_back() - { - if (!Utils::isPrimitiveType()) - reinterpret_cast(_v)[_l]->~T(); - --_l; - } - - ZT_ALWAYS_INLINE reference front() { reinterpret_cast(_v)[0]; } - ZT_ALWAYS_INLINE const_reference front() const { reinterpret_cast(_v)[0]; } - ZT_ALWAYS_INLINE reference back() { reinterpret_cast(_v)[_l - 1]; } - ZT_ALWAYS_INLINE const_reference back() const { reinterpret_cast(_v)[_l - 1]; } - - ZT_ALWAYS_INLINE unsigned long size() const { return _l; } - ZT_ALWAYS_INLINE bool empty() const { return (_l == 0); } - - ZT_ALWAYS_INLINE iterator begin() { return reinterpret_cast(_v); } - ZT_ALWAYS_INLINE iterator end() { return (reinterpret_cast(_v) + _l); } - ZT_ALWAYS_INLINE const_iterator begin() const { return reinterpret_cast(_v); } - ZT_ALWAYS_INLINE const_iterator end() const { return (reinterpret_cast(_v) + _l); } - - ZT_ALWAYS_INLINE T *data() { return reinterpret_cast(_v); } - ZT_ALWAYS_INLINE const T *data() const { return reinterpret_cast(_v); } - - ZT_ALWAYS_INLINE reference operator[](const unsigned long i) { return reinterpret_cast(_v)[i]; } - ZT_ALWAYS_INLINE const_reference operator[](const unsigned long i) const { return reinterpret_cast(_v)[i]; } - ZT_ALWAYS_INLINE reference at(const unsigned long i) { return reinterpret_cast(_v)[i]; } - ZT_ALWAYS_INLINE const_reference at(const unsigned long i) const { return reinterpret_cast(_v)[i]; } - -private: - uint8_t _baseMem[BASE * sizeof(T)]; - void *_v; - unsigned long _c; - unsigned long _l; -}; - -} // namespace ZeroTier - -#endif diff --git a/attic/macui/ZeroTier One.xcodeproj/project.pbxproj b/attic/macui/ZeroTier One.xcodeproj/project.pbxproj deleted file mode 100644 index fc5cfc1fb..000000000 --- a/attic/macui/ZeroTier One.xcodeproj/project.pbxproj +++ /dev/null @@ -1,382 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 932D472F1D1CD499004BCFE2 /* ZeroTierIcon.icns in Resources */ = {isa = PBXBuildFile; fileRef = 932D472E1D1CD499004BCFE2 /* ZeroTierIcon.icns */; }; - 932D47331D1CD861004BCFE2 /* PreferencesViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 932D47311D1CD861004BCFE2 /* PreferencesViewController.xib */; }; - 932D47371D1CDC9B004BCFE2 /* AboutViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 932D47351D1CDC9B004BCFE2 /* AboutViewController.xib */; }; - 93326BDE1CE7C816005CA2AC /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 93326BDD1CE7C816005CA2AC /* Assets.xcassets */; }; - 93326BE11CE7C816005CA2AC /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 93326BDF1CE7C816005CA2AC /* MainMenu.xib */; }; - 93326BEB1CE7D9B9005CA2AC /* JoinNetworkViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 93326BE91CE7D9B9005CA2AC /* JoinNetworkViewController.xib */; }; - 93326BEF1CE7DA30005CA2AC /* ShowNetworksViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 93326BED1CE7DA30005CA2AC /* ShowNetworksViewController.xib */; }; - 93D1675F1D54191C00330C99 /* NodeStatus.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D1675E1D54191C00330C99 /* NodeStatus.m */; }; - 93D167621D541BC200330C99 /* ServiceCom.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D167611D541BC200330C99 /* ServiceCom.m */; }; - 93D167661D54308200330C99 /* Network.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D167651D54308200330C99 /* Network.m */; }; - 93D167691D57E7EA00330C99 /* AboutViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D167681D57E7EA00330C99 /* AboutViewController.m */; }; - 93D1676D1D57EB8400330C99 /* PreferencesViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D1676C1D57EB8400330C99 /* PreferencesViewController.m */; }; - 93D167701D57FD3800330C99 /* NetworkMonitor.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D1676F1D57FD3800330C99 /* NetworkMonitor.m */; }; - 93D167731D58093C00330C99 /* NetworkInfoCell.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D167721D58093C00330C99 /* NetworkInfoCell.m */; }; - 93D167761D580C3500330C99 /* ShowNetworksViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D167751D580C3500330C99 /* ShowNetworksViewController.m */; }; - 93D167791D5815E600330C99 /* JoinNetworkViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D167781D5815E600330C99 /* JoinNetworkViewController.m */; }; - 93D1677C1D58228A00330C99 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D1677B1D58228A00330C99 /* AppDelegate.m */; }; - 93D1679B1D58300F00330C99 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 93D1679A1D58300F00330C99 /* main.m */; }; - 93D1679D1D595F0000330C99 /* WebKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 93D1679C1D595F0000330C99 /* WebKit.framework */; }; - 93DAFB271D3F0BEE004D5417 /* about.html in Resources */ = {isa = PBXBuildFile; fileRef = 93DAFB261D3F0BEE004D5417 /* about.html */; }; - 93DAFE4B1CFE53CA00547CC4 /* AuthtokenCopy.m in Sources */ = {isa = PBXBuildFile; fileRef = 93DAFE4A1CFE53CA00547CC4 /* AuthtokenCopy.m */; }; -/* End PBXBuildFile section */ - -/* Begin PBXFileReference section */ - 932D472E1D1CD499004BCFE2 /* ZeroTierIcon.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; path = ZeroTierIcon.icns; sourceTree = ""; }; - 932D47311D1CD861004BCFE2 /* PreferencesViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = PreferencesViewController.xib; sourceTree = ""; }; - 932D47351D1CDC9B004BCFE2 /* AboutViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = AboutViewController.xib; sourceTree = ""; }; - 93326BD81CE7C816005CA2AC /* ZeroTier One.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "ZeroTier One.app"; sourceTree = BUILT_PRODUCTS_DIR; }; - 93326BDD1CE7C816005CA2AC /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 93326BE01CE7C816005CA2AC /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; - 93326BE21CE7C816005CA2AC /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 93326BE91CE7D9B9005CA2AC /* JoinNetworkViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = JoinNetworkViewController.xib; sourceTree = ""; }; - 93326BED1CE7DA30005CA2AC /* ShowNetworksViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = ShowNetworksViewController.xib; sourceTree = ""; }; - 93D1675D1D54191C00330C99 /* NodeStatus.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NodeStatus.h; sourceTree = ""; }; - 93D1675E1D54191C00330C99 /* NodeStatus.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NodeStatus.m; sourceTree = ""; }; - 93D167601D541BC200330C99 /* ServiceCom.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ServiceCom.h; sourceTree = ""; }; - 93D167611D541BC200330C99 /* ServiceCom.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ServiceCom.m; sourceTree = ""; }; - 93D167641D54308200330C99 /* Network.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Network.h; sourceTree = ""; }; - 93D167651D54308200330C99 /* Network.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Network.m; sourceTree = ""; }; - 93D167671D57E7EA00330C99 /* AboutViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AboutViewController.h; sourceTree = ""; }; - 93D167681D57E7EA00330C99 /* AboutViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AboutViewController.m; sourceTree = ""; }; - 93D1676B1D57EB8400330C99 /* PreferencesViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PreferencesViewController.h; sourceTree = ""; }; - 93D1676C1D57EB8400330C99 /* PreferencesViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PreferencesViewController.m; sourceTree = ""; }; - 93D1676E1D57FD3800330C99 /* NetworkMonitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NetworkMonitor.h; sourceTree = ""; }; - 93D1676F1D57FD3800330C99 /* NetworkMonitor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NetworkMonitor.m; sourceTree = ""; }; - 93D167711D58093C00330C99 /* NetworkInfoCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NetworkInfoCell.h; sourceTree = ""; }; - 93D167721D58093C00330C99 /* NetworkInfoCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NetworkInfoCell.m; sourceTree = ""; }; - 93D167741D580C3500330C99 /* ShowNetworksViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ShowNetworksViewController.h; sourceTree = ""; }; - 93D167751D580C3500330C99 /* ShowNetworksViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ShowNetworksViewController.m; sourceTree = ""; }; - 93D167771D5815E600330C99 /* JoinNetworkViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JoinNetworkViewController.h; sourceTree = ""; }; - 93D167781D5815E600330C99 /* JoinNetworkViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JoinNetworkViewController.m; sourceTree = ""; }; - 93D1677A1D58228A00330C99 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; - 93D1677B1D58228A00330C99 /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; - 93D1679A1D58300F00330C99 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; - 93D1679C1D595F0000330C99 /* WebKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WebKit.framework; path = System/Library/Frameworks/WebKit.framework; sourceTree = SDKROOT; }; - 93DAFB261D3F0BEE004D5417 /* about.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = about.html; sourceTree = ""; }; - 93DAFE4A1CFE53CA00547CC4 /* AuthtokenCopy.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AuthtokenCopy.m; sourceTree = ""; }; - 93DAFE4C1CFE53DA00547CC4 /* AuthtokenCopy.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AuthtokenCopy.h; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 93326BD51CE7C816005CA2AC /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 93D1679D1D595F0000330C99 /* WebKit.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 93326BCF1CE7C816005CA2AC = { - isa = PBXGroup; - children = ( - 93D1679C1D595F0000330C99 /* WebKit.framework */, - 93326BDA1CE7C816005CA2AC /* ZeroTier One */, - 93326BD91CE7C816005CA2AC /* Products */, - ); - sourceTree = ""; - }; - 93326BD91CE7C816005CA2AC /* Products */ = { - isa = PBXGroup; - children = ( - 93326BD81CE7C816005CA2AC /* ZeroTier One.app */, - ); - name = Products; - sourceTree = ""; - }; - 93326BDA1CE7C816005CA2AC /* ZeroTier One */ = { - isa = PBXGroup; - children = ( - 932D472E1D1CD499004BCFE2 /* ZeroTierIcon.icns */, - 93326BDD1CE7C816005CA2AC /* Assets.xcassets */, - 93326BDF1CE7C816005CA2AC /* MainMenu.xib */, - 93326BE21CE7C816005CA2AC /* Info.plist */, - 93DAFE4A1CFE53CA00547CC4 /* AuthtokenCopy.m */, - 93DAFE4C1CFE53DA00547CC4 /* AuthtokenCopy.h */, - 93D1676E1D57FD3800330C99 /* NetworkMonitor.h */, - 93D1676F1D57FD3800330C99 /* NetworkMonitor.m */, - 93DAFB261D3F0BEE004D5417 /* about.html */, - 93D1675D1D54191C00330C99 /* NodeStatus.h */, - 93D1675E1D54191C00330C99 /* NodeStatus.m */, - 93D167601D541BC200330C99 /* ServiceCom.h */, - 93D167611D541BC200330C99 /* ServiceCom.m */, - 93D167641D54308200330C99 /* Network.h */, - 93D167651D54308200330C99 /* Network.m */, - 93D167671D57E7EA00330C99 /* AboutViewController.h */, - 93D167681D57E7EA00330C99 /* AboutViewController.m */, - 932D47351D1CDC9B004BCFE2 /* AboutViewController.xib */, - 93D1676B1D57EB8400330C99 /* PreferencesViewController.h */, - 93D1676C1D57EB8400330C99 /* PreferencesViewController.m */, - 932D47311D1CD861004BCFE2 /* PreferencesViewController.xib */, - 93D167711D58093C00330C99 /* NetworkInfoCell.h */, - 93D167721D58093C00330C99 /* NetworkInfoCell.m */, - 93D167741D580C3500330C99 /* ShowNetworksViewController.h */, - 93D167751D580C3500330C99 /* ShowNetworksViewController.m */, - 93326BED1CE7DA30005CA2AC /* ShowNetworksViewController.xib */, - 93D167771D5815E600330C99 /* JoinNetworkViewController.h */, - 93D167781D5815E600330C99 /* JoinNetworkViewController.m */, - 93326BE91CE7D9B9005CA2AC /* JoinNetworkViewController.xib */, - 93D1677A1D58228A00330C99 /* AppDelegate.h */, - 93D1677B1D58228A00330C99 /* AppDelegate.m */, - 93D1679A1D58300F00330C99 /* main.m */, - ); - path = "ZeroTier One"; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 93326BD71CE7C816005CA2AC /* ZeroTier One */ = { - isa = PBXNativeTarget; - buildConfigurationList = 93326BE51CE7C816005CA2AC /* Build configuration list for PBXNativeTarget "ZeroTier One" */; - buildPhases = ( - 93326BD41CE7C816005CA2AC /* Sources */, - 93326BD51CE7C816005CA2AC /* Frameworks */, - 93326BD61CE7C816005CA2AC /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = "ZeroTier One"; - productName = "ZeroTier One"; - productReference = 93326BD81CE7C816005CA2AC /* ZeroTier One.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 93326BD01CE7C816005CA2AC /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 0730; - LastUpgradeCheck = 0800; - ORGANIZATIONNAME = "ZeroTier, Inc"; - TargetAttributes = { - 93326BD71CE7C816005CA2AC = { - CreatedOnToolsVersion = 7.3; - }; - }; - }; - buildConfigurationList = 93326BD31CE7C816005CA2AC /* Build configuration list for PBXProject "ZeroTier One" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 93326BCF1CE7C816005CA2AC; - productRefGroup = 93326BD91CE7C816005CA2AC /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 93326BD71CE7C816005CA2AC /* ZeroTier One */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 93326BD61CE7C816005CA2AC /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 93DAFB271D3F0BEE004D5417 /* about.html in Resources */, - 93326BEF1CE7DA30005CA2AC /* ShowNetworksViewController.xib in Resources */, - 932D47371D1CDC9B004BCFE2 /* AboutViewController.xib in Resources */, - 93326BEB1CE7D9B9005CA2AC /* JoinNetworkViewController.xib in Resources */, - 93326BDE1CE7C816005CA2AC /* Assets.xcassets in Resources */, - 93326BE11CE7C816005CA2AC /* MainMenu.xib in Resources */, - 932D472F1D1CD499004BCFE2 /* ZeroTierIcon.icns in Resources */, - 932D47331D1CD861004BCFE2 /* PreferencesViewController.xib in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 93326BD41CE7C816005CA2AC /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 93D1679B1D58300F00330C99 /* main.m in Sources */, - 93D167621D541BC200330C99 /* ServiceCom.m in Sources */, - 93D167761D580C3500330C99 /* ShowNetworksViewController.m in Sources */, - 93DAFE4B1CFE53CA00547CC4 /* AuthtokenCopy.m in Sources */, - 93D167701D57FD3800330C99 /* NetworkMonitor.m in Sources */, - 93D1675F1D54191C00330C99 /* NodeStatus.m in Sources */, - 93D167691D57E7EA00330C99 /* AboutViewController.m in Sources */, - 93D1676D1D57EB8400330C99 /* PreferencesViewController.m in Sources */, - 93D1677C1D58228A00330C99 /* AppDelegate.m in Sources */, - 93D167731D58093C00330C99 /* NetworkInfoCell.m in Sources */, - 93D167661D54308200330C99 /* Network.m in Sources */, - 93D167791D5815E600330C99 /* JoinNetworkViewController.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXVariantGroup section */ - 93326BDF1CE7C816005CA2AC /* MainMenu.xib */ = { - isa = PBXVariantGroup; - children = ( - 93326BE01CE7C816005CA2AC /* Base */, - ); - name = MainMenu.xib; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 93326BE31CE7C816005CA2AC /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.11; - MTL_ENABLE_DEBUG_INFO = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = macosx; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - 93326BE41CE7C816005CA2AC /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.11; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = macosx; - }; - name = Release; - }; - 93326BE61CE7C816005CA2AC /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - CLANG_ENABLE_MODULES = YES; - COMBINE_HIDPI_IMAGES = YES; - INFOPLIST_FILE = "ZeroTier One/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; - MACOSX_DEPLOYMENT_TARGET = 10.10; - PRODUCT_BUNDLE_IDENTIFIER = "com.zerotier.ZeroTier-One"; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "ZeroTier One/ZeroTier One-Bridging-Header.h"; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - 93326BE71CE7C816005CA2AC /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - CLANG_ENABLE_MODULES = YES; - COMBINE_HIDPI_IMAGES = YES; - INFOPLIST_FILE = "ZeroTier One/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; - MACOSX_DEPLOYMENT_TARGET = 10.10; - PRODUCT_BUNDLE_IDENTIFIER = "com.zerotier.ZeroTier-One"; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "ZeroTier One/ZeroTier One-Bridging-Header.h"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 93326BD31CE7C816005CA2AC /* Build configuration list for PBXProject "ZeroTier One" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 93326BE31CE7C816005CA2AC /* Debug */, - 93326BE41CE7C816005CA2AC /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 93326BE51CE7C816005CA2AC /* Build configuration list for PBXNativeTarget "ZeroTier One" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 93326BE61CE7C816005CA2AC /* Debug */, - 93326BE71CE7C816005CA2AC /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 93326BD01CE7C816005CA2AC /* Project object */; -} diff --git a/attic/macui/ZeroTier One.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/attic/macui/ZeroTier One.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index fd60338ec..000000000 --- a/attic/macui/ZeroTier One.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/attic/macui/ZeroTier One.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/attic/macui/ZeroTier One.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d981003..000000000 --- a/attic/macui/ZeroTier One.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/attic/macui/ZeroTier One/AboutViewController.h b/attic/macui/ZeroTier One/AboutViewController.h deleted file mode 100644 index d3d5bc14e..000000000 --- a/attic/macui/ZeroTier One/AboutViewController.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import -#import - -@interface AboutViewController : NSViewController - -@property (nonatomic, weak) IBOutlet WebView *webView; - -- (void)viewDidLoad; - -- (void)webView:(WebView *)webView decidePolicyForNavigationAction:(NSDictionary *)actionInformation - request:(NSURLRequest *)request - frame:(WebFrame *)frame -decisionListener:(id)listener; - -@end diff --git a/attic/macui/ZeroTier One/AboutViewController.m b/attic/macui/ZeroTier One/AboutViewController.m deleted file mode 100644 index 7f92977d3..000000000 --- a/attic/macui/ZeroTier One/AboutViewController.m +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import "AboutViewController.h" - -@interface AboutViewController () - -@end - -@implementation AboutViewController - -- (void)viewDidLoad { - [super viewDidLoad]; - - [self.webView setWantsLayer:YES]; - self.webView.layer.borderWidth = 1.0f; - [self.webView.layer setCornerRadius:1.0f]; - self.webView.layer.masksToBounds = YES; - [self.webView.layer setBorderColor:[[NSColor darkGrayColor] CGColor]]; - self.webView.policyDelegate = self; - - NSBundle *bundle = [NSBundle mainBundle]; - NSURL *path = [bundle URLForResource:@"about" withExtension:@"html"]; - if(path) { - [self.webView.mainFrame loadRequest:[NSURLRequest requestWithURL:path]]; - } -} - -- (void)webView:(WebView *)webView decidePolicyForNavigationAction:(NSDictionary *)actionInformation - request:(NSURLRequest *)request - frame:(WebFrame *)frame -decisionListener:(id)listener -{ - if(request.URL != nil && request.URL.host != nil) { - [[NSWorkspace sharedWorkspace] openURL:request.URL]; - } - else { - [listener use]; - } -} - -@end diff --git a/attic/macui/ZeroTier One/AboutViewController.xib b/attic/macui/ZeroTier One/AboutViewController.xib deleted file mode 100644 index a0df0fcfc..000000000 --- a/attic/macui/ZeroTier One/AboutViewController.xib +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/attic/macui/ZeroTier One/AppDelegate.h b/attic/macui/ZeroTier One/AppDelegate.h deleted file mode 100644 index a00cfba9d..000000000 --- a/attic/macui/ZeroTier One/AppDelegate.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import - -@class NetworkMonitor; -@class Network; -@class NodeStatus; - -@interface AppDelegate : NSObject - -@property (weak, nonatomic) IBOutlet NSWindow *window; - -@property (nonatomic) NSStatusItem *statusItem; - -@property (nonatomic) NSPopover *networkListPopover; -@property (nonatomic) NSPopover *joinNetworkPopover; -@property (nonatomic) NSPopover *preferencesPopover; -@property (nonatomic) NSPopover *aboutPopover; - -@property (nonatomic) id transientMonitor; - -@property (nonatomic) NetworkMonitor *monitor; - -@property (nonatomic) NSMutableArray *networks; - -@property (nonatomic) NodeStatus *status; - -- (void)buildMenu; - -- (void)onNetworkListUpdated:(NSNotification*)note; -- (void)onNodeStatusUpdated:(NSNotification*)note; - -- (void)showNetworks; -- (void)joinNetwork; -- (void)showPreferences; -- (void)showAbout; -- (void)quit; -- (void)toggleNetwork:(NSMenuItem*)sender; -- (void)copyNodeID; - -- (void)closeJoinNetworkPopover; - -- (void)darkModeChanged:(NSNotification*)note; - -@end diff --git a/attic/macui/ZeroTier One/AppDelegate.m b/attic/macui/ZeroTier One/AppDelegate.m deleted file mode 100644 index ae3e042f1..000000000 --- a/attic/macui/ZeroTier One/AppDelegate.m +++ /dev/null @@ -1,378 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import "AppDelegate.h" -#import "NetworkMonitor.h" -#import "Network.h" -#import "NodeStatus.h" -#import "JoinNetworkViewController.h" -#import "ShowNetworksViewController.h" -#import "PreferencesViewController.h" -#import "AboutViewController.h" -#import "ServiceCom.h" - -@implementation AppDelegate - -- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { - self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:-2.0f]; - self.networkListPopover = [[NSPopover alloc] init]; - self.joinNetworkPopover = [[NSPopover alloc] init]; - self.preferencesPopover = [[NSPopover alloc] init]; - self.aboutPopover = [[NSPopover alloc] init]; - self.transientMonitor = nil; - self.monitor = [[NetworkMonitor alloc] init]; - self.networks = [NSMutableArray array]; - self.status = nil; - - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSDictionary *defaultsDict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:@"firstRun"]; - [defaults registerDefaults:defaultsDict]; - - NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; - - [nc addObserver:self - selector:@selector(onNetworkListUpdated:) - name:NetworkUpdateKey - object:nil]; - [nc addObserver:self - selector:@selector(onNodeStatusUpdated:) - name:StatusUpdateKey - object:nil]; - - NSString *osxMode = [defaults stringForKey:@"AppleInterfaceStyle"]; - - if(osxMode != nil && [osxMode isEqualToString:@"Dark"]) { - self.statusItem.image = [NSImage imageNamed:@"MenuBarIconMacWhite"]; - } - else { - self.statusItem.image = [NSImage imageNamed:@"MenuBarIconMac"]; - } - - [[NSDistributedNotificationCenter defaultCenter] addObserver:self - selector:@selector(darkModeChanged:) - name:@"AppleInterfaceThemeChangedNotification" - object:nil]; - - [self buildMenu]; - JoinNetworkViewController *jnvc = [[JoinNetworkViewController alloc] initWithNibName:@"JoinNetworkViewController" bundle:nil]; - jnvc.appDelegate = self; - self.joinNetworkPopover.contentViewController = jnvc; - self.joinNetworkPopover.behavior = NSPopoverBehaviorTransient; - - ShowNetworksViewController *showNetworksView = [[ShowNetworksViewController alloc] initWithNibName:@"ShowNetworksViewController" bundle:nil]; - showNetworksView.netMonitor = self.monitor; - self.networkListPopover.contentViewController = showNetworksView; - self.networkListPopover.behavior = NSPopoverBehaviorTransient; - - PreferencesViewController *prefsView = [[PreferencesViewController alloc] initWithNibName:@"PreferencesViewController" bundle:nil]; - self.preferencesPopover.contentViewController = prefsView; - self.preferencesPopover.behavior = NSPopoverBehaviorTransient; - - self.aboutPopover.contentViewController = [[AboutViewController alloc] initWithNibName:@"AboutViewController" bundle:nil]; - self.aboutPopover.behavior = NSPopoverBehaviorTransient; - - BOOL firstRun = [defaults boolForKey:@"firstRun"]; - - if(firstRun) { - [defaults setBool:NO forKey:@"firstRun"]; - [defaults synchronize]; - - [prefsView setLaunchAtLoginEnabled:YES]; - - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - sleep(2); - [[NSOperationQueue mainQueue] addOperationWithBlock:^{ - [self showAbout]; - }]; - }); - } - - [self.monitor updateNetworkInfo]; - [self.monitor start]; -} - -- (void)applicationWillTerminate:(NSNotification *)aNotification { - [[NSNotificationCenter defaultCenter] removeObserver:self]; - [[NSDistributedNotificationCenter defaultCenter] removeObserver:self - name:@"AppleInterfaceThemeChangedNotification" - object:nil]; -} - -- (void)showNetworks { - NSButton *button = nil; - NSRect frame; - if ([self.statusItem respondsToSelector:@selector(button)]) { - button = self.statusItem.button; - frame = button.bounds; - } else if ([self.statusItem respondsToSelector:@selector(_button)]) { - button = [self.statusItem performSelector:@selector(_button)]; - frame = button.bounds; - } else { - NSLog(@"Can't get view. Uh oh."); - return; - } - - [self.networkListPopover showRelativeToRect:frame - ofView:button - preferredEdge:NSMinYEdge]; - - if(self.transientMonitor == nil) { - self.transientMonitor = - [NSEvent addGlobalMonitorForEventsMatchingMask:(NSLeftMouseDown|NSRightMouseDown|NSOtherMouseDown) - handler:^(NSEvent * _Nonnull e) { - [NSEvent removeMonitor:self.transientMonitor]; - self.transientMonitor = nil; - [self.networkListPopover close]; - }]; - } -} - -- (void)joinNetwork { - NSButton *button = nil; - NSRect frame; - if ([self.statusItem respondsToSelector:@selector(button)]) { - button = self.statusItem.button; - frame = button.bounds; - } else if ([self.statusItem respondsToSelector:@selector(_button)]) { - button = [self.statusItem performSelector:@selector(_button)]; - frame = button.bounds; - } else { - NSLog(@"Can't get view. Uh oh."); - return; - } - - [self.joinNetworkPopover showRelativeToRect:button.bounds - ofView:button - preferredEdge:NSMinYEdge]; - if(self.transientMonitor == nil) { - self.transientMonitor = - [NSEvent addGlobalMonitorForEventsMatchingMask:(NSLeftMouseDown|NSRightMouseDown|NSOtherMouseDown) - handler:^(NSEvent * _Nonnull e) { - [NSEvent removeMonitor:self.transientMonitor]; - self.transientMonitor = nil; - [self.joinNetworkPopover close]; - }]; - } -} - -- (void)showPreferences { - NSButton *button = nil; - NSRect frame; - if ([self.statusItem respondsToSelector:@selector(button)]) { - button = self.statusItem.button; - frame = button.bounds; - } else if ([self.statusItem respondsToSelector:@selector(_button)]) { - button = [self.statusItem performSelector:@selector(_button)]; - frame = button.bounds; - } else { - NSLog(@"Can't get view. Uh oh."); - return; - } - - [self.preferencesPopover showRelativeToRect:button.bounds - ofView:button - preferredEdge:NSMinYEdge]; - if(self.transientMonitor == nil) { - [NSEvent addGlobalMonitorForEventsMatchingMask:(NSLeftMouseDown|NSRightMouseDown|NSOtherMouseDown) - handler:^(NSEvent * _Nonnull e) { - [NSEvent removeMonitor:self.transientMonitor]; - self.transientMonitor = nil; - [self.preferencesPopover close]; - }]; - } -} - -- (void)showAbout { - NSButton *button = nil; - NSRect frame; - if ([self.statusItem respondsToSelector:@selector(button)]) { - button = self.statusItem.button; - frame = button.bounds; - } else if ([self.statusItem respondsToSelector:@selector(_button)]) { - button = [self.statusItem performSelector:@selector(_button)]; - frame = button.bounds; - } else { - NSLog(@"Can't get view. Uh oh."); - return; - } - - [self.aboutPopover showRelativeToRect:button.bounds - ofView:button - preferredEdge:NSMinYEdge]; - if(self.transientMonitor == nil) { - [NSEvent addGlobalMonitorForEventsMatchingMask:(NSLeftMouseDown|NSRightMouseDown|NSOtherMouseDown) - handler:^(NSEvent * _Nonnull e) { - [NSEvent removeMonitor:self.transientMonitor]; - self.transientMonitor = nil; - [self.aboutPopover close]; - }]; - } -} - -- (void)quit { - [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0]; -} - -- (void)onNetworkListUpdated:(NSNotification*)note { - NSArray *netList = [note.userInfo objectForKey:@"networks"]; - [(ShowNetworksViewController*)self.networkListPopover.contentViewController setNetworks:netList]; - self.networks = [netList mutableCopy]; - - [self buildMenu]; -} - -- (void)onNodeStatusUpdated:(NSNotification*)note { - NodeStatus *status = [note.userInfo objectForKey:@"status"]; - self.status = status; - - [self buildMenu]; -} - -- (void)buildMenu { - NSMenu *menu = [[NSMenu alloc] init]; - - if(self.status != nil) { - NSString *nodeId = @"Node ID: "; - nodeId = [nodeId stringByAppendingString:self.status.address]; - [menu addItem:[[NSMenuItem alloc] initWithTitle:nodeId - action:@selector(copyNodeID) - keyEquivalent:@""]]; - [menu addItem:[NSMenuItem separatorItem]]; - } - - [menu addItem:[[NSMenuItem alloc] initWithTitle:@"Network Details..." - action:@selector(showNetworks) - keyEquivalent:@"n"]]; - [menu addItem:[[NSMenuItem alloc] initWithTitle:@"Join Network..." - action:@selector(joinNetwork) - keyEquivalent:@"j"]]; - - [menu addItem:[NSMenuItem separatorItem]]; - - if([self.networks count] > 0) { - for(Network *net in self.networks) { - NSString *nwid = [NSString stringWithFormat:@"%10llx", net.nwid]; - NSString *networkName = @""; - if([net.name lengthOfBytesUsingEncoding:NSUTF8StringEncoding] == 0) { - networkName = nwid; - } - else { - networkName = [NSString stringWithFormat:@"%@ (%@)", nwid, net.name]; - } - - if(net.allowDefault && net.connected) { - networkName = [networkName stringByAppendingString:@" [default]"]; - } - - NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:networkName - action:@selector(toggleNetwork:) - keyEquivalent:@""]; - if(net.connected) { - item.state = NSOnState; - } - else { - item.state = NSOffState; - } - - item.representedObject = net; - - [menu addItem:item]; - } - - [menu addItem:[NSMenuItem separatorItem]]; - } - - [menu addItem:[[NSMenuItem alloc] initWithTitle:@"About ZeroTier One..." - action:@selector(showAbout) - keyEquivalent:@""]]; - [menu addItem:[[NSMenuItem alloc] initWithTitle:@"Preferences..." - action:@selector(showPreferences) - keyEquivalent:@""]]; - - [menu addItem:[NSMenuItem separatorItem]]; - - [menu addItem:[[NSMenuItem alloc] initWithTitle:@"Quit" - action:@selector(quit) - keyEquivalent:@"q"]]; - - self.statusItem.menu = menu; -} - -- (void)toggleNetwork:(NSMenuItem*)sender { - Network *network = sender.representedObject; - NSString *nwid = [NSString stringWithFormat:@"%10llx", network.nwid]; - - if(network.connected) { - NSError *error = nil; - - [[ServiceCom sharedInstance] leaveNetwork:nwid error:&error]; - - if (error) { - NSAlert *alert = [NSAlert alertWithError:error]; - alert.alertStyle = NSCriticalAlertStyle; - [alert addButtonWithTitle:@"Ok"]; - - [alert runModal]; - } - } - else { - NSError *error = nil; - [[ServiceCom sharedInstance] joinNetwork:nwid - allowManaged:network.allowManaged - allowGlobal:network.allowGlobal - allowDefault:(network.allowDefault && ![Network defaultRouteExists:self.networks]) - error:&error]; - - if (error) { - NSAlert *alert = [NSAlert alertWithError:error]; - alert.alertStyle = NSCriticalAlertStyle; - [alert addButtonWithTitle:@"Ok"]; - - [alert runModal]; - } - } -} - -- (void)copyNodeID { - if(self.status != nil) { - NSPasteboard *pasteboard = [NSPasteboard generalPasteboard]; - [pasteboard declareTypes:[NSArray arrayWithObject:NSPasteboardTypeString] owner:nil]; - [pasteboard setString:self.status.address forType:NSPasteboardTypeString]; - } -} - -- (void)darkModeChanged:(NSNotification*)note { - NSString *osxMode = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"]; - - if(osxMode != nil && [osxMode isEqualToString:@"Dark"]) { - self.statusItem.image = [NSImage imageNamed:@"MenuBarIconMacWhite"]; - } - else { - self.statusItem.image = [NSImage imageNamed:@"MenuBarIconMac"]; - } -} - -- (void)closeJoinNetworkPopover { - if (self.transientMonitor) { - [NSEvent removeMonitor:self.transientMonitor]; - self.transientMonitor = nil; - } - [self.joinNetworkPopover close]; -} - -@end diff --git a/attic/macui/ZeroTier One/Assets.xcassets/AppIcon.appiconset/Contents.json b/attic/macui/ZeroTier One/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index 24c81d35f..000000000 --- a/attic/macui/ZeroTier One/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "images" : [ - { - "idiom" : "mac", - "size" : "16x16", - "scale" : "1x" - }, - { - "idiom" : "mac", - "size" : "16x16", - "scale" : "2x" - }, - { - "idiom" : "mac", - "size" : "32x32", - "scale" : "1x" - }, - { - "idiom" : "mac", - "size" : "32x32", - "scale" : "2x" - }, - { - "idiom" : "mac", - "size" : "128x128", - "scale" : "1x" - }, - { - "idiom" : "mac", - "size" : "128x128", - "scale" : "2x" - }, - { - "idiom" : "mac", - "size" : "256x256", - "scale" : "1x" - }, - { - "idiom" : "mac", - "size" : "256x256", - "scale" : "2x" - }, - { - "size" : "512x512", - "idiom" : "mac", - "filename" : "ZeroTierIcon512x512.png", - "scale" : "1x" - }, - { - "idiom" : "mac", - "size" : "512x512", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/attic/macui/ZeroTier One/Assets.xcassets/AppIcon.appiconset/ZeroTierIcon512x512.png b/attic/macui/ZeroTier One/Assets.xcassets/AppIcon.appiconset/ZeroTierIcon512x512.png deleted file mode 100644 index d225c2e33..000000000 Binary files a/attic/macui/ZeroTier One/Assets.xcassets/AppIcon.appiconset/ZeroTierIcon512x512.png and /dev/null differ diff --git a/attic/macui/ZeroTier One/Assets.xcassets/Contents.json b/attic/macui/ZeroTier One/Assets.xcassets/Contents.json deleted file mode 100644 index da4a164c9..000000000 --- a/attic/macui/ZeroTier One/Assets.xcassets/Contents.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMac.imageset/Contents.json b/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMac.imageset/Contents.json deleted file mode 100644 index a680b58b8..000000000 --- a/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMac.imageset/Contents.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "images" : [ - { - "idiom" : "mac", - "filename" : "Menubar.png", - "scale" : "1x" - }, - { - "idiom" : "mac", - "filename" : "MenuBar@2x.png", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "template-rendering-intent" : "template" - } -} \ No newline at end of file diff --git a/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMac.imageset/MenuBar@2x.png b/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMac.imageset/MenuBar@2x.png deleted file mode 100644 index 9fd3d3dee..000000000 Binary files a/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMac.imageset/MenuBar@2x.png and /dev/null differ diff --git a/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMac.imageset/Menubar.png b/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMac.imageset/Menubar.png deleted file mode 100644 index ee0d7e3fd..000000000 Binary files a/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMac.imageset/Menubar.png and /dev/null differ diff --git a/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMacWhite.imageset/Contents.json b/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMacWhite.imageset/Contents.json deleted file mode 100644 index 617377601..000000000 --- a/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMacWhite.imageset/Contents.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "images" : [ - { - "idiom" : "mac", - "filename" : "MenubarWhite.png", - "scale" : "1x" - }, - { - "idiom" : "mac", - "filename" : "MenubarWhite@2x.png", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "template-rendering-intent" : "template" - } -} \ No newline at end of file diff --git a/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMacWhite.imageset/MenubarWhite.png b/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMacWhite.imageset/MenubarWhite.png deleted file mode 100644 index 7049ae550..000000000 Binary files a/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMacWhite.imageset/MenubarWhite.png and /dev/null differ diff --git a/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMacWhite.imageset/MenubarWhite@2x.png b/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMacWhite.imageset/MenubarWhite@2x.png deleted file mode 100644 index 8c20e36fe..000000000 Binary files a/attic/macui/ZeroTier One/Assets.xcassets/MenuBarIconMacWhite.imageset/MenubarWhite@2x.png and /dev/null differ diff --git a/attic/macui/ZeroTier One/AuthtokenCopy.h b/attic/macui/ZeroTier One/AuthtokenCopy.h deleted file mode 100644 index f0497cc6d..000000000 --- a/attic/macui/ZeroTier One/AuthtokenCopy.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#ifndef AuthtokenCopy_h -#define AuthtokenCopy_h - -#import - -NSString* getAdminAuthToken(AuthorizationRef authRef); - -#endif /* AuthtokenCopy_h */ diff --git a/attic/macui/ZeroTier One/AuthtokenCopy.m b/attic/macui/ZeroTier One/AuthtokenCopy.m deleted file mode 100644 index a10350f7b..000000000 --- a/attic/macui/ZeroTier One/AuthtokenCopy.m +++ /dev/null @@ -1,97 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import - -#import "AuthtokenCopy.h" - - -NSString* getAdminAuthToken(AuthorizationRef authRef) { - char *tool = "/bin/cat"; - char *args[] = { "/Library/Application Support/ZeroTier/One/authtoken.secret", NULL}; - FILE *pipe = nil; - char token[25]; - memset(token, 0, sizeof(char)*25); - - - OSStatus status = AuthorizationExecuteWithPrivileges(authRef, tool, kAuthorizationFlagDefaults, args, &pipe); - - if (status != errAuthorizationSuccess) { - NSLog(@"Reading authtoken failed!"); - - - switch(status) { - case errAuthorizationDenied: - NSLog(@"Autorization Denied"); - break; - case errAuthorizationCanceled: - NSLog(@"Authorization Canceled"); - break; - case errAuthorizationInternal: - NSLog(@"Authorization Internal"); - break; - case errAuthorizationBadAddress: - NSLog(@"Bad Address"); - break; - case errAuthorizationInvalidRef: - NSLog(@"Invalid Ref"); - break; - case errAuthorizationInvalidSet: - NSLog(@"Invalid Set"); - break; - case errAuthorizationInvalidTag: - NSLog(@"Invalid Tag"); - break; - case errAuthorizationInvalidFlags: - NSLog(@"Invalid Flags"); - break; - case errAuthorizationInvalidPointer: - NSLog(@"Invalid Pointer"); - break; - case errAuthorizationToolExecuteFailure: - NSLog(@"Tool Execute Failure"); - break; - case errAuthorizationToolEnvironmentError: - NSLog(@"Tool Environment Failure"); - break; - case errAuthorizationExternalizeNotAllowed: - NSLog(@"Externalize Not Allowed"); - break; - case errAuthorizationInteractionNotAllowed: - NSLog(@"Interaction Not Allowed"); - break; - case errAuthorizationInternalizeNotAllowed: - NSLog(@"Internalize Not Allowed"); - break; - default: - NSLog(@"Unknown Error"); - break; - } - - return @""; - } - - if(pipe != nil) { - fread(&token, sizeof(char), 24, pipe); - fclose(pipe); - - return [NSString stringWithUTF8String:token]; - } - - return @""; -} diff --git a/attic/macui/ZeroTier One/Base.lproj/MainMenu.xib b/attic/macui/ZeroTier One/Base.lproj/MainMenu.xib deleted file mode 100644 index 6b6da2a64..000000000 --- a/attic/macui/ZeroTier One/Base.lproj/MainMenu.xib +++ /dev/null @@ -1,680 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Default - - - - - - - Left to Right - - - - - - - Right to Left - - - - - - - - - - - Default - - - - - - - Left to Right - - - - - - - Right to Left - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/attic/macui/ZeroTier One/Info.plist b/attic/macui/ZeroTier One/Info.plist deleted file mode 100644 index e04b5f282..000000000 --- a/attic/macui/ZeroTier One/Info.plist +++ /dev/null @@ -1,41 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIconFile - ZeroTierIcon.icns - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - APPL - CFBundleShortVersionString - 1.0 - CFBundleSignature - ???? - CFBundleVersion - 15 - LSMinimumSystemVersion - $(MACOSX_DEPLOYMENT_TARGET) - LSUIElement - - NSAppTransportSecurity - - NSAllowsArbitraryLoads - - - NSHumanReadableCopyright - Copyright © 2016 ZeroTier, Inc. All rights reserved. - NSMainNibFile - MainMenu - NSPrincipalClass - NSApplication - - diff --git a/attic/macui/ZeroTier One/JoinNetworkViewController.h b/attic/macui/ZeroTier One/JoinNetworkViewController.h deleted file mode 100644 index 428959fba..000000000 --- a/attic/macui/ZeroTier One/JoinNetworkViewController.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import - - -extern NSString * const JoinedNetworksKey; - -@class AppDelegate; - -@interface JoinNetworkViewController : NSViewController - -@property (nonatomic, weak) IBOutlet NSComboBox *network; -@property (nonatomic, weak) IBOutlet NSButton *joinButton; -@property (nonatomic, weak) IBOutlet NSButton *allowManagedCheckBox; -@property (nonatomic, weak) IBOutlet NSButton *allowGlobalCheckBox; -@property (nonatomic, weak) IBOutlet NSButton *allowDefaultCheckBox; -@property (nonatomic, weak) IBOutlet AppDelegate *appDelegate; - -@property (nonatomic) NSMutableArray *values; - -- (IBAction)onJoinClicked:(id)sender; - - -@end diff --git a/attic/macui/ZeroTier One/JoinNetworkViewController.m b/attic/macui/ZeroTier One/JoinNetworkViewController.m deleted file mode 100644 index cae265416..000000000 --- a/attic/macui/ZeroTier One/JoinNetworkViewController.m +++ /dev/null @@ -1,184 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import "JoinNetworkViewController.h" -#import "ServiceCom.h" -#import "AppDelegate.h" - - -NSString * const JoinedNetworksKey = @"com.zerotier.one.joined-networks"; - -@interface NSString (extra) - -- (BOOL)contains:(NSString*)find; - -@end - -@implementation NSString (extra) - -- (BOOL)contains:(NSString*)find { - NSRange range = [self rangeOfString:find]; - return range.location != NSNotFound; -} - -@end - - -@implementation JoinNetworkViewController - -- (void)viewDidLoad { - [super viewDidLoad]; - // Do view setup here. - [self.network setDelegate:self]; - [self.network setDataSource:self]; -} - -- (void)viewWillAppear { - [super viewWillAppear]; - - self.allowManagedCheckBox.state = NSOnState; - self.allowGlobalCheckBox.state = NSOffState; - self.allowDefaultCheckBox.state = NSOffState; - - self.network.stringValue = @""; - - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - - NSMutableArray *vals = [[defaults stringArrayForKey:JoinedNetworksKey] mutableCopy]; - - if(vals) { - self.values = vals; - } -} - -- (void)viewWillDisappear { - [super viewWillDisappear]; - - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - - [defaults setObject:self.values forKey:JoinedNetworksKey]; -} - -- (IBAction)onJoinClicked:(id)sender { - NSString *networkId = self.network.stringValue; - - NSError *error = nil; - [[ServiceCom sharedInstance] joinNetwork:networkId - allowManaged:(self.allowManagedCheckBox.state == NSOnState) - allowGlobal:(self.allowGlobalCheckBox.state == NSOnState) - allowDefault:(self.allowDefaultCheckBox.state == NSOnState) - error:&error]; - - if(error) { - NSAlert *alert = [NSAlert alertWithError:error]; - alert.alertStyle = NSCriticalAlertStyle; - [alert addButtonWithTitle:@"Ok"]; - - [alert runModal]; - return; - } - - self.network.stringValue = @""; - - if(![self.values containsObject:networkId]) { - [self.values insertObject:networkId atIndex:0]; - - while([self.values count] > 20) { - [self.values removeLastObject]; - } - } - - [self.appDelegate closeJoinNetworkPopover]; -} - -// NSComboBoxDelegate methods - -- (void)controlTextDidChange:(NSNotification *)obj { - NSComboBox *cb = (NSComboBox*)obj.object; - NSString *value = cb.stringValue; - - NSString *allowedCharacters = @"abcdefABCDEF0123456789"; - - NSString *outValue = @""; - - for(int i = 0; i < [value length]; ++i) { - if(![allowedCharacters contains:[NSString stringWithFormat:@"%C", [value characterAtIndex:i]]]) { - NSBeep(); - } - else { - outValue = [outValue stringByAppendingString:[NSString stringWithFormat:@"%C", [value characterAtIndex:i]]]; - } - } - - if([outValue lengthOfBytesUsingEncoding:NSUTF8StringEncoding] == 16) { - self.joinButton.enabled = YES; - } - else { - if([outValue lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 16) { - NSRange range = {0, 16}; - range = [outValue rangeOfComposedCharacterSequencesForRange:range]; - outValue = [outValue substringWithRange:range]; - NSBeep(); - self.joinButton.enabled = YES; - } - else { - self.joinButton.enabled = NO; - } - } - - cb.stringValue = outValue; -} - -// end NSComboBoxDelegate methods - -// NSComboBoxDataSource methods - -- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)aComboBox { - return [self.values count]; -} - -- (id)comboBox:(NSComboBox *)aComboBox objectValueForItemAtIndex:(NSInteger)index { - return [self.values objectAtIndex:index]; -} - -- (NSUInteger)comboBox:(NSComboBox *)aComboBox indexOfItemWithStringValue:(NSString *)string { - NSUInteger counter = 0; - - for(NSString *val in self.values) { - if([val isEqualToString:string]) { - return counter; - } - - counter += 1; - } - - return NSNotFound; -} - -- (NSString*)comboBox:(NSComboBox *)aComboBox completedString:(NSString *)string { - for(NSString *val in self.values) { - if([val hasPrefix:string]) { - return val; - } - } - return nil; -} - -// end NSComboBoxDataSource methods - -@end diff --git a/attic/macui/ZeroTier One/JoinNetworkViewController.xib b/attic/macui/ZeroTier One/JoinNetworkViewController.xib deleted file mode 100644 index 59161093f..000000000 --- a/attic/macui/ZeroTier One/JoinNetworkViewController.xib +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/attic/macui/ZeroTier One/Network.h b/attic/macui/ZeroTier One/Network.h deleted file mode 100644 index 957ff8d56..000000000 --- a/attic/macui/ZeroTier One/Network.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import - -enum NetworkStatus { - REQUESTING_CONFIGURATION, - OK, - ACCESS_DENIED, - NOT_FOUND, - PORT_ERROR, - CLIENT_TOO_OLD, -}; - -enum NetworkType { - PUBLIC, - PRIVATE, -}; - -@interface Network : NSObject - -@property (readonly) NSArray *assignedAddresses; -@property (readonly) BOOL bridge; -@property (readonly) BOOL broadcastEnabled; -@property (readonly) BOOL dhcp; -@property (readonly) NSString *mac; -@property (readonly) int mtu; -@property (readonly) int netconfRevision; -@property (readonly) NSString *name; -@property (readonly) UInt64 nwid; -@property (readonly) NSString *portDeviceName; -@property (readonly) int portError; -@property (readonly) enum NetworkStatus status; -@property (readonly) enum NetworkType type; -@property (readonly) BOOL allowManaged; -@property (readonly) BOOL allowGlobal; -@property (readonly) BOOL allowDefault; -@property (readonly) BOOL connected; // not persisted. set to YES if loaded via json - -- (id)initWithJsonData:(NSDictionary*)jsonData; -- (id)initWithCoder:(NSCoder *)aDecoder; -- (void)encodeWithCoder:(NSCoder *)aCoder; -+ (BOOL)defaultRouteExists:(NSArray*)netList; -- (NSString*)statusString; -- (NSString*)typeString; - -- (BOOL)hasSameNetworkId:(UInt64)networkId; - -- (BOOL)isEqualToNetwork:(Network*)network; -- (BOOL)isEqual:(id)object; -- (NSUInteger)hash; - -@end diff --git a/attic/macui/ZeroTier One/Network.m b/attic/macui/ZeroTier One/Network.m deleted file mode 100644 index 8474acaaf..000000000 --- a/attic/macui/ZeroTier One/Network.m +++ /dev/null @@ -1,337 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import "Network.h" - -NSString *NetworkAddressesKey = @"addresses"; -NSString *NetworkBridgeKey = @"bridge"; -NSString *NetworkBroadcastKey = @"broadcast"; -NSString *NetworkDhcpKey = @"dhcp"; -NSString *NetworkMacKey = @"mac"; -NSString *NetworkMtuKey = @"mtu"; -NSString *NetworkMulticastKey = @"multicast"; -NSString *NetworkNameKey = @"name"; -NSString *NetworkNetconfKey = @"netconf"; -NSString *NetworkNwidKey = @"nwid"; -NSString *NetworkPortNameKey = @"port"; -NSString *NetworkPortErrorKey = @"portError"; -NSString *NetworkStatusKey = @"status"; -NSString *NetworkTypeKey = @"type"; -NSString *NetworkAllowManagedKey = @"allowManaged"; -NSString *NetworkAllowGlobalKey = @"allowGlobal"; -NSString *NetworkAllowDefaultKey = @"allowDefault"; - -@implementation Network - -- (id)initWithJsonData:(NSDictionary*)jsonData -{ - self = [super init]; - - if(self) { - if([jsonData objectForKey:@"assignedAddresses"]) { - _assignedAddresses = (NSArray*)[jsonData objectForKey:@"assignedAddresses"]; - } - - if([jsonData objectForKey:@"bridge"]) { - _bridge = [(NSNumber*)[jsonData objectForKey:@"bridge"] boolValue]; - } - - if([jsonData objectForKey:@"broadcastEnabled"]) { - _broadcastEnabled = [(NSNumber*)[jsonData objectForKey:@"broadcastEnabled"] boolValue]; - } - - if([jsonData objectForKey:@"dhcp"]) { - _dhcp = [(NSNumber*)[jsonData objectForKey:@"dhcp"] boolValue]; - } - - if([jsonData objectForKey:@"mac"]) { - _mac = (NSString*)[jsonData objectForKey:@"mac"]; - } - - if([jsonData objectForKey:@"mtu"]) { - _mtu = [(NSNumber*)[jsonData objectForKey:@"mtu"] intValue]; - } - - if([jsonData objectForKey:@"name"]) { - _name = (NSString*)[jsonData objectForKey:@"name"]; - } - - if([jsonData objectForKey:@"netconfRevision"]) { - _netconfRevision = [(NSNumber*)[jsonData objectForKey:@"netconfRevision"] intValue]; - } - - if([jsonData objectForKey:@"nwid"]) { - NSString *networkid = (NSString*)[jsonData objectForKey:@"nwid"]; - - NSScanner *scanner = [NSScanner scannerWithString:networkid]; - [scanner scanHexLongLong:&_nwid]; - } - - if([jsonData objectForKey:@"portDeviceName"]) { - _portDeviceName = (NSString*)[jsonData objectForKey:@"portDeviceName"]; - } - - if([jsonData objectForKey:@"portError"]) { - _portError = [(NSNumber*)[jsonData objectForKey:@"portError"] intValue]; - } - - if([jsonData objectForKey:@"allowManaged"]) { - _allowManaged = [(NSNumber*)[jsonData objectForKey:@"allowManaged"] boolValue]; - } - - if([jsonData objectForKey:@"allowGlobal"]) { - _allowGlobal = [(NSNumber*)[jsonData objectForKey:@"allowGlobal"] boolValue]; - } - - if([jsonData objectForKey:@"allowDefault"]) { - _allowDefault = [(NSNumber*)[jsonData objectForKey:@"allowDefault"] boolValue]; - } - - if([jsonData objectForKey:@"status"]) { - NSString *statusStr = (NSString*)[jsonData objectForKey:@"status"]; - if([statusStr isEqualToString:@"REQUESTING_CONFIGURATION"]) { - _status = REQUESTING_CONFIGURATION; - } - else if([statusStr isEqualToString:@"OK"]) { - _status = OK; - } - else if([statusStr isEqualToString:@"ACCESS_DENIED"]) { - _status = ACCESS_DENIED; - } - else if([statusStr isEqualToString:@"NOT_FOUND"]) { - _status = NOT_FOUND; - } - else if([statusStr isEqualToString:@"PORT_ERROR"]) { - _status = PORT_ERROR; - } - else if([statusStr isEqualToString:@"CLIENT_TOO_OLD"]) { - _status = CLIENT_TOO_OLD; - } - } - - if([jsonData objectForKey:@"type"]) { - NSString *typeStr = (NSString*)[jsonData objectForKey:@"type"]; - if([typeStr isEqualToString:@"PRIVATE"]) { - _type = PRIVATE; - } - else if([typeStr isEqualToString:@"PUBLIC"]) { - _type = PUBLIC; - } - } - - _connected = YES; - } - - return self; -} -- (id)initWithCoder:(NSCoder *)aDecoder -{ - self = [super init]; - - if(self) { - if([aDecoder containsValueForKey:NetworkAddressesKey]) { - _assignedAddresses = (NSArray*)[aDecoder decodeObjectForKey:NetworkAddressesKey]; - } - - if([aDecoder containsValueForKey:NetworkBridgeKey]) { - _bridge = [aDecoder decodeBoolForKey:NetworkBridgeKey]; - } - - if([aDecoder containsValueForKey:NetworkBroadcastKey]) { - _broadcastEnabled = [aDecoder decodeBoolForKey:NetworkBroadcastKey]; - } - - if([aDecoder containsValueForKey:NetworkDhcpKey]) { - _dhcp = [aDecoder decodeBoolForKey:NetworkDhcpKey]; - } - - if([aDecoder containsValueForKey:NetworkMacKey]) { - _mac = (NSString*)[aDecoder decodeObjectForKey:NetworkMacKey]; - } - - if([aDecoder containsValueForKey:NetworkMtuKey]) { - _mtu = (int)[aDecoder decodeIntegerForKey:NetworkMtuKey]; - } - - if([aDecoder containsValueForKey:NetworkNameKey]) { - _name = (NSString*)[aDecoder decodeObjectForKey:NetworkNameKey]; - } - - if([aDecoder containsValueForKey:NetworkNetconfKey]) { - _netconfRevision = (int)[aDecoder decodeIntegerForKey:NetworkNetconfKey]; - } - - if([aDecoder containsValueForKey:NetworkNwidKey]) { - _nwid = [(NSNumber*)[aDecoder decodeObjectForKey:NetworkNwidKey] unsignedLongLongValue]; - } - - if([aDecoder containsValueForKey:NetworkPortNameKey]) { - _portDeviceName = (NSString*)[aDecoder decodeObjectForKey:NetworkPortNameKey]; - } - - if([aDecoder containsValueForKey:NetworkPortErrorKey]) { - _portError = (int)[aDecoder decodeIntegerForKey:NetworkPortErrorKey]; - } - - if([aDecoder containsValueForKey:NetworkStatusKey]) { - _status = (enum NetworkStatus)[aDecoder decodeIntegerForKey:NetworkStatusKey]; - } - - if([aDecoder containsValueForKey:NetworkTypeKey]) { - _type = (enum NetworkType)[aDecoder decodeIntegerForKey:NetworkTypeKey]; - } - - if([aDecoder containsValueForKey:NetworkAllowManagedKey]) { - _allowManaged = [aDecoder decodeBoolForKey:NetworkAllowManagedKey]; - } - - if([aDecoder containsValueForKey:NetworkAllowGlobalKey]) { - _allowGlobal = [aDecoder decodeBoolForKey:NetworkAllowGlobalKey]; - } - - if([aDecoder containsValueForKey:NetworkAllowDefaultKey]) { - _allowDefault = [aDecoder decodeBoolForKey:NetworkAllowDefaultKey]; - } - - _connected = NO; - } - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder -{ - [aCoder encodeObject:_assignedAddresses forKey:NetworkAddressesKey]; - [aCoder encodeBool:_bridge forKey:NetworkBridgeKey]; - [aCoder encodeBool:_broadcastEnabled forKey:NetworkBroadcastKey]; - [aCoder encodeBool:_dhcp forKey:NetworkDhcpKey]; - [aCoder encodeObject:_mac forKey:NetworkMacKey]; - [aCoder encodeInteger:_mtu forKey:NetworkMtuKey]; - [aCoder encodeObject:_name forKey:NetworkNameKey]; - [aCoder encodeInteger:_netconfRevision forKey:NetworkNetconfKey]; - [aCoder encodeObject:[NSNumber numberWithUnsignedLongLong:_nwid] - forKey:NetworkNwidKey]; - [aCoder encodeObject:_portDeviceName forKey:NetworkPortNameKey]; - [aCoder encodeInteger:_portError forKey:NetworkPortErrorKey]; - [aCoder encodeInteger:_status forKey:NetworkStatusKey]; - [aCoder encodeInteger:_type forKey:NetworkTypeKey]; - [aCoder encodeBool:_allowManaged forKey:NetworkAllowManagedKey]; - [aCoder encodeBool:_allowGlobal forKey:NetworkAllowGlobalKey]; - [aCoder encodeBool:_allowDefault forKey:NetworkAllowDefaultKey]; -} - -+ (BOOL)defaultRouteExists:(NSArray*)netList -{ - for(Network *net in netList) { - if (net.allowDefault && net.connected) { - return YES; - } - } - return NO; -} - -- (NSString*)statusString { - switch(_status) { - case REQUESTING_CONFIGURATION: - return @"REQUESTING_CONFIGURATION"; - case OK: - return @"OK"; - case ACCESS_DENIED: - return @"ACCESS_DENIED"; - case NOT_FOUND: - return @"NOT_FOUND"; - case PORT_ERROR: - return @"PORT_ERROR"; - case CLIENT_TOO_OLD: - return @"CLIENT_TOO_OLD"; - default: - return @""; - } -} - -- (NSString*)typeString { - switch(_type) { - case PUBLIC: - return @"PUBLIC"; - case PRIVATE: - return @"PRIVATE"; - default: - return @""; - } -} - -- (BOOL)hasSameNetworkId:(UInt64)networkId -{ - return self.nwid == networkId; -} - -- (BOOL)isEqualToNetwork:(Network*)network -{ - return [self.assignedAddresses isEqualToArray:network.assignedAddresses] && - self.bridge == network.bridge && - self.broadcastEnabled == network.broadcastEnabled && - self.dhcp == network.dhcp && - [self.mac isEqualToString:network.mac] && - self.mtu == network.mtu && - self.netconfRevision == network.netconfRevision && - [self.name isEqualToString:network.name] && - self.nwid == network.nwid && - [self.portDeviceName isEqualToString:network.portDeviceName] && - self.status == network.status && - self.type == network.type && - self.allowManaged == network.allowManaged && - self.allowGlobal == network.allowGlobal && - self.allowDefault == network.allowDefault && - self.connected == network.connected; -} - -- (BOOL)isEqual:(id)object -{ - if (self == object) { - return YES; - } - - if (![object isKindOfClass:[Network class]]) { - return NO; - } - - return [self isEqualToNetwork:object]; -} - -- (NSUInteger)hash -{ - return [self.assignedAddresses hash] ^ - self.bridge ^ - self.broadcastEnabled ^ - self.dhcp ^ - [self.mac hash] ^ - self.mtu ^ - self.netconfRevision ^ - [self.name hash] ^ - self.nwid ^ - [self.portDeviceName hash] ^ - self.portError ^ - self.status ^ - self.type ^ - self.allowManaged ^ - self.allowGlobal ^ - self.allowDefault ^ - self.connected; -} - -@end diff --git a/attic/macui/ZeroTier One/NetworkInfoCell.h b/attic/macui/ZeroTier One/NetworkInfoCell.h deleted file mode 100644 index be9345d70..000000000 --- a/attic/macui/ZeroTier One/NetworkInfoCell.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import - -@class ShowNetworksViewController; - -@interface NetworkInfoCell : NSTableCellView - -@property (weak, nonatomic) ShowNetworksViewController *parent; - -@property (weak, nonatomic) IBOutlet NSTextField *networkIdField; -@property (weak, nonatomic) IBOutlet NSTextField *networkNameField; -@property (weak, nonatomic) IBOutlet NSTextField *statusField; -@property (weak, nonatomic) IBOutlet NSTextField *typeField; -@property (weak, nonatomic) IBOutlet NSTextField *macField; -@property (weak, nonatomic) IBOutlet NSTextField *mtuField; -@property (weak, nonatomic) IBOutlet NSTextField *broadcastField; -@property (weak, nonatomic) IBOutlet NSTextField *bridgingField; -@property (weak, nonatomic) IBOutlet NSTextField *deviceField; -@property (weak, nonatomic) IBOutlet NSTextField *addressesField; -@property (weak, nonatomic) IBOutlet NSButton *allowManaged; -@property (weak, nonatomic) IBOutlet NSButton *allowGlobal; -@property (weak, nonatomic) IBOutlet NSButton *allowDefault; -@property (weak, nonatomic) IBOutlet NSButton *connectedCheckbox; -@property (weak, nonatomic) IBOutlet NSButton *deleteButton; - -- (IBAction)onConnectCheckStateChanged:(NSButton*)sender; -- (IBAction)deleteNetwork:(NSButton*)sender; -- (IBAction)onAllowStatusChanged:(NSButton*)sender; - -- (void)joinNetwork:(NSString*)nwid; -- (void)leaveNetwork:(NSString*)nwid; - -@end diff --git a/attic/macui/ZeroTier One/NetworkInfoCell.m b/attic/macui/ZeroTier One/NetworkInfoCell.m deleted file mode 100644 index dc75cab39..000000000 --- a/attic/macui/ZeroTier One/NetworkInfoCell.m +++ /dev/null @@ -1,85 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import "NetworkInfoCell.h" -#import "ServiceCom.h" -#import "ShowNetworksViewController.h" -#import "Network.h" - -@implementation NetworkInfoCell - -- (void)drawRect:(NSRect)dirtyRect { - [super drawRect:dirtyRect]; - - // Drawing code here. -} - -- (IBAction)onConnectCheckStateChanged:(NSButton*)sender -{ - if(sender.state == NSOnState) { - [self joinNetwork:self.networkIdField.stringValue]; - } - else { - [self leaveNetwork:self.networkIdField.stringValue]; - } -} - -- (IBAction)deleteNetwork:(NSButton*)sender; -{ - [self leaveNetwork:self.networkIdField.stringValue]; - [self.parent deleteNetworkFromList:self.networkIdField.stringValue]; -} - -- (IBAction)onAllowStatusChanged:(NSButton*)sender -{ - [self joinNetwork:self.networkIdField.stringValue]; -} - -- (void)joinNetwork:(NSString*)nwid -{ - NSError *error = nil; - [[ServiceCom sharedInstance] joinNetwork:nwid - allowManaged:(self.allowManaged.state == NSOnState) - allowGlobal:(self.allowGlobal.state == NSOnState) - allowDefault:![Network defaultRouteExists:_parent.networkList] && (self.allowDefault.state == NSOnState) - error:&error]; - - if (error) { - NSAlert *alert = [NSAlert alertWithError:error]; - alert.alertStyle = NSCriticalAlertStyle; - [alert addButtonWithTitle:@"Ok"]; - - [alert runModal]; - } -} - -- (void)leaveNetwork:(NSString*)nwid -{ - NSError *error = nil; - [[ServiceCom sharedInstance] leaveNetwork:nwid error:&error]; - - if (error) { - NSAlert *alert = [NSAlert alertWithError:error]; - alert.alertStyle = NSCriticalAlertStyle; - [alert addButtonWithTitle:@"Ok"]; - - [alert runModal]; - } -} - -@end diff --git a/attic/macui/ZeroTier One/NetworkMonitor.h b/attic/macui/ZeroTier One/NetworkMonitor.h deleted file mode 100644 index 8cdec4ed6..000000000 --- a/attic/macui/ZeroTier One/NetworkMonitor.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import - -extern NSString * const NetworkUpdateKey; -extern NSString * const StatusUpdateKey; - -@class Network; - -@interface NetworkMonitor : NSObject -{ - NSMutableArray *_savedNetworks; - NSArray *_receivedNetworks; - NSMutableArray *_allNetworks; - - NSTimer *_timer; -} - -- (id)init; -- (void)dealloc; - -- (void)start; -- (void)stop; - -- (void)updateNetworkInfo; - -- (void)deleteSavedNetwork:(NSString*)networkId; - -@end diff --git a/attic/macui/ZeroTier One/NetworkMonitor.m b/attic/macui/ZeroTier One/NetworkMonitor.m deleted file mode 100644 index 7ed22c4a9..000000000 --- a/attic/macui/ZeroTier One/NetworkMonitor.m +++ /dev/null @@ -1,253 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import "NetworkMonitor.h" -#import "Network.h" -#import "ServiceCom.h" -#import "NodeStatus.h" - -@import AppKit; - - -NSString * const NetworkUpdateKey = @"com.zerotier.one.network-list"; -NSString * const StatusUpdateKey = @"com.zerotier.one.status"; - -@interface NetworkMonitor (private) - -- (NSString*)dataFile; -- (void)internal_updateNetworkInfo; -- (NSInteger)findNetworkWithID:(UInt64)networkId; -- (NSInteger)findSavedNetworkWithID:(UInt64)networkId; -- (void)saveNetworks; - -@end - -@implementation NetworkMonitor - -- (id)init -{ - self = [super init]; - if(self) - { - _savedNetworks = [NSMutableArray array]; - _receivedNetworks = [NSArray array]; - _allNetworks = [NSMutableArray array]; - _timer = nil; - } - - return self; -} - -- (void)dealloc -{ - [_timer invalidate]; -} - -- (void)start -{ - NSLog(@"ZeroTier monitor started"); - _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f - target:self - selector:@selector(updateNetworkInfo) - userInfo:nil - repeats:YES]; -} - -- (void)stop -{ - NSLog(@"ZeroTier monitor stopped"); - [_timer invalidate]; - _timer = nil; -} - -- (void)updateNetworkInfo -{ - NSString *filePath = [self dataFile]; - - if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { - NSArray *networks = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; - - if(networks != nil) { - _savedNetworks = [networks mutableCopy]; - } - } - - NSError *error = nil; - - [[ServiceCom sharedInstance] getNetworklist:^(NSArray *networkList) { - _receivedNetworks = networkList; - - [[NSOperationQueue mainQueue] addOperationWithBlock:^{ - [self internal_updateNetworkInfo]; - } ]; - } error:&error]; - - if(error) { - [self stop]; - - NSAlert *alert = [NSAlert alertWithError:error]; - alert.alertStyle = NSCriticalAlertStyle; - [alert addButtonWithTitle:@"Quit"]; - [alert addButtonWithTitle:@"Retry"]; - - NSModalResponse res = [alert runModal]; - - if(res == NSAlertFirstButtonReturn) { - [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0]; - } - else if(res == NSAlertSecondButtonReturn) { - [self start]; - return; - } - } - - [[ServiceCom sharedInstance] getNodeStatus:^(NodeStatus *status) { - NSDictionary *userInfo = [NSDictionary dictionaryWithObject:status forKey:@"status"]; - - [[NSOperationQueue mainQueue] addOperationWithBlock:^{ - [[NSNotificationCenter defaultCenter] postNotificationName:StatusUpdateKey - object:nil - userInfo:userInfo]; - }]; - } error:&error]; - - if (error) { - [self stop]; - - NSAlert *alert = [NSAlert alertWithError:error]; - alert.alertStyle = NSCriticalAlertStyle; - [alert addButtonWithTitle:@"Quit"]; - [alert addButtonWithTitle:@"Retry"]; - - NSModalResponse res = [alert runModal]; - - if(res == NSAlertFirstButtonReturn) { - [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0]; - } - else if(res == NSAlertSecondButtonReturn) { - [self start]; - return; - } - } -} - -- (void)deleteSavedNetwork:(NSString*)networkId -{ - UInt64 nwid = 0; - NSScanner *scanner = [NSScanner scannerWithString:networkId]; - [scanner scanHexLongLong:&nwid]; - - NSInteger index = [self findNetworkWithID:nwid]; - - if(index != NSNotFound) { - [_allNetworks removeObjectAtIndex:index]; - } - - index = [self findSavedNetworkWithID:nwid]; - - if(index != NSNotFound) { - [_savedNetworks removeObjectAtIndex:index]; - } - - [self saveNetworks]; -} - -@end - -@implementation NetworkMonitor (private) -- (NSString*)dataFile -{ - NSURL *appSupport = [[[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory - inDomains:NSUserDomainMask] objectAtIndex:0]; - - appSupport = [[[appSupport URLByAppendingPathComponent:@"ZeroTier"] URLByAppendingPathComponent:@"One"] URLByAppendingPathComponent:@"networkinfo.dat"]; - return appSupport.path; -} - -- (void)internal_updateNetworkInfo -{ - NSMutableArray *networks = [_savedNetworks mutableCopy]; - - for(Network *nw in _receivedNetworks) { - NSInteger index = [self findSavedNetworkWithID:nw.nwid]; - - if(index != NSNotFound) { - [networks setObject:nw atIndexedSubscript:index]; - } - else { - [networks addObject:nw]; - } - } - - [networks sortUsingComparator:^NSComparisonResult(Network *obj1, Network *obj2) { - if(obj1.nwid > obj2.nwid) { - return true; - } - return false; - }]; - - @synchronized(_allNetworks) { - _allNetworks = networks; - } - - [self saveNetworks]; - - NSDictionary *userInfo = [NSDictionary dictionaryWithObject:networks forKey:@"networks"]; - - [[NSNotificationCenter defaultCenter] postNotificationName:NetworkUpdateKey - object:nil - userInfo:userInfo]; -} - -- (NSInteger)findNetworkWithID:(UInt64)networkId -{ - for(int i = 0; i < [_allNetworks count]; ++i) { - Network *nw = [_allNetworks objectAtIndex:i]; - - if(nw.nwid == networkId) { - return i; - } - } - - return NSNotFound; -} - - -- (NSInteger)findSavedNetworkWithID:(UInt64)networkId -{ - for(int i = 0; i < [_savedNetworks count]; ++i) { - Network *nw = [_savedNetworks objectAtIndex:i]; - - if(nw.nwid == networkId) { - return i; - } - } - - return NSNotFound; -} - -- (void)saveNetworks -{ - NSString *filePath = [self dataFile]; - - @synchronized(_allNetworks) { - [NSKeyedArchiver archiveRootObject:_allNetworks toFile:filePath]; - } -} - -@end diff --git a/attic/macui/ZeroTier One/NodeStatus.h b/attic/macui/ZeroTier One/NodeStatus.h deleted file mode 100644 index eab5bfe44..000000000 --- a/attic/macui/ZeroTier One/NodeStatus.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import - -@interface NodeStatus : NSObject - -@property (readonly) NSString *address; -@property (readonly) NSString *publicIdentity; -@property (readonly) BOOL online; -@property (readonly) BOOL tcpFallbackActive; -@property (readonly) int versionMajor; -@property (readonly) int versionMinor; -@property (readonly) int versionRev; -@property (readonly) NSString *version; -@property (readonly) UInt64 clock; - -- (id)initWithJsonData:(NSDictionary*)jsonData; - -@end diff --git a/attic/macui/ZeroTier One/NodeStatus.m b/attic/macui/ZeroTier One/NodeStatus.m deleted file mode 100644 index 3bae3c7da..000000000 --- a/attic/macui/ZeroTier One/NodeStatus.m +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -#import "NodeStatus.h" - -@implementation NodeStatus - -- (id)initWithJsonData:(NSDictionary*)jsonData -{ - self = [super init]; - - if(self) { - _address = (NSString*)[jsonData objectForKey:@"address"]; - _publicIdentity = (NSString*)[jsonData objectForKey:@"publicIdentity"]; - _online = [(NSNumber*)[jsonData objectForKey:@"online"] boolValue]; - _tcpFallbackActive = [(NSNumber*)[jsonData objectForKey:@"tcpFallbackActive"] boolValue]; - _versionMajor = [(NSNumber*)[jsonData objectForKey:@"versionMajor"] intValue]; - _versionMinor = [(NSNumber*)[jsonData objectForKey:@"versionMinor"] intValue]; - _versionRev = [(NSNumber*)[jsonData objectForKey:@"versionRev"] intValue]; - _version = (NSString*)[jsonData objectForKey:@"version"]; - _clock = [(NSNumber*)[jsonData objectForKey:@"clock"] unsignedLongLongValue]; - } - - return self; -} -@end diff --git a/attic/macui/ZeroTier One/PreferencesViewController.h b/attic/macui/ZeroTier One/PreferencesViewController.h deleted file mode 100644 index 56d0fdb82..000000000 --- a/attic/macui/ZeroTier One/PreferencesViewController.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import - -@interface PreferencesViewController : NSViewController - -@property (nonatomic, weak) IBOutlet NSButton *startupCheckBox; - -- (IBAction)onStartupCheckBoxChanged:(NSButton*)sender; - -- (BOOL)isLaunchAtStartup; -- (LSSharedFileListItemRef)itemRefInLoginItems; -- (void)setLaunchAtLoginEnabled:(BOOL)enabled; - -@end diff --git a/attic/macui/ZeroTier One/PreferencesViewController.m b/attic/macui/ZeroTier One/PreferencesViewController.m deleted file mode 100644 index 13927fbaf..000000000 --- a/attic/macui/ZeroTier One/PreferencesViewController.m +++ /dev/null @@ -1,112 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import "PreferencesViewController.h" - -@interface PreferencesViewController () - -@end - -@implementation PreferencesViewController - -- (void)viewDidLoad { - [super viewDidLoad]; - - if([self isLaunchAtStartup]) { - self.startupCheckBox.state = NSOnState; - } - else { - self.startupCheckBox.state = NSOffState; - } -} - -- (IBAction)onStartupCheckBoxChanged:(NSButton *)sender -{ - if(sender.state == NSOnState) { - [self setLaunchAtLoginEnabled:YES]; - } - else { - [self setLaunchAtLoginEnabled:NO]; - } - -} - -- (void)setLaunchAtLoginEnabled:(BOOL)enabled -{ - LSSharedFileListRef loginItemsRef = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); - - if (enabled) { - // Add the app to the LoginItems list. - CFURLRef appUrl = (__bridge CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]; - LSSharedFileListItemRef itemRef = LSSharedFileListInsertItemURL(loginItemsRef, kLSSharedFileListItemLast, NULL, NULL, appUrl, NULL, NULL); - if (itemRef) CFRelease(itemRef); - } - else { - // Remove the app from the LoginItems list. - LSSharedFileListItemRef itemRef = [self itemRefInLoginItems]; - LSSharedFileListItemRemove(loginItemsRef,itemRef); - if (itemRef != nil) CFRelease(itemRef); - } -} - - -- (BOOL)isLaunchAtStartup { - // See if the app is currently in LoginItems. - LSSharedFileListItemRef itemRef = [self itemRefInLoginItems]; - // Store away that boolean. - BOOL isInList = itemRef != nil; - // Release the reference if it exists. - if (itemRef != nil) CFRelease(itemRef); - - return isInList; -} - -- (LSSharedFileListItemRef)itemRefInLoginItems { - LSSharedFileListItemRef itemRef = nil; - - NSString * appPath = [[NSBundle mainBundle] bundlePath]; - - // This will retrieve the path for the application - // For example, /Applications/test.app - CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:appPath]; - - // Create a reference to the shared file list. - LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); - - if (loginItems) { - UInt32 seedValue; - //Retrieve the list of Login Items and cast them to - // a NSArray so that it will be easier to iterate. - NSArray *loginItemsArray = (__bridge NSArray *)LSSharedFileListCopySnapshot(loginItems, &seedValue); - for(int i = 0; i< [loginItemsArray count]; i++){ - LSSharedFileListItemRef currentItemRef = (__bridge LSSharedFileListItemRef)[loginItemsArray - objectAtIndex:i]; - //Resolve the item with URL - if (LSSharedFileListItemResolve(currentItemRef, 0, (CFURLRef*) &url, NULL) == noErr) { - NSString * urlPath = [(__bridge NSURL*)url path]; - if ([urlPath compare:appPath] == NSOrderedSame){ - itemRef = currentItemRef; - } - } - } - } - CFRelease(loginItems); - return itemRef; -} - -@end diff --git a/attic/macui/ZeroTier One/PreferencesViewController.xib b/attic/macui/ZeroTier One/PreferencesViewController.xib deleted file mode 100644 index 62aef4c03..000000000 --- a/attic/macui/ZeroTier One/PreferencesViewController.xib +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/attic/macui/ZeroTier One/ServiceCom.h b/attic/macui/ZeroTier One/ServiceCom.h deleted file mode 100644 index c2b4692f8..000000000 --- a/attic/macui/ZeroTier One/ServiceCom.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import - -@class NodeStatus; -@class Network; - -@interface ServiceCom : NSObject -{ - NSString *baseURL; - NSURLSession *session; - BOOL _isQuitting; - BOOL _resetKey; -} -+ (ServiceCom*)sharedInstance; - -- (id)init; - -- (void)getNetworklist:(void (^)(NSArray*))completionHandler error:(NSError* __autoreleasing *)error; -- (void)getNodeStatus:(void (^)(NodeStatus*))completionHandler error:(NSError*__autoreleasing*)error; -- (void)joinNetwork:(NSString*)networkId allowManaged:(BOOL)allowManaged allowGlobal:(BOOL)allowGlobal allowDefault:(BOOL)allowDefault error:(NSError*__autoreleasing*)error; -- (void)leaveNetwork:(NSString*)networkId error:(NSError*__autoreleasing*)error; - -@end diff --git a/attic/macui/ZeroTier One/ServiceCom.m b/attic/macui/ZeroTier One/ServiceCom.m deleted file mode 100644 index 75b98502f..000000000 --- a/attic/macui/ZeroTier One/ServiceCom.m +++ /dev/null @@ -1,516 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import "ServiceCom.h" -#import "AuthtokenCopy.h" -#import "Network.h" -#import "NodeStatus.h" -@import AppKit; - -@interface ServiceCom (Private) - -- (NSString*)key; - -@end - -@implementation ServiceCom - -+ (ServiceCom*)sharedInstance { - static ServiceCom *sc = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - sc = [[ServiceCom alloc] init]; - }); - return sc; -} - -- (id)init -{ - self = [super init]; - if(self) { - baseURL = @"http://127.0.0.1:9993"; - session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration]]; - _isQuitting = NO; - _resetKey = NO; - } - - return self; -} - -- (NSString*)key:(NSError* __autoreleasing *)err -{ - static NSString *k = nil; - static NSUInteger resetCount = 0; - - @synchronized (self) { - if (_isQuitting) { - return @""; - } - - if (_resetKey && k != nil) { - k = nil; - ++resetCount; - NSLog(@"ResetCount: %lu", (unsigned long)resetCount); - if (resetCount > 10) { - [[NSOperationQueue mainQueue] addOperationWithBlock:^{ - NSAlert *alert = [NSAlert alertWithMessageText:@"Error obtaining Auth Token" - defaultButton:@"Quit" - alternateButton:@"Retry" - otherButton:nil - informativeTextWithFormat:@"Please ensure ZeroTier is installed correctly"]; - alert.alertStyle = NSCriticalAlertStyle; - - NSModalResponse res; - if (!_isQuitting) { - res = [alert runModal]; - } - else { - return; - } - - if(res == 1) { - _isQuitting = YES; - [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0]; - } - }]; - return @""; - } - } - - if (k == nil) { - NSError *error = nil; - NSURL *appSupportDir = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:false error:&error]; - - if (error) { - NSLog(@"Error: %@", error); - return @""; - } - - appSupportDir = [[appSupportDir URLByAppendingPathComponent:@"ZeroTier"] URLByAppendingPathComponent:@"One"]; - NSURL *authtokenURL = [appSupportDir URLByAppendingPathComponent:@"authtoken.secret"]; - - if (!_resetKey && [[NSFileManager defaultManager] fileExistsAtPath:[authtokenURL path]]) { - k = [NSString stringWithContentsOfURL:authtokenURL - encoding:NSUTF8StringEncoding - error:&error]; - - k = [k stringByReplacingOccurrencesOfString:@"\n" withString:@""]; - - if (error) { - NSLog(@"Error: %@", error); - k = nil; - *err = error; - return @""; - } - } - else { - _resetKey = NO; - NSURL *sysAppSupportDir = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSSystemDomainMask appropriateForURL:nil create:false error:nil]; - - sysAppSupportDir = [[sysAppSupportDir URLByAppendingPathComponent:@"ZeroTier"] URLByAppendingPathComponent:@"One"]; - NSURL *sysAuthtokenURL = [sysAppSupportDir URLByAppendingPathComponent:@"authtoken.secret"]; - - if(![[NSFileManager defaultManager] fileExistsAtPath:[sysAuthtokenURL path]]) { - - } - - [[NSFileManager defaultManager] createDirectoryAtURL:appSupportDir - withIntermediateDirectories:YES - attributes:nil - error:&error]; - - if (error) { - NSLog(@"Error: %@", error); - *err = error; - k = nil; - return @""; - } - - AuthorizationRef authRef; - OSStatus status = AuthorizationCreate(nil, nil, kAuthorizationFlagDefaults, &authRef); - - if (status != errAuthorizationSuccess) { - NSLog(@"Authorization Failed! %d", status); - - NSDictionary *userInfo = @{ - NSLocalizedDescriptionKey: NSLocalizedString(@"Couldn't create AuthorizationRef", nil), - }; - *err = [NSError errorWithDomain:@"com.zerotier.one" code:-1 userInfo:userInfo]; - - return @""; - } - - AuthorizationItem authItem; - authItem.name = kAuthorizationRightExecute; - authItem.valueLength = 0; - authItem.flags = 0; - - AuthorizationRights authRights; - authRights.count = 1; - authRights.items = &authItem; - - AuthorizationFlags authFlags = kAuthorizationFlagDefaults | - kAuthorizationFlagInteractionAllowed | - kAuthorizationFlagPreAuthorize | - kAuthorizationFlagExtendRights; - - status = AuthorizationCopyRights(authRef, &authRights, nil, authFlags, nil); - - if (status != errAuthorizationSuccess) { - NSLog(@"Authorization Failed! %d", status); - NSDictionary *userInfo = @{ - NSLocalizedDescriptionKey: NSLocalizedString(@"Couldn't copy authorization rights", nil), - }; - *err = [NSError errorWithDomain:@"com.zerotier.one" code:-1 userInfo:userInfo]; - return @""; - } - - NSString *localKey = getAdminAuthToken(authRef); - AuthorizationFree(authRef, kAuthorizationFlagDestroyRights); - - if (localKey != nil && [localKey lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 0) { - k = localKey; - - [localKey writeToURL:authtokenURL - atomically:YES - encoding:NSUTF8StringEncoding - error:&error]; - - if (error) { - NSLog(@"Error writing token to disk: %@", error); - *err = error; - } - } - } - } - - if (k == nil) { - NSDictionary *userInfo = @{ - NSLocalizedDescriptionKey: NSLocalizedString(@"Unknown error finding authorization key", nil), - }; - *err = [NSError errorWithDomain:@"com.zerotier.one" code:-1 userInfo:userInfo]; - - return @""; - } - } - return k; -} - -- (void)getNetworklist:(void (^)(NSArray *))completionHandler error:(NSError *__autoreleasing*)error -{ - NSString* key = [self key:error]; - if(*error) { - return; - } - - NSString *urlString = [[baseURL stringByAppendingString:@"/network?auth="] stringByAppendingString:key]; - - NSURL *url = [NSURL URLWithString:urlString]; - NSURLSessionDataTask *task = - [session dataTaskWithURL:url - completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable err) { - - if (err) { - [[NSOperationQueue mainQueue] addOperationWithBlock:^{ - NSAlert *alert = [NSAlert alertWithError:err]; - alert.alertStyle = NSCriticalAlertStyle; - [alert addButtonWithTitle:@"Quit"]; - [alert addButtonWithTitle:@"Retry"]; - - NSModalResponse res; - if (!_isQuitting) { - res = [alert runModal]; - } - else { - return; - } - - if(res == NSAlertFirstButtonReturn) { - [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0]; - _isQuitting = YES; - } - }]; - return; - } - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response; - NSInteger status = [httpResponse statusCode]; - - NSError *err2; - - if (status == 200) { - NSArray *json = [NSJSONSerialization JSONObjectWithData:data - options:0 - error:&err2]; - if (err) { - NSLog(@"Error fetching network list: %@", err2); - - [[NSOperationQueue mainQueue] addOperationWithBlock:^{ - NSAlert *alert = [NSAlert alertWithError:err2]; - alert.alertStyle = NSCriticalAlertStyle; - [alert addButtonWithTitle:@"Quit"]; - [alert addButtonWithTitle:@"Retry"]; - - NSModalResponse res; - if (!_isQuitting) { - res = [alert runModal]; - } - else { - return; - } - - if(res == NSAlertFirstButtonReturn) { - _isQuitting = YES; - [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0]; - } - }]; - return; - } - - NSMutableArray *networks = [[NSMutableArray alloc] init]; - for(NSDictionary *dict in json) { - [networks addObject:[[Network alloc] initWithJsonData:dict]]; - } - - completionHandler(networks); - } - else if (status == 401) { - self->_resetKey = YES; - } - }]; - [task resume]; -} - -- (void)getNodeStatus:(void (^)(NodeStatus*))completionHandler error:(NSError*__autoreleasing*)error -{ - NSString *key = [self key:error]; - if(*error) { - return; - } - - NSString *urlString = [[baseURL stringByAppendingString:@"/status?auth="] stringByAppendingString:key]; - - NSURL *url = [NSURL URLWithString:urlString]; - NSURLSessionDataTask *task = - [session dataTaskWithURL:url - completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable err) { - - if(err) { - [[NSOperationQueue mainQueue] addOperationWithBlock:^{ - NSAlert *alert = [NSAlert alertWithError:err]; - alert.alertStyle = NSCriticalAlertStyle; - [alert addButtonWithTitle:@"Quit"]; - [alert addButtonWithTitle:@"Retry"]; - - NSModalResponse res; - if (!_isQuitting) { - res = [alert runModal]; - } - else { - return; - } - - if(res == NSAlertFirstButtonReturn) { - [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0]; - _isQuitting = YES; - } - }]; - return; - } - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response; - NSInteger status = [httpResponse statusCode]; - - NSError *err2; - if(status == 200) { - NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data - options:0 - error:&err2]; - - if(err2) { - NSLog(@"Error fetching node status: %@", err2); - [[NSOperationQueue mainQueue] addOperationWithBlock:^{ - NSAlert *alert = [NSAlert alertWithError:err2]; - alert.alertStyle = NSCriticalAlertStyle; - [alert addButtonWithTitle:@"Quit"]; - [alert addButtonWithTitle:@"Retry"]; - - NSModalResponse res; - if (!_isQuitting) { - res = [alert runModal]; - } - else { - return; - } - - if(res == NSAlertFirstButtonReturn) { - [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0]; - _isQuitting = YES; - } - }]; - return; - } - - NodeStatus *status = [[NodeStatus alloc] initWithJsonData:json]; - - completionHandler(status); - } - else if (status == 401) { - self->_resetKey = YES; - } - }]; - [task resume]; -} - -- (void)joinNetwork:(NSString*)networkId allowManaged:(BOOL)allowManaged allowGlobal:(BOOL)allowGlobal allowDefault:(BOOL)allowDefault error:(NSError *__autoreleasing*)error -{ - NSString *key = [self key:error]; - if(*error) { - return; - } - - NSString *urlString = [[[[baseURL stringByAppendingString:@"/network/"] - stringByAppendingString:networkId] - stringByAppendingString:@"?auth="] - stringByAppendingString:key]; - - NSURL *url = [NSURL URLWithString:urlString]; - - NSMutableDictionary *jsonDict = [NSMutableDictionary dictionary]; - [jsonDict setObject:[NSNumber numberWithBool:allowManaged] forKey:@"allowManaged"]; - [jsonDict setObject:[NSNumber numberWithBool:allowGlobal] forKey:@"allowGlobal"]; - [jsonDict setObject:[NSNumber numberWithBool:allowDefault] forKey:@"allowDefault"]; - - NSError *err = nil; - - NSData *json = [NSJSONSerialization dataWithJSONObject:jsonDict - options:0 - error:&err]; - - if(err) { - NSLog(@"Error creating json data: %@", err); - *error = err; - return; - } - - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; - request.HTTPMethod = @"POST"; - request.HTTPBody = json; - [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; - - NSURLSessionDataTask *task = - [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable err) { - if(err) { - NSLog(@"Error posting join request: %@", err); - [[NSOperationQueue mainQueue] addOperationWithBlock:^{ - NSAlert *alert = [NSAlert alertWithError:err]; - alert.alertStyle = NSCriticalAlertStyle; - [alert addButtonWithTitle:@"Quit"]; - [alert addButtonWithTitle:@"Retry"]; - - NSModalResponse res; - if (!_isQuitting) { - res = [alert runModal]; - } - else { - return; - } - - if(res == NSAlertFirstButtonReturn) { - [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0]; - _isQuitting = YES; - } - }]; - } - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response; - NSInteger status = [httpResponse statusCode]; - - if(status == 200) { - NSLog(@"join ok"); - } - else if (status == 401) { - self->_resetKey = YES; - } - else { - NSLog(@"join error: %ld", (long)status); - } - }]; - [task resume]; -} - -- (void)leaveNetwork:(NSString*)networkId error:(NSError*__autoreleasing*)error -{ - NSString *key = [self key:error]; - if(*error) { - return; - } - - NSString *urlString = [[[[baseURL stringByAppendingString:@"/network/"] - stringByAppendingString:networkId] - stringByAppendingString:@"?auth="] - stringByAppendingString:key]; - - NSURL *url = [NSURL URLWithString:urlString]; - - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; - request.HTTPMethod = @"DELETE"; - - NSURLSessionDataTask *task = - [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable err) { - if(err) { - NSLog(@"Error posting delete request: %@", err); - [[NSOperationQueue mainQueue] addOperationWithBlock:^{ - NSAlert *alert = [NSAlert alertWithError:err]; - alert.alertStyle = NSCriticalAlertStyle; - [alert addButtonWithTitle:@"Quit"]; - [alert addButtonWithTitle:@"Retry"]; - - NSModalResponse res; - if (!_isQuitting) { - res = [alert runModal]; - } - else { - return; - } - - if(res == NSAlertFirstButtonReturn) { - [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0]; - _isQuitting = YES; - } - }]; - return; - } - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response; - NSInteger status = httpResponse.statusCode; - - if(status == 200) { - NSLog(@"leave ok"); - } - else if (status == 401) { - self->_resetKey = YES; - } - else { - NSLog(@"leave error: %ld", status); - } - }]; - [task resume]; -} - -@end diff --git a/attic/macui/ZeroTier One/ShowNetworksViewController.h b/attic/macui/ZeroTier One/ShowNetworksViewController.h deleted file mode 100644 index 6138958d3..000000000 --- a/attic/macui/ZeroTier One/ShowNetworksViewController.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import - -@class NetworkMonitor; -@class Network; - -@interface ShowNetworksViewController : NSViewController - -@property (nonatomic) NSMutableArray *networkList; -@property (nonatomic) NetworkMonitor *netMonitor; -@property (nonatomic) BOOL visible; - -@property (weak, nonatomic) IBOutlet NSTableView *tableView; - -- (void)deleteNetworkFromList:(NSString*)nwid; -- (void)setNetworks:(NSArray*)list; - - -@end diff --git a/attic/macui/ZeroTier One/ShowNetworksViewController.m b/attic/macui/ZeroTier One/ShowNetworksViewController.m deleted file mode 100644 index 903a4b447..000000000 --- a/attic/macui/ZeroTier One/ShowNetworksViewController.m +++ /dev/null @@ -1,181 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import "ShowNetworksViewController.h" -#import "NetworkMonitor.h" -#import "NetworkInfoCell.h" -#import "Network.h" - -BOOL hasNetworkWithID(NSArray *list, UInt64 nwid) -{ - for(Network *n in list) { - if(n.nwid == nwid) { - return YES; - } - } - - return NO; -} - -@interface ShowNetworksViewController () - -@end - -@implementation ShowNetworksViewController - -- (void)viewDidLoad { - [super viewDidLoad]; - - self.networkList = [NSMutableArray array]; - - [self.tableView setDelegate:self]; - [self.tableView setDataSource:self]; - [self.tableView setBackgroundColor:[NSColor clearColor]]; -} - -- (void)viewWillAppear { - [super viewWillAppear]; - self.visible = YES; -} - -- (void)viewWillDisappear { - [super viewWillDisappear]; - self.visible = NO; -} - -- (NSInteger)findNetworkWithID:(UInt64)networkId -{ - for(int i = 0; i < [_networkList count]; ++i) { - Network *nw = [_networkList objectAtIndex:i]; - - if(nw.nwid == networkId) { - return i; - } - } - - return NSNotFound; -} - - -- (void)deleteNetworkFromList:(NSString *)nwid { - [self.netMonitor deleteSavedNetwork:nwid]; - - UInt64 netid = 0; - NSScanner *scanner = [NSScanner scannerWithString:nwid]; - [scanner scanHexLongLong:&netid]; - for (Network *n in _networkList) { - if (n.nwid == netid) { - NSInteger index = [self findNetworkWithID:netid]; - - if (index != NSNotFound) { - [_networkList removeObjectAtIndex:index]; - [_tableView reloadData]; - } - } - } -} - -- (void)setNetworks:(NSArray *)list { - for (Network *n in list) { - if ([_networkList containsObject:n]) { - // don't need to do anything here. Already an identical object in the list - continue; - } - else { - // network not in the list based on equality. Did an object change? or is it a new item? - if (hasNetworkWithID(_networkList, n.nwid)) { - - for (int i = 0; i < [_networkList count]; ++i) { - Network *n2 = [_networkList objectAtIndex:i]; - if (n.nwid == n2.nwid) - { - [_networkList replaceObjectAtIndex:i withObject:n]; - [_tableView reloadDataForRowIndexes:[NSIndexSet indexSetWithIndex:i] - columnIndexes:[NSIndexSet indexSetWithIndex:0]]; - } - } - } - else { - [_networkList addObject:n]; - [_tableView reloadData]; - } - } - } -} - -- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView { - return [_networkList count]; -} - -- (NSView*)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row -{ - NetworkInfoCell *cell = (NetworkInfoCell*)[tableView makeViewWithIdentifier:@"NetworkInfoCell" - owner:nil]; - Network *network = [_networkList objectAtIndex:row]; - cell.parent = self; - cell.networkIdField.stringValue = [NSString stringWithFormat:@"%10llx", network.nwid]; - cell.networkNameField.stringValue = network.name; - cell.statusField.stringValue = [network statusString]; - cell.typeField.stringValue = [network typeString]; - cell.mtuField.stringValue = [NSString stringWithFormat:@"%d", network.mtu]; - cell.macField.stringValue = network.mac; - cell.broadcastField.stringValue = network.broadcastEnabled ? @"ENABLED" : @"DISABLED"; - cell.bridgingField.stringValue = network.bridge ? @"ENABLED" : @"DISABLED"; - cell.deviceField.stringValue = network.portDeviceName; - - if(network.connected) { - cell.connectedCheckbox.state = NSOnState; - - if(network.allowDefault) { - cell.allowDefault.enabled = YES; - cell.allowDefault.state = NSOnState; - } - else { - cell.allowDefault.state = NSOffState; - - if([Network defaultRouteExists:_networkList]) { - cell.allowDefault.enabled = NO; - } - else { - cell.allowDefault.enabled = YES; - } - } - - cell.allowGlobal.enabled = YES; - cell.allowManaged.enabled = YES; - } - else { - cell.connectedCheckbox.state = NSOffState; - cell.allowDefault.enabled = NO; - cell.allowGlobal.enabled = NO; - cell.allowManaged.enabled = NO; - } - - cell.allowGlobal.state = network.allowGlobal ? NSOnState : NSOffState; - cell.allowManaged.state = network.allowManaged ? NSOnState : NSOffState; - - cell.addressesField.stringValue = @""; - - for(NSString *addr in network.assignedAddresses) { - cell.addressesField.stringValue = [[cell.addressesField.stringValue stringByAppendingString:addr] stringByAppendingString:@"\n"]; - } - - return cell; -} - -@end diff --git a/attic/macui/ZeroTier One/ShowNetworksViewController.xib b/attic/macui/ZeroTier One/ShowNetworksViewController.xib deleted file mode 100644 index 62ac289a2..000000000 --- a/attic/macui/ZeroTier One/ShowNetworksViewController.xib +++ /dev/null @@ -1,371 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/attic/macui/ZeroTier One/ZeroTierIcon.icns b/attic/macui/ZeroTier One/ZeroTierIcon.icns deleted file mode 100644 index 17e60d587..000000000 Binary files a/attic/macui/ZeroTier One/ZeroTierIcon.icns and /dev/null differ diff --git a/attic/macui/ZeroTier One/about.html b/attic/macui/ZeroTier One/about.html deleted file mode 100644 index 09f6eb36a..000000000 --- a/attic/macui/ZeroTier One/about.html +++ /dev/null @@ -1,58 +0,0 @@ - - - - - -
-
-

Welcome to ZeroTier

-

Getting Started

-

Networks are identified by 16-digit network IDs. If someone invited you to join theirs you probably received one. If not you can create your own at my.zerotier.com or by running running your own network controller. -

Your computer is identified by a 10-digit ZeroTier address. You can find it at the top of the ZeroTier app's pull-down menu or by typing "sudo zerotier-cli info" in a terminal window. This number is unique to your system and is how network administrators can recognize you. If someone invited you to a network, give them this ID so they can authorize you to join.

-

Starting, Stopping, and Uninstalling

-

The ZeroTier service is separate from the UI app and starts on system boot. The app can be started on login or only when needed. To stop the ZeroTier service use:

-      sudo launchctl unload /Library/LaunchDaemons/com.zerotier.one.plist

- Replace "unload" with "load" to start it again.

-

ZeroTier can be uninstalled with:

-      sudo '/Library/Application Support/ZeroTier/One/uninstall.sh' -

-

For more information, visit zerotier.com.

-
- - \ No newline at end of file diff --git a/attic/macui/ZeroTier One/main.m b/attic/macui/ZeroTier One/main.m deleted file mode 100644 index 108a6bd18..000000000 --- a/attic/macui/ZeroTier One/main.m +++ /dev/null @@ -1,23 +0,0 @@ -/* - * ZeroTier One - Network Virtualization Everywhere - * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#import - -int main(int argc, const char * argv[]) { - return NSApplicationMain(argc, argv); -} diff --git a/attic/webview/.clang-format b/attic/webview/.clang-format deleted file mode 100644 index 5dad5a60a..000000000 --- a/attic/webview/.clang-format +++ /dev/null @@ -1,111 +0,0 @@ ---- -Language: Cpp -# BasedOnStyle: LLVM -AccessModifierOffset: -2 -AlignAfterOpenBracket: Align -AlignConsecutiveAssignments: false -AlignConsecutiveDeclarations: false -AlignEscapedNewlines: Right -AlignOperands: true -AlignTrailingComments: true -AllowAllParametersOfDeclarationOnNextLine: true -AllowShortBlocksOnASingleLine: false -AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: All -AllowShortIfStatementsOnASingleLine: false -AllowShortLoopsOnASingleLine: false -AlwaysBreakAfterDefinitionReturnType: None -AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: false -AlwaysBreakTemplateDeclarations: false -BinPackArguments: true -BinPackParameters: true -BraceWrapping: - AfterClass: false - AfterControlStatement: false - AfterEnum: false - AfterFunction: false - AfterNamespace: false - AfterObjCDeclaration: false - AfterStruct: false - AfterUnion: false - AfterExternBlock: false - BeforeCatch: false - BeforeElse: false - IndentBraces: false - SplitEmptyFunction: true - SplitEmptyRecord: true - SplitEmptyNamespace: true -BreakBeforeBinaryOperators: None -BreakBeforeBraces: Attach -BreakBeforeInheritanceComma: false -BreakBeforeTernaryOperators: true -BreakConstructorInitializersBeforeComma: false -BreakConstructorInitializers: BeforeColon -BreakAfterJavaFieldAnnotations: false -BreakStringLiterals: true -ColumnLimit: 80 -CommentPragmas: '^ IWYU pragma:' -CompactNamespaces: false -ConstructorInitializerAllOnOneLineOrOnePerLine: false -ConstructorInitializerIndentWidth: 4 -ContinuationIndentWidth: 4 -Cpp11BracedListStyle: true -DerivePointerAlignment: false -DisableFormat: false -ExperimentalAutoDetectBinPacking: false -FixNamespaceComments: true -ForEachMacros: - - foreach - - Q_FOREACH - - BOOST_FOREACH -IncludeBlocks: Preserve -IncludeCategories: - - Regex: '^"(llvm|llvm-c|clang|clang-c)/' - Priority: 2 - - Regex: '^(<|"(gtest|gmock|isl|json)/)' - Priority: 3 - - Regex: '.*' - Priority: 1 -IncludeIsMainRegex: '(Test)?$' -IndentCaseLabels: false -IndentPPDirectives: None -IndentWidth: 2 -IndentWrappedFunctionNames: false -JavaScriptQuotes: Leave -JavaScriptWrapImports: true -KeepEmptyLinesAtTheStartOfBlocks: true -MacroBlockBegin: '' -MacroBlockEnd: '' -MaxEmptyLinesToKeep: 1 -NamespaceIndentation: None -ObjCBlockIndentWidth: 2 -ObjCSpaceAfterProperty: false -ObjCSpaceBeforeProtocolList: true -PenaltyBreakAssignment: 2 -PenaltyBreakBeforeFirstCallParameter: 19 -PenaltyBreakComment: 300 -PenaltyBreakFirstLessLess: 120 -PenaltyBreakString: 1000 -PenaltyExcessCharacter: 1000000 -PenaltyReturnTypeOnItsOwnLine: 60 -PointerAlignment: Right -ReflowComments: true -SortIncludes: true -SortUsingDeclarations: true -SpaceAfterCStyleCast: false -SpaceAfterTemplateKeyword: true -SpaceBeforeAssignmentOperators: true -SpaceBeforeParens: ControlStatements -SpaceInEmptyParentheses: false -SpacesBeforeTrailingComments: 1 -SpacesInAngles: false -SpacesInContainerLiterals: true -SpacesInCStyleCastParentheses: false -SpacesInParentheses: false -SpacesInSquareBrackets: false -Standard: Cpp11 -TabWidth: 8 -UseTab: Never -... - diff --git a/attic/webview/.clang-tidy b/attic/webview/.clang-tidy deleted file mode 100644 index cc8f6eb3d..000000000 --- a/attic/webview/.clang-tidy +++ /dev/null @@ -1,256 +0,0 @@ ---- -Checks: 'clang-diagnostic-*,clang-analyzer-*,*' -HeaderFilterRegex: '' -AnalyzeTemporaryDtors: false -User: serge -CheckOptions: - - key: bugprone-argument-comment.StrictMode - value: '0' - - key: bugprone-assert-side-effect.AssertMacros - value: assert - - key: bugprone-assert-side-effect.CheckFunctionCalls - value: '0' - - key: bugprone-dangling-handle.HandleClasses - value: 'std::basic_string_view;std::experimental::basic_string_view' - - key: bugprone-string-constructor.LargeLengthThreshold - value: '8388608' - - key: bugprone-string-constructor.WarnOnLargeLength - value: '1' - - key: cert-dcl59-cpp.HeaderFileExtensions - value: ',h,hh,hpp,hxx' - - key: cert-err09-cpp.CheckThrowTemporaries - value: '1' - - key: cert-err61-cpp.CheckThrowTemporaries - value: '1' - - key: cert-oop11-cpp.IncludeStyle - value: llvm - - key: cppcoreguidelines-no-malloc.Allocations - value: '::malloc;::calloc' - - key: cppcoreguidelines-no-malloc.Deallocations - value: '::free' - - key: cppcoreguidelines-no-malloc.Reallocations - value: '::realloc' - - key: cppcoreguidelines-owning-memory.LegacyResourceConsumers - value: '::free;::realloc;::freopen;::fclose' - - key: cppcoreguidelines-owning-memory.LegacyResourceProducers - value: '::malloc;::aligned_alloc;::realloc;::calloc;::fopen;::freopen;::tmpfile' - - key: cppcoreguidelines-pro-bounds-constant-array-index.GslHeader - value: '' - - key: cppcoreguidelines-pro-bounds-constant-array-index.IncludeStyle - value: '0' - - key: cppcoreguidelines-pro-type-member-init.IgnoreArrays - value: '0' - - key: cppcoreguidelines-special-member-functions.AllowMissingMoveFunctions - value: '0' - - key: cppcoreguidelines-special-member-functions.AllowSoleDefaultDtor - value: '0' - - key: google-build-namespaces.HeaderFileExtensions - value: ',h,hh,hpp,hxx' - - key: google-global-names-in-headers.HeaderFileExtensions - value: ',h,hh,hpp,hxx' - - key: google-readability-braces-around-statements.ShortStatementLines - value: '1' - - key: google-readability-function-size.BranchThreshold - value: '4294967295' - - key: google-readability-function-size.LineThreshold - value: '4294967295' - - key: google-readability-function-size.NestingThreshold - value: '4294967295' - - key: google-readability-function-size.ParameterThreshold - value: '4294967295' - - key: google-readability-function-size.StatementThreshold - value: '800' - - key: google-readability-namespace-comments.ShortNamespaceLines - value: '10' - - key: google-readability-namespace-comments.SpacesBeforeComments - value: '2' - - key: google-runtime-int.SignedTypePrefix - value: int - - key: google-runtime-int.TypeSuffix - value: '' - - key: google-runtime-int.UnsignedTypePrefix - value: uint - - key: google-runtime-references.WhiteListTypes - value: '' - - key: hicpp-braces-around-statements.ShortStatementLines - value: '0' - - key: hicpp-function-size.BranchThreshold - value: '4294967295' - - key: hicpp-function-size.LineThreshold - value: '4294967295' - - key: hicpp-function-size.NestingThreshold - value: '4294967295' - - key: hicpp-function-size.ParameterThreshold - value: '4294967295' - - key: hicpp-function-size.StatementThreshold - value: '800' - - key: hicpp-member-init.IgnoreArrays - value: '0' - - key: hicpp-move-const-arg.CheckTriviallyCopyableMove - value: '1' - - key: hicpp-named-parameter.IgnoreFailedSplit - value: '0' - - key: hicpp-no-malloc.Allocations - value: '::malloc;::calloc' - - key: hicpp-no-malloc.Deallocations - value: '::free' - - key: hicpp-no-malloc.Reallocations - value: '::realloc' - - key: hicpp-special-member-functions.AllowMissingMoveFunctions - value: '0' - - key: hicpp-special-member-functions.AllowSoleDefaultDtor - value: '0' - - key: hicpp-use-auto.RemoveStars - value: '0' - - key: hicpp-use-emplace.ContainersWithPushBack - value: '::std::vector;::std::list;::std::deque' - - key: hicpp-use-emplace.SmartPointers - value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' - - key: hicpp-use-emplace.TupleMakeFunctions - value: '::std::make_pair;::std::make_tuple' - - key: hicpp-use-emplace.TupleTypes - value: '::std::pair;::std::tuple' - - key: hicpp-use-equals-default.IgnoreMacros - value: '1' - - key: hicpp-use-noexcept.ReplacementString - value: '' - - key: hicpp-use-noexcept.UseNoexceptFalse - value: '1' - - key: hicpp-use-nullptr.NullMacros - value: '' - - key: llvm-namespace-comment.ShortNamespaceLines - value: '1' - - key: llvm-namespace-comment.SpacesBeforeComments - value: '1' - - key: misc-definitions-in-headers.HeaderFileExtensions - value: ',h,hh,hpp,hxx' - - key: misc-definitions-in-headers.UseHeaderFileExtension - value: '1' - - key: misc-misplaced-widening-cast.CheckImplicitCasts - value: '0' - - key: misc-sizeof-expression.WarnOnSizeOfCompareToConstant - value: '1' - - key: misc-sizeof-expression.WarnOnSizeOfConstant - value: '1' - - key: misc-sizeof-expression.WarnOnSizeOfThis - value: '1' - - key: misc-suspicious-enum-usage.StrictMode - value: '0' - - key: misc-suspicious-missing-comma.MaxConcatenatedTokens - value: '5' - - key: misc-suspicious-missing-comma.RatioThreshold - value: '0.200000' - - key: misc-suspicious-missing-comma.SizeThreshold - value: '5' - - key: misc-suspicious-string-compare.StringCompareLikeFunctions - value: '' - - key: misc-suspicious-string-compare.WarnOnImplicitComparison - value: '1' - - key: misc-suspicious-string-compare.WarnOnLogicalNotComparison - value: '0' - - key: misc-throw-by-value-catch-by-reference.CheckThrowTemporaries - value: '1' - - key: modernize-loop-convert.MaxCopySize - value: '16' - - key: modernize-loop-convert.MinConfidence - value: reasonable - - key: modernize-loop-convert.NamingStyle - value: CamelCase - - key: modernize-make-shared.IgnoreMacros - value: '1' - - key: modernize-make-shared.IncludeStyle - value: '0' - - key: modernize-make-shared.MakeSmartPtrFunction - value: 'std::make_shared' - - key: modernize-make-shared.MakeSmartPtrFunctionHeader - value: memory - - key: modernize-make-unique.IgnoreMacros - value: '1' - - key: modernize-make-unique.IncludeStyle - value: '0' - - key: modernize-make-unique.MakeSmartPtrFunction - value: 'std::make_unique' - - key: modernize-make-unique.MakeSmartPtrFunctionHeader - value: memory - - key: modernize-pass-by-value.IncludeStyle - value: llvm - - key: modernize-pass-by-value.ValuesOnly - value: '0' - - key: modernize-raw-string-literal.ReplaceShorterLiterals - value: '0' - - key: modernize-replace-auto-ptr.IncludeStyle - value: llvm - - key: modernize-replace-random-shuffle.IncludeStyle - value: llvm - - key: modernize-use-auto.RemoveStars - value: '0' - - key: modernize-use-default-member-init.IgnoreMacros - value: '1' - - key: modernize-use-default-member-init.UseAssignment - value: '0' - - key: modernize-use-emplace.ContainersWithPushBack - value: '::std::vector;::std::list;::std::deque' - - key: modernize-use-emplace.SmartPointers - value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' - - key: modernize-use-emplace.TupleMakeFunctions - value: '::std::make_pair;::std::make_tuple' - - key: modernize-use-emplace.TupleTypes - value: '::std::pair;::std::tuple' - - key: modernize-use-equals-default.IgnoreMacros - value: '1' - - key: modernize-use-noexcept.ReplacementString - value: '' - - key: modernize-use-noexcept.UseNoexceptFalse - value: '1' - - key: modernize-use-nullptr.NullMacros - value: 'NULL' - - key: modernize-use-transparent-functors.SafeMode - value: '0' - - key: modernize-use-using.IgnoreMacros - value: '1' - - key: objc-forbidden-subclassing.ForbiddenSuperClassNames - value: 'ABNewPersonViewController;ABPeoplePickerNavigationController;ABPersonViewController;ABUnknownPersonViewController;NSHashTable;NSMapTable;NSPointerArray;NSPointerFunctions;NSTimer;UIActionSheet;UIAlertView;UIImagePickerController;UITextInputMode;UIWebView' - - key: objc-property-declaration.Acronyms - value: 'ASCII;PDF;XML;HTML;URL;RTF;HTTP;TIFF;JPG;PNG;GIF;LZW;ROM;RGB;CMYK;MIDI;FTP' - - key: performance-faster-string-find.StringLikeClasses - value: 'std::basic_string' - - key: performance-for-range-copy.WarnOnAllAutoCopies - value: '0' - - key: performance-inefficient-string-concatenation.StrictMode - value: '0' - - key: performance-inefficient-vector-operation.VectorLikeClasses - value: '::std::vector' - - key: performance-move-const-arg.CheckTriviallyCopyableMove - value: '1' - - key: performance-move-constructor-init.IncludeStyle - value: llvm - - key: performance-type-promotion-in-math-fn.IncludeStyle - value: llvm - - key: performance-unnecessary-value-param.IncludeStyle - value: llvm - - key: readability-braces-around-statements.ShortStatementLines - value: '0' - - key: readability-function-size.BranchThreshold - value: '4294967295' - - key: readability-function-size.LineThreshold - value: '4294967295' - - key: readability-function-size.NestingThreshold - value: '4294967295' - - key: readability-function-size.ParameterThreshold - value: '4294967295' - - key: readability-function-size.StatementThreshold - value: '800' - - key: readability-identifier-naming.IgnoreFailedSplit - value: '0' - - key: readability-implicit-bool-conversion.AllowIntegerConditions - value: '0' - - key: readability-implicit-bool-conversion.AllowPointerConditions - value: '0' - - key: readability-simplify-boolean-expr.ChainedConditionalAssignment - value: '0' - - key: readability-simplify-boolean-expr.ChainedConditionalReturn - value: '0' - - key: readability-static-accessed-through-instance.NameSpecifierNestingThreshold - value: '3' -... - diff --git a/attic/webview/.gitattributes b/attic/webview/.gitattributes deleted file mode 100644 index 5170675f3..000000000 --- a/attic/webview/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -*.h linguist-language=c diff --git a/attic/webview/.gitignore b/attic/webview/.gitignore deleted file mode 100644 index 6307e1aab..000000000 --- a/attic/webview/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -# Build atrifacts -/build -/examples/minimal-go/minimal-go -/examples/minimal/minimal -/examples/minimal/minimal.exe -/examples/minimal/build -/examples/timer-cxx/build diff --git a/attic/webview/.travis.yml b/attic/webview/.travis.yml deleted file mode 100644 index e94a7765e..000000000 --- a/attic/webview/.travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -language: go - -go: - - 1.x - -matrix: - include: - - os: linux - before_install: - - sudo add-apt-repository ppa:webkit-team/ppa -y - - sudo apt-get update - - sudo apt-get install libwebkit2gtk-4.0-dev -y - env: WEBVIEW=gtk - - os: osx - osx_image: xcode8.3 - env: WEBVIEW=cocoa - -script: - - make example diff --git a/attic/webview/LICENSE b/attic/webview/LICENSE deleted file mode 100644 index b18604bf4..000000000 --- a/attic/webview/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 Serge Zaitsev - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/attic/webview/Makefile b/attic/webview/Makefile deleted file mode 100644 index 71cdf57db..000000000 --- a/attic/webview/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -WEBVIEW_gtk_FLAGS = -DWEBVIEW_GTK -std=c++14 -Wall -Wextra -pedantic $(shell pkg-config --cflags --libs gtk+-3.0 webkit2gtk-4.0) -WEBVIEW_cocoa_FLAGS = -DWEBVIEW_COCOA -std=c++14 -Wall -Wextra -pedantic -framework WebKit -mmacosx-version-min=10.11 -DOBJC_OLD_DISPATCH_PROTOTYPES -WEBVIEW_mshtml_FLAGS := -DWEBVIEW_MSHTML -std=c++14 -luser32 -lole32 -loleaut32 -lcomctl32 -luuid -static -WEBVIEW_edge_FLAGS := -DWEBVIEW_EDGE - -all: - @echo "make WEBVIEW=... test - build and run tests" - @echo "make WEBVIEW=... lint - run clang-tidy checkers" - @echo "make WEBVIEW=... fmt - run clang-format for all sources" - -fmt: webview.h - clang-format -i $^ - -check-env: -ifndef WEBVIEW_$(WEBVIEW)_FLAGS - $(error "Unknown WEBVIEW value, use WEBVIEW=gtk|cocoa|mshtml|edge") -endif - -lint: check-env - clang-tidy example.cc -- $(WEBVIEW_$(WEBVIEW)_FLAGS) - -example: check-env example.cc webview.h - $(CXX) example.cc $(WEBVIEW_$(WEBVIEW)_FLAGS) -o example - -test: check-env - $(CXX) webview_test.cc $(WEBVIEW_$(WEBVIEW)_FLAGS) -o webview_test - ./webview_test - rm webview_test diff --git a/attic/webview/example.cc b/attic/webview/example.cc deleted file mode 100644 index 7afcc5794..000000000 --- a/attic/webview/example.cc +++ /dev/null @@ -1,39 +0,0 @@ -// +build ignore - -#include "webview.h" - -#ifdef _WIN32 -int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, - LPSTR lpCmdLine, int nCmdShow) -#else -int main() -#endif -{ - webview::webview w(true, nullptr); - w.set_title("Example"); - w.set_size(480, 320, true); - w.bind("noop", [](std::string s) -> std::string { printf("%s\n", s.c_str());return s; }); - w.bind("add", [](std::string s) -> std::string { - auto a = std::stoi(webview::json_parse(s, "", 0)); - auto b = std::stoi(webview::json_parse(s, "", 1)); - return std::to_string(a + b); - }); - w.navigate(R"(data:text/html, - - - hello - - - )"); - w.run(); - return 0; -} diff --git a/attic/webview/example/example.go b/attic/webview/example/example.go deleted file mode 100644 index d536a07cb..000000000 --- a/attic/webview/example/example.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "github.com/zserge/webview" -) - -func main() { - w := webview.New(true) - w.Navigate("https://github.com") - w.SetTitle("Hello") - w.Dispatch(func() { - println("Hello dispatch") - }) - w.Run() -} diff --git a/attic/webview/go.mod b/attic/webview/go.mod deleted file mode 100644 index 487f240b9..000000000 --- a/attic/webview/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/zserge/webview - -go 1.13 diff --git a/attic/webview/webview.cc b/attic/webview/webview.cc deleted file mode 100644 index 0d861df50..000000000 --- a/attic/webview/webview.cc +++ /dev/null @@ -1 +0,0 @@ -#include "webview.h" diff --git a/attic/webview/webview.go b/attic/webview/webview.go deleted file mode 100644 index 32595f26a..000000000 --- a/attic/webview/webview.go +++ /dev/null @@ -1,138 +0,0 @@ -package webview - -/* -#cgo linux openbsd freebsd CXXFLAGS: -DWEBVIEW_GTK -std=c++14 -#cgo linux openbsd freebsd pkg-config: gtk+-3.0 webkit2gtk-4.0 - -#cgo darwin CXXFLAGS: -DWEBVIEW_COCOA -std=c++14 -DOBJC_OLD_DISPATCH_PROTOTYPES -#cgo darwin LDFLAGS: -framework WebKit - -#cgo windows CXXFLAGS: -DWEBVIEW_MSHTML -#cgo windows LDFLAGS: -lole32 -lcomctl32 -loleaut32 -luuid -lgdi32 - -#define WEBVIEW_HEADER -#include "webview.h" - -#include -#include - -extern void _webviewDispatchGoCallback(void *); -static inline void _webview_dispatch_cb(webview_t w, void *arg) { - _webviewDispatchGoCallback(arg); -} -static inline void CgoWebViewDispatch(webview_t w, uintptr_t arg) { - webview_dispatch(w, _webview_dispatch_cb, (void *)arg); -} -*/ -import "C" -import ( - "runtime" - "sync" - "unsafe" -) - -func init() { - // Ensure that main.main is called from the main thread - runtime.LockOSThread() -} - -type WebView interface { - Run() - Terminate() - Dispatch(f func()) - Navigate(url string) - SetTitle(title string) - Window() unsafe.Pointer - Init(js string) - Eval(js string) - Destroy() - /* - SetBounds(x, y, width, height int) - Bounds() (x, y, width, height int) - Bind(name string, v interface{}) - */ -} - -type webview struct { - w C.webview_t -} - -var ( - m sync.Mutex - index uintptr - dispatch = map[uintptr]func(){} -) - -func boolToInt(b bool) C.int { - if b { - return 1 - } - return 0 -} - -func New(debug bool) WebView { return NewWindow(debug, nil) } - -func NewWindow(debug bool, window unsafe.Pointer) WebView { - w := &webview{} -q - return w -} - -func (w *webview) Destroy() { - C.webview_destroy(w.w) -} - -func (w *webview) Run() { - C.webview_run(w.w) -} - -func (w *webview) Terminate() { - C.webview_terminate(w.w) -} - -func (w *webview) Window() unsafe.Pointer { - return C.webview_get_window(w.w) -} - -func (w *webview) Navigate(url string) { - s := C.CString(url) - defer C.free(unsafe.Pointer(s)) - C.webview_navigate(w.w, s) -} - -func (w *webview) SetTitle(title string) { - s := C.CString(title) - defer C.free(unsafe.Pointer(s)) - C.webview_set_title(w.w, s) -} - -func (w *webview) Init(js string) { - s := C.CString(js) - defer C.free(unsafe.Pointer(s)) - C.webview_init(w.w, s) -} - -func (w *webview) Eval(js string) { - s := C.CString(js) - defer C.free(unsafe.Pointer(s)) - C.webview_eval(w.w, s) -} - -func (w *webview) Dispatch(f func()) { - m.Lock() - for ; dispatch[index] != nil; index++ { - } - dispatch[index] = f - m.Unlock() - C.CgoWebViewDispatch(w.w, C.uintptr_t(index)) -} - -//export _webviewDispatchGoCallback -func _webviewDispatchGoCallback(index unsafe.Pointer) { - var f func() - m.Lock() - f = dispatch[uintptr(index)] - delete(dispatch, uintptr(index)) - m.Unlock() - f() -} diff --git a/attic/webview/webview.h b/attic/webview/webview.h deleted file mode 100644 index 7a20b9541..000000000 --- a/attic/webview/webview.h +++ /dev/null @@ -1,1248 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2017 Serge Zaitsev - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -#ifndef WEBVIEW_H -#define WEBVIEW_H - -#ifndef WEBVIEW_API -#define WEBVIEW_API extern -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void *webview_t; - -// Create a new webview instance -WEBVIEW_API webview_t webview_create(int debug, void *wnd); - -// Destroy a webview -WEBVIEW_API void webview_destroy(webview_t w); - -// Run the main loop -WEBVIEW_API void webview_run(webview_t w); - -// Stop the main loop -WEBVIEW_API void webview_terminate(webview_t w); - -// Post a function to be executed on the main thread -WEBVIEW_API void -webview_dispatch(webview_t w, void (*fn)(webview_t w, void *arg), void *arg); - -WEBVIEW_API void *webview_get_window(webview_t w); - -WEBVIEW_API void webview_set_title(webview_t w, const char *title); - -WEBVIEW_API void webview_set_bounds(webview_t w, int x, int y, int width, - int height, int flags); -WEBVIEW_API void webview_get_bounds(webview_t w, int *x, int *y, int *width, - int *height, int *flags); - -WEBVIEW_API void webview_navigate(webview_t w, const char *url); -WEBVIEW_API void webview_init(webview_t w, const char *js); -WEBVIEW_API void webview_eval(webview_t w, const char *js); - -#ifdef __cplusplus -} -#endif - -#ifndef WEBVIEW_HEADER - -#if !defined(WEBVIEW_GTK) && !defined(WEBVIEW_COCOA) && \ - !defined(WEBVIEW_MSHTML) && !defined(WEBVIEW_EDGE) -#error "please, specify webview backend" -#endif - -#include -#include -#include -#include -#include -#include - -#include - -namespace webview { -using dispatch_fn_t = std::function; -using msg_cb_t = std::function; - -inline std::string url_encode(std::string s) { - std::string encoded; - for (unsigned int i = 0; i < s.length(); i++) { - auto c = s[i]; - if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { - encoded = encoded + c; - } else { - char hex[4]; - snprintf(hex, sizeof(hex), "%%%02x", c); - encoded = encoded + hex; - } - } - return encoded; -} - -inline std::string url_decode(std::string s) { - std::string decoded; - for (unsigned int i = 0; i < s.length(); i++) { - if (s[i] == '%') { - int n; - sscanf(s.substr(i + 1, 2).c_str(), "%x", &n); - decoded = decoded + static_cast(n); - i = i + 2; - } else if (s[i] == '+') { - decoded = decoded + ' '; - } else { - decoded = decoded + s[i]; - } - } - return decoded; -} - -inline std::string html_from_uri(std::string s) { - if (s.substr(0, 15) == "data:text/html,") { - return url_decode(s.substr(15)); - } - return ""; -} - -inline int json_parse_c(const char *s, size_t sz, const char *key, size_t keysz, - const char **value, size_t *valuesz) { - enum { - JSON_STATE_VALUE, - JSON_STATE_LITERAL, - JSON_STATE_STRING, - JSON_STATE_ESCAPE, - JSON_STATE_UTF8 - } state = JSON_STATE_VALUE; - const char *k = NULL; - int index = 1; - int depth = 0; - int utf8_bytes = 0; - - if (key == NULL) { - index = keysz; - keysz = 0; - } - - *value = NULL; - *valuesz = 0; - - for (; sz > 0; s++, sz--) { - enum { - JSON_ACTION_NONE, - JSON_ACTION_START, - JSON_ACTION_END, - JSON_ACTION_START_STRUCT, - JSON_ACTION_END_STRUCT - } action = JSON_ACTION_NONE; - unsigned char c = *s; - switch (state) { - case JSON_STATE_VALUE: - if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ',' || - c == ':') { - continue; - } else if (c == '"') { - action = JSON_ACTION_START; - state = JSON_STATE_STRING; - } else if (c == '{' || c == '[') { - action = JSON_ACTION_START_STRUCT; - } else if (c == '}' || c == ']') { - action = JSON_ACTION_END_STRUCT; - } else if (c == 't' || c == 'f' || c == 'n' || c == '-' || - (c >= '0' && c <= '9')) { - action = JSON_ACTION_START; - state = JSON_STATE_LITERAL; - } else { - return -1; - } - break; - case JSON_STATE_LITERAL: - if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ',' || - c == ']' || c == '}' || c == ':') { - state = JSON_STATE_VALUE; - s--; - sz++; - action = JSON_ACTION_END; - } else if (c < 32 || c > 126) { - return -1; - } // fallthrough - case JSON_STATE_STRING: - if (c < 32 || (c > 126 && c < 192)) { - return -1; - } else if (c == '"') { - action = JSON_ACTION_END; - state = JSON_STATE_VALUE; - } else if (c == '\\') { - state = JSON_STATE_ESCAPE; - } else if (c >= 192 && c < 224) { - utf8_bytes = 1; - state = JSON_STATE_UTF8; - } else if (c >= 224 && c < 240) { - utf8_bytes = 2; - state = JSON_STATE_UTF8; - } else if (c >= 240 && c < 247) { - utf8_bytes = 3; - state = JSON_STATE_UTF8; - } else if (c >= 128 && c < 192) { - return -1; - } - break; - case JSON_STATE_ESCAPE: - if (c == '"' || c == '\\' || c == '/' || c == 'b' || c == 'f' || - c == 'n' || c == 'r' || c == 't' || c == 'u') { - state = JSON_STATE_STRING; - } else { - return -1; - } - break; - case JSON_STATE_UTF8: - if (c < 128 || c > 191) { - return -1; - } - utf8_bytes--; - if (utf8_bytes == 0) { - state = JSON_STATE_STRING; - } - break; - default: - return -1; - } - - if (action == JSON_ACTION_END_STRUCT) { - depth--; - } - - if (depth == 1) { - if (action == JSON_ACTION_START || action == JSON_ACTION_START_STRUCT) { - if (index == 0) { - *value = s; - } else if (keysz > 0 && index == 1) { - k = s; - } else { - index--; - } - } else if (action == JSON_ACTION_END || - action == JSON_ACTION_END_STRUCT) { - if (*value != NULL && index == 0) { - *valuesz = (size_t)(s + 1 - *value); - return 0; - } else if (keysz > 0 && k != NULL) { - if (keysz == (size_t)(s - k - 1) && memcmp(key, k + 1, keysz) == 0) { - index = 0; - } else { - index = 2; - } - k = NULL; - } - } - } - - if (action == JSON_ACTION_START_STRUCT) { - depth++; - } - } - return -1; -} - -inline std::string json_escape(std::string s) { - // TODO: implement - return '"' + s + '"'; -} - -inline int json_unescape(const char *s, size_t n, char *out) { - int r = 0; - if (*s++ != '"') { - return -1; - } - while (n > 2) { - char c = *s; - if (c == '\\') { - s++; - n--; - switch (*s) { - case 'b': - c = '\b'; - break; - case 'f': - c = '\f'; - break; - case 'n': - c = '\n'; - break; - case 'r': - c = '\r'; - break; - case 't': - c = '\t'; - break; - case '\\': - c = '\\'; - break; - case '/': - c = '/'; - break; - case '\"': - c = '\"'; - break; - default: // TODO: support unicode decoding - return -1; - } - } - if (out != NULL) { - *out++ = c; - } - s++; - n--; - r++; - } - if (*s != '"') { - return -1; - } - if (out != NULL) { - *out = '\0'; - } - return r; -} - -inline std::string json_parse(std::string s, std::string key, int index) { - const char *value; - size_t value_sz; - if (key == "") { - json_parse_c(s.c_str(), s.length(), nullptr, index, &value, &value_sz); - } else { - json_parse_c(s.c_str(), s.length(), key.c_str(), key.length(), &value, - &value_sz); - } - if (value != nullptr) { - if (value[0] != '"') { - return std::string(value, value_sz); - } - int n = json_unescape(value, value_sz, nullptr); - if (n > 0) { - char *decoded = new char[n]; - json_unescape(value, value_sz, decoded); - auto result = std::string(decoded, n); - delete[] decoded; - return result; - } - } - return ""; -} - -} // namespace webview - -#if defined(WEBVIEW_GTK) -// -// ==================================================================== -// -// This implementation uses webkit2gtk backend. It requires gtk+3.0 and -// webkit2gtk-4.0 libraries. Proper compiler flags can be retrieved via: -// -// pkg-config --cflags --libs gtk+-3.0 webkit2gtk-4.0 -// -// ==================================================================== -// -#include -#include -#include - -namespace webview { - -class browser_engine { -public: - browser_engine(msg_cb_t cb, bool debug, void *window) - : m_cb(cb), m_window(static_cast(window)) { - gtk_init_check(0, NULL); - m_window = static_cast(window); - if (m_window == nullptr) { - m_window = gtk_window_new(GTK_WINDOW_TOPLEVEL); - } - g_signal_connect(G_OBJECT(m_window), "destroy", - G_CALLBACK(+[](GtkWidget *w, gpointer arg) { - static_cast(arg)->terminate(); - }), - this); - // Initialize webview widget - m_webview = webkit_web_view_new(); - WebKitUserContentManager *manager = - webkit_web_view_get_user_content_manager(WEBKIT_WEB_VIEW(m_webview)); - g_signal_connect(manager, "script-message-received::external", - G_CALLBACK(+[](WebKitUserContentManager *m, - WebKitJavascriptResult *r, gpointer arg) { - auto *w = static_cast(arg); -#if WEBKIT_MAJOR_VERSION >= 2 && WEBKIT_MINOR_VERSION >= 22 - JSCValue *value = - webkit_javascript_result_get_js_value(r); - char *s = jsc_value_to_string(value); -#else - JSGlobalContextRef ctx = - webkit_javascript_result_get_global_context(r); - JSValueRef value = webkit_javascript_result_get_value(r); - JSStringRef js = JSValueToStringCopy(ctx, value, NULL); - size_t n = JSStringGetMaximumUTF8CStringSize(js); - char *s = g_new(char, n); - JSStringGetUTF8CString(js, s, n); - JSStringRelease(js); -#endif - w->m_cb(s); - g_free(s); - }), - this); - webkit_user_content_manager_register_script_message_handler(manager, - "external"); - init("window.external={invoke:function(s){window.webkit.messageHandlers." - "external.postMessage(s);}}"); - - gtk_container_add(GTK_CONTAINER(m_window), GTK_WIDGET(m_webview)); - gtk_widget_grab_focus(GTK_WIDGET(m_webview)); - - if (debug) { - WebKitSettings *settings = - webkit_web_view_get_settings(WEBKIT_WEB_VIEW(m_webview)); - webkit_settings_set_enable_write_console_messages_to_stdout(settings, - true); - webkit_settings_set_enable_developer_extras(settings, true); - } - - gtk_widget_show_all(m_window); - } - void run() { gtk_main(); } - void terminate() { gtk_main_quit(); } - void dispatch(std::function f) { - g_idle_add_full(G_PRIORITY_HIGH_IDLE, (GSourceFunc)([](void *f) -> int { - (*static_cast(f))(); - return G_SOURCE_REMOVE; - }), - new std::function(f), - [](void *f) { delete static_cast(f); }); - } - - void set_title(const char *title) { - gtk_window_set_title(GTK_WINDOW(m_window), title); - } - - void set_size(int width, int height, bool resizable) { - gtk_window_set_resizable(GTK_WINDOW(m_window), !!resizable); - if (resizable) { - gtk_window_set_default_size(GTK_WINDOW(m_window), width, height); - } else { - gtk_widget_set_size_request(m_window, width, height); - } - } - - void navigate(const char *url) { - webkit_web_view_load_uri(WEBKIT_WEB_VIEW(m_webview), url); - } - - void init(const char *js) { - WebKitUserContentManager *manager = - webkit_web_view_get_user_content_manager(WEBKIT_WEB_VIEW(m_webview)); - webkit_user_content_manager_add_script( - manager, webkit_user_script_new( - js, WEBKIT_USER_CONTENT_INJECT_TOP_FRAME, - WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, NULL, NULL)); - } - - void eval(const char *js) { - webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(m_webview), js, NULL, NULL, - NULL); - } - -protected: - std::function m_cb; - GtkWidget *m_window; - GtkWidget *m_webview; -}; - -} // namespace webview - -#elif defined(WEBVIEW_COCOA) - -// -// ==================================================================== -// -// This implementation uses Cocoa WKWebView backend on macOS. It is -// written using ObjC runtime and uses WKWebView class as a browser runtime. -// You should pass "-framework Webkit" flag to the compiler. -// -// ==================================================================== -// - -#include -#include - -#define NSBackingStoreBuffered 2 - -#define NSWindowStyleMaskResizable 8 -#define NSWindowStyleMaskMiniaturizable 4 -#define NSWindowStyleMaskTitled 1 -#define NSWindowStyleMaskClosable 2 - -#define NSApplicationActivationPolicyRegular 0 - -#define WKUserScriptInjectionTimeAtDocumentStart 0 - -namespace webview { - -id operator"" _cls(const char *s, std::size_t sz) { - return (id)objc_getClass(s); -} -SEL operator"" _sel(const char *s, std::size_t sz) { - return sel_registerName(s); -} -id operator"" _str(const char *s, std::size_t sz) { - return objc_msgSend("NSString"_cls, "stringWithUTF8String:"_sel, s); -} - -class browser_engine { -public: - browser_engine(msg_cb_t cb, bool debug, void *window) : m_cb(cb) { - // Application - id app = objc_msgSend("NSApplication"_cls, "sharedApplication"_sel); - objc_msgSend(app, "setActivationPolicy:"_sel, - NSApplicationActivationPolicyRegular); - - // Delegate - auto cls = objc_allocateClassPair((Class) "NSObject"_cls, "AppDelegate", 0); - class_addProtocol(cls, objc_getProtocol("NSApplicationDelegate")); - class_addProtocol(cls, objc_getProtocol("WKScriptMessageHandler")); - class_addMethod( - cls, "applicationShouldTerminateAfterLastWindowClosed:"_sel, - (IMP)(+[](id self, SEL cmd, id notification) -> BOOL { return 1; }), - "c@:@"); - class_addMethod( - cls, "userContentController:didReceiveScriptMessage:"_sel, - (IMP)(+[](id self, SEL cmd, id notification, id msg) { - auto w = (browser_engine *)objc_getAssociatedObject(self, "webview"); - w->m_cb((const char *)objc_msgSend(objc_msgSend(msg, "body"_sel), - "UTF8String"_sel)); - }), - "v@:@@"); - objc_registerClassPair(cls); - - auto delegate = objc_msgSend((id)cls, "new"_sel); - objc_setAssociatedObject(delegate, "webview", (id)this, - OBJC_ASSOCIATION_ASSIGN); - objc_msgSend(app, sel_registerName("setDelegate:"), delegate); - - // Main window - if (window == nullptr) { - m_window = objc_msgSend("NSWindow"_cls, "alloc"_sel); - m_window = objc_msgSend( - m_window, "initWithContentRect:styleMask:backing:defer:"_sel, - CGRectMake(0, 0, 0, 0), 0, NSBackingStoreBuffered, 0); - set_size(480, 320, true); - } else { - m_window = (id)window; - } - - // Webview - auto config = objc_msgSend("WKWebViewConfiguration"_cls, "new"_sel); - m_manager = objc_msgSend(config, "userContentController"_sel); - m_webview = objc_msgSend("WKWebView"_cls, "alloc"_sel); - objc_msgSend(m_webview, "initWithFrame:configuration:"_sel, - CGRectMake(0, 0, 0, 0), config); - objc_msgSend(m_manager, "addScriptMessageHandler:name:"_sel, delegate, - "external"_str); - init(R"script( - window.external = { - invoke: function(s) { - window.webkit.messageHandlers.external.postMessage(s); - }, - }; - )script"); - if (debug) { - objc_msgSend(objc_msgSend(config, "preferences"_sel), - "setValue:forKey:"_sel, 1, "developerExtrasEnabled"_str); - } - objc_msgSend(m_window, "setContentView:"_sel, m_webview); - objc_msgSend(m_window, "makeKeyAndOrderFront:"_sel, nullptr); - } - ~browser_engine() { objc_msgSend(m_window, "close"_sel); } - void terminate() { objc_msgSend("NSApp"_cls, "terminate:"_sel, nullptr); } - void run() { - id app = objc_msgSend("NSApplication"_cls, "sharedApplication"_sel); - dispatch([&]() { objc_msgSend(app, "activateIgnoringOtherApps:"_sel, 1); }); - objc_msgSend(app, "run"_sel); - } - void dispatch(std::function f) { - dispatch_async_f(dispatch_get_main_queue(), new dispatch_fn_t(f), - (dispatch_function_t)([](void *arg) { - auto f = static_cast(arg); - (*f)(); - delete f; - })); - } - void set_title(const char *title) { - objc_msgSend( - m_window, "setTitle:"_sel, - objc_msgSend("NSString"_cls, "stringWithUTF8String:"_sel, title)); - } - void set_size(int width, int height, bool resizable) { - auto style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | - NSWindowStyleMaskMiniaturizable; - if (resizable) { - style = style | NSWindowStyleMaskResizable; - } - objc_msgSend(m_window, "setStyleMask:"_sel, style); - objc_msgSend(m_window, "setFrame:display:animate:"_sel, - CGRectMake(0, 0, width, height), 1, 0); - } - void navigate(const char *url) { - auto nsurl = objc_msgSend( - "NSURL"_cls, "URLWithString:"_sel, - objc_msgSend("NSString"_cls, "stringWithUTF8String:"_sel, url)); - objc_msgSend( - m_webview, "loadRequest:"_sel, - objc_msgSend("NSURLRequest"_cls, "requestWithURL:"_sel, nsurl)); - } - void init(const char *js) { - objc_msgSend( - m_manager, "addUserScript:"_sel, - objc_msgSend( - objc_msgSend("WKUserScript"_cls, "alloc"_sel), - "initWithSource:injectionTime:forMainFrameOnly:"_sel, - objc_msgSend("NSString"_cls, "stringWithUTF8String:"_sel, js), - WKUserScriptInjectionTimeAtDocumentStart, 1)); - } - void eval(const char *js) { - objc_msgSend(m_webview, "evaluateJavaScript:completionHandler:"_sel, - objc_msgSend("NSString"_cls, "stringWithUTF8String:"_sel, js), - nullptr); - } - -protected: - id m_window; - id m_webview; - id m_manager; - msg_cb_t m_cb; -}; - -} // namespace webview - -#elif defined(WEBVIEW_MSHTML) || defined(WEBVIEW_EDGE) - -// -// ==================================================================== -// -// This implementation uses Win32 API to create a native window. It can -// use either MSHTML or EdgeHTML backend as a browser engine. -// -// ==================================================================== -// - -#define WIN32_LEAN_AND_MEAN -#include - -#pragma comment(lib, "user32.lib") -namespace webview { -class browser_window { -public: - browser_window(msg_cb_t cb, void *window) : m_cb(cb) { - if (window == nullptr) { - WNDCLASSEX wc; - ZeroMemory(&wc, sizeof(WNDCLASSEX)); - wc.cbSize = sizeof(WNDCLASSEX); - wc.hInstance = GetModuleHandle(nullptr); - wc.lpszClassName = "webview"; - wc.lpfnWndProc = - (WNDPROC)(+[](HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) -> int { - auto w = (browser_window *)GetWindowLongPtr(hwnd, GWLP_USERDATA); - switch (msg) { - case WM_SIZE: - w->resize(); - break; - case WM_CLOSE: - DestroyWindow(hwnd); - break; - case WM_DESTROY: - w->terminate(); - break; - default: - return DefWindowProc(hwnd, msg, wp, lp); - } - return 0; - }); - RegisterClassEx(&wc); - m_window = CreateWindow("webview", "", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, - CW_USEDEFAULT, 640, 480, nullptr, nullptr, - GetModuleHandle(nullptr), nullptr); - SetWindowLongPtr(m_window, GWLP_USERDATA, (LONG_PTR)this); - } else { - m_window = *(static_cast(window)); - } - - ShowWindow(m_window, SW_SHOW); - UpdateWindow(m_window); - SetFocus(m_window); - } - - void run() { - MSG msg; - BOOL res; - while ((res = GetMessage(&msg, nullptr, 0, 0)) != -1) { - if (msg.hwnd) { - TranslateMessage(&msg); - DispatchMessage(&msg); - continue; - } - if (msg.message == WM_APP) { - auto f = (dispatch_fn_t *)(msg.lParam); - (*f)(); - delete f; - } else if (msg.message == WM_QUIT) { - return; - } - } - } - - void terminate() { PostQuitMessage(0); } - void dispatch(dispatch_fn_t f) { - PostThreadMessage(m_main_thread, WM_APP, 0, (LPARAM) new dispatch_fn_t(f)); - } - - void set_title(const char *title) { SetWindowText(m_window, title); } - - void set_size(int width, int height, bool resizable) { - RECT r; - r.left = 50; - r.top = 50; - r.right = width; - r.bottom = height; - AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, 0); - SetWindowPos(m_window, NULL, r.left, r.top, r.right - r.left, - r.bottom - r.top, - SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); - } - -protected: - virtual void resize() {} - HWND m_window; - DWORD m_main_thread = GetCurrentThreadId(); - msg_cb_t m_cb; -}; -} // namespace webview - -#if defined(WEBVIEW_MSHTML) -#include -#include -#include -#include -#include -#pragma comment(lib, "ole32.lib") -#pragma comment(lib, "oleaut32.lib") - -#define DISPID_EXTERNAL_INVOKE 0x1000 - -namespace webview { -class browser_engine : public browser_window, - public IOleClientSite, - public IOleInPlaceSite, - public IOleInPlaceFrame, - public IDocHostUIHandler, - public DWebBrowserEvents2 { -public: - browser_engine(msg_cb_t cb, bool debug, void *window) - : browser_window(cb, window) { - RECT rect; - LPCLASSFACTORY cf = nullptr; - IOleObject *obj = nullptr; - - fix_ie_compat_mode(); - - OleInitialize(nullptr); - CoGetClassObject(CLSID_WebBrowser, - CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER, nullptr, - IID_IClassFactory, (void **)&cf); - cf->CreateInstance(nullptr, IID_IOleObject, (void **)&obj); - cf->Release(); - - obj->SetClientSite(this); - OleSetContainedObject(obj, TRUE); - GetWindowRect(m_window, &rect); - obj->DoVerb(OLEIVERB_INPLACEACTIVATE, NULL, this, -1, m_window, &rect); - obj->QueryInterface(IID_IWebBrowser2, (void **)&m_webview); - - IConnectionPointContainer *cpc; - IConnectionPoint *cp; - DWORD cookie; - m_webview->QueryInterface(IID_IConnectionPointContainer, (void **)&cpc); - cpc->FindConnectionPoint(DIID_DWebBrowserEvents2, &cp); - cpc->Release(); - cp->Advise(static_cast(this), &cookie); - - resize(); - navigate("about:blank"); - } - - ~browser_engine() { OleUninitialize(); } - - void navigate(const char *url) { - VARIANT v; - DWORD size = MultiByteToWideChar(CP_UTF8, 0, url, -1, 0, 0); - WCHAR *ws = (WCHAR *)GlobalAlloc(GMEM_FIXED, sizeof(WCHAR) * size); - MultiByteToWideChar(CP_UTF8, 0, url, -1, ws, size); - VariantInit(&v); - v.vt = VT_BSTR; - v.bstrVal = SysAllocString(ws); - m_webview->Navigate2(&v, nullptr, nullptr, nullptr, nullptr); - VariantClear(&v); - } - - void eval(const char *js) { - // TODO - } - -private: - IWebBrowser2 *m_webview; - - int fix_ie_compat_mode() { - const char *WEBVIEW_KEY_FEATURE_BROWSER_EMULATION = - "Software\\Microsoft\\Internet " - "Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION"; - HKEY hKey; - DWORD ie_version = 11000; - TCHAR appname[MAX_PATH + 1]; - TCHAR *p; - if (GetModuleFileName(NULL, appname, MAX_PATH + 1) == 0) { - return -1; - } - for (p = &appname[strlen(appname) - 1]; p != appname && *p != '\\'; p--) { - } - p++; - if (RegCreateKey(HKEY_CURRENT_USER, WEBVIEW_KEY_FEATURE_BROWSER_EMULATION, - &hKey) != ERROR_SUCCESS) { - return -1; - } - if (RegSetValueEx(hKey, p, 0, REG_DWORD, (BYTE *)&ie_version, - sizeof(ie_version)) != ERROR_SUCCESS) { - RegCloseKey(hKey); - return -1; - } - RegCloseKey(hKey); - return 0; - } - - // Inheruted via browser_window - void resize() override { - RECT rect; - GetClientRect(m_window, &rect); - m_webview->put_Left(0); - m_webview->put_Top(0); - m_webview->put_Width(rect.right); - m_webview->put_Height(rect.bottom); - m_webview->put_Visible(VARIANT_TRUE); - } - - // Inherited via IUnknown - ULONG __stdcall AddRef(void) override { return 1; } - ULONG __stdcall Release(void) override { return 1; } - HRESULT __stdcall QueryInterface(REFIID riid, void **obj) override { - if (riid == IID_IUnknown || riid == IID_IOleClientSite) { - *obj = static_cast(this); - return S_OK; - } - if (riid == IID_IOleInPlaceSite) { - *obj = static_cast(this); - return S_OK; - } - if (riid == IID_IDocHostUIHandler) { - *obj = static_cast(this); - return S_OK; - } - if (riid == IID_IDispatch || riid == DIID_DWebBrowserEvents2) { - *obj = static_cast(this); - return S_OK; - } - *obj = nullptr; - return E_NOINTERFACE; - } - - // Inherited via IOleClientSite - HRESULT __stdcall SaveObject(void) override { return E_NOTIMPL; } - HRESULT __stdcall GetMoniker(DWORD dwAssign, DWORD dwWhichMoniker, - IMoniker **ppmk) override { - return E_NOTIMPL; - } - HRESULT __stdcall GetContainer(IOleContainer **ppContainer) override { - *ppContainer = nullptr; - return E_NOINTERFACE; - } - HRESULT __stdcall ShowObject(void) override { return S_OK; } - HRESULT __stdcall OnShowWindow(BOOL fShow) override { return S_OK; } - HRESULT __stdcall RequestNewObjectLayout(void) override { return E_NOTIMPL; } - - // Inherited via IOleInPlaceSite - HRESULT __stdcall GetWindow(HWND *phwnd) override { - *phwnd = m_window; - return S_OK; - } - HRESULT __stdcall ContextSensitiveHelp(BOOL fEnterMode) override { - return E_NOTIMPL; - } - HRESULT __stdcall CanInPlaceActivate(void) override { return S_OK; } - HRESULT __stdcall OnInPlaceActivate(void) override { return S_OK; } - HRESULT __stdcall OnUIActivate(void) override { return S_OK; } - HRESULT __stdcall GetWindowContext( - IOleInPlaceFrame **ppFrame, IOleInPlaceUIWindow **ppDoc, - LPRECT lprcPosRect, LPRECT lprcClipRect, - LPOLEINPLACEFRAMEINFO lpFrameInfo) override { - *ppFrame = static_cast(this); - *ppDoc = nullptr; - lpFrameInfo->fMDIApp = FALSE; - lpFrameInfo->hwndFrame = m_window; - lpFrameInfo->haccel = 0; - lpFrameInfo->cAccelEntries = 0; - return S_OK; - } - HRESULT __stdcall Scroll(SIZE scrollExtant) override { return E_NOTIMPL; } - HRESULT __stdcall OnUIDeactivate(BOOL fUndoable) override { return S_OK; } - HRESULT __stdcall OnInPlaceDeactivate(void) override { return S_OK; } - HRESULT __stdcall DiscardUndoState(void) override { return E_NOTIMPL; } - HRESULT __stdcall DeactivateAndUndo(void) override { return E_NOTIMPL; } - HRESULT __stdcall OnPosRectChange(LPCRECT lprcPosRect) override { - IOleInPlaceObject *inplace; - m_webview->QueryInterface(IID_IOleInPlaceObject, (void **)&inplace); - inplace->SetObjectRects(lprcPosRect, lprcPosRect); - return S_OK; - } - - // Inherited via IDocHostUIHandler - HRESULT __stdcall ShowContextMenu(DWORD dwID, POINT *ppt, - IUnknown *pcmdtReserved, - IDispatch *pdispReserved) override { - return S_OK; - } - HRESULT __stdcall GetHostInfo(DOCHOSTUIINFO *pInfo) override { - pInfo->dwDoubleClick = DOCHOSTUIDBLCLK_DEFAULT; - pInfo->dwFlags = DOCHOSTUIFLAG_NO3DBORDER; - return S_OK; - } - HRESULT __stdcall ShowUI(DWORD dwID, IOleInPlaceActiveObject *pActiveObject, - IOleCommandTarget *pCommandTarget, - IOleInPlaceFrame *pFrame, - IOleInPlaceUIWindow *pDoc) override { - return S_OK; - } - HRESULT __stdcall HideUI(void) override { return S_OK; } - HRESULT __stdcall UpdateUI(void) override { return S_OK; } - HRESULT __stdcall EnableModeless(BOOL fEnable) override { return S_OK; } - HRESULT __stdcall OnDocWindowActivate(BOOL fActivate) override { - return S_OK; - } - HRESULT __stdcall OnFrameWindowActivate(BOOL fActivate) override { - return S_OK; - } - HRESULT __stdcall ResizeBorder(LPCRECT prcBorder, - IOleInPlaceUIWindow *pUIWindow, - BOOL fRameWindow) override { - return S_OK; - } - HRESULT __stdcall GetOptionKeyPath(LPOLESTR *pchKey, DWORD dw) override { - return S_FALSE; - } - HRESULT __stdcall GetDropTarget(IDropTarget *pDropTarget, - IDropTarget **ppDropTarget) override { - return E_NOTIMPL; - } - HRESULT __stdcall GetExternal(IDispatch **ppDispatch) override { - *ppDispatch = static_cast(this); - return S_OK; - } - HRESULT __stdcall TranslateUrl(DWORD dwTranslate, LPWSTR pchURLIn, - LPWSTR *ppchURLOut) override { - *ppchURLOut = nullptr; - return S_FALSE; - } - HRESULT __stdcall FilterDataObject(IDataObject *pDO, - IDataObject **ppDORet) override { - *ppDORet = nullptr; - return S_FALSE; - } - HRESULT __stdcall TranslateAcceleratorA(LPMSG lpMsg, - const GUID *pguidCmdGroup, - DWORD nCmdID) { - return S_FALSE; - } - - // Inherited via IOleInPlaceFrame - HRESULT __stdcall GetBorder(LPRECT lprectBorder) override { return S_OK; } - HRESULT __stdcall RequestBorderSpace(LPCBORDERWIDTHS pborderwidths) override { - return S_OK; - } - HRESULT __stdcall SetBorderSpace(LPCBORDERWIDTHS pborderwidths) override { - return S_OK; - } - HRESULT __stdcall SetActiveObject(IOleInPlaceActiveObject *pActiveObject, - LPCOLESTR pszObjName) override { - return S_OK; - } - HRESULT __stdcall InsertMenus(HMENU hmenuShared, - LPOLEMENUGROUPWIDTHS lpMenuWidths) override { - return S_OK; - } - HRESULT __stdcall SetMenu(HMENU hmenuShared, HOLEMENU holemenu, - HWND hwndActiveObject) override { - return S_OK; - } - HRESULT __stdcall RemoveMenus(HMENU hmenuShared) override { return S_OK; } - HRESULT __stdcall SetStatusText(LPCOLESTR pszStatusText) override { - return S_OK; - } - HRESULT __stdcall TranslateAcceleratorA(LPMSG lpmsg, WORD wID) { - return S_OK; - } - - // Inherited via IDispatch - HRESULT __stdcall GetTypeInfoCount(UINT *pctinfo) override { return S_OK; } - HRESULT __stdcall GetTypeInfo(UINT iTInfo, LCID lcid, - ITypeInfo **ppTInfo) override { - return S_OK; - } - HRESULT __stdcall GetIDsOfNames(REFIID riid, LPOLESTR *rgszNames, UINT cNames, - LCID lcid, DISPID *rgDispId) override { - *rgDispId = DISPID_EXTERNAL_INVOKE; - return S_OK; - } - HRESULT __stdcall Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, - WORD wFlags, DISPPARAMS *pDispParams, - VARIANT *pVarResult, EXCEPINFO *pExcepInfo, - UINT *puArgErr) override { - if (dispIdMember == DISPID_NAVIGATECOMPLETE2) { - } else if (dispIdMember == DISPID_DOCUMENTCOMPLETE) { - } else if (dispIdMember == DISPID_EXTERNAL_INVOKE) { - } - return S_OK; - } -}; -} // namespace webview - -#elif defined(WEBVIEW_EDGE) -#include -#include -#include - -#pragma comment(lib, "windowsapp") - -namespace webview { - -using namespace winrt; -using namespace Windows::Foundation; -using namespace Windows::Web::UI; -using namespace Windows::Web::UI::Interop; - -class browser_engine : public browser_window { -public: - browser_engine(msg_cb_t cb, bool debug, void *window) - : browser_window(cb, window) { - init_apartment(winrt::apartment_type::single_threaded); - m_process = WebViewControlProcess(); - auto op = m_process.CreateWebViewControlAsync( - reinterpret_cast(m_window), Rect()); - if (op.Status() != AsyncStatus::Completed) { - handle h(CreateEvent(nullptr, false, false, nullptr)); - op.Completed([h = h.get()](auto, auto) { SetEvent(h); }); - HANDLE hs[] = {h.get()}; - DWORD i; - CoWaitForMultipleHandles(COWAIT_DISPATCH_WINDOW_MESSAGES | - COWAIT_DISPATCH_CALLS | - COWAIT_INPUTAVAILABLE, - INFINITE, 1, hs, &i); - } - m_webview = op.GetResults(); - m_webview.Settings().IsScriptNotifyAllowed(true); - m_webview.IsVisible(true); - m_webview.ScriptNotify([=](auto const &sender, auto const &args) { - std::string s = winrt::to_string(args.Value()); - m_cb(s.c_str()); - }); - m_webview.NavigationStarting([=](auto const &sender, auto const &args) { - m_webview.AddInitializeScript(winrt::to_hstring(init_js)); - }); - init("window.external.invoke = s => window.external.notify(s)"); - resize(); - } - - void navigate(const char *url) { - Uri uri(winrt::to_hstring(url)); - // TODO: if url starts with 'data:text/html,' prefix then use it as a string - m_webview.Navigate(uri); - // m_webview.NavigateToString(winrt::to_hstring(url)); - } - void init(const char *js) { - init_js = init_js + "(function(){" + js + "})();"; - } - void eval(const char *js) { - m_webview.InvokeScriptAsync( - L"eval", single_threaded_vector({winrt::to_hstring(js)})); - } - -private: - void resize() { - RECT r; - GetClientRect(m_window, &r); - Rect bounds(r.left, r.top, r.right - r.left, r.bottom - r.top); - m_webview.Bounds(bounds); - } - WebViewControlProcess m_process; - WebViewControl m_webview = nullptr; - std::string init_js = ""; -}; -} // namespace webview -#endif - -#endif /* WEBVIEW_GTK, WEBVIEW_COCOA, WEBVIEW_MSHTML, WEBVIEW_MSHTML */ - -namespace webview { - -class webview : public browser_engine { -public: - webview(bool debug = false, void *wnd = nullptr) - : browser_engine( - std::bind(&webview::on_message, this, std::placeholders::_1), debug, - wnd) {} - - void *window() { return (void *)m_window; } - - void navigate(const char *url) { - std::string html = html_from_uri(url); - if (html != "") { - browser_engine::navigate(("data:text/html," + url_encode(html)).c_str()); - } else { - browser_engine::navigate(url); - } - } - - using binding_t = std::function; - - void bind(const char *name, binding_t f) { - auto js = "(function() { var name = '" + std::string(name) + "';" + R"( - window[name] = function() { - var me = window[name]; - var errors = me['errors']; - var callbacks = me['callbacks']; - if (!callbacks) { - callbacks = {}; - me['callbacks'] = callbacks; - } - if (!errors) { - errors = {}; - me['errors'] = errors; - } - var seq = (me['lastSeq'] || 0) + 1; - me['lastSeq'] = seq; - var promise = new Promise(function(resolve, reject) { - callbacks[seq] = resolve; - errors[seq] = reject; - }); - window.external.invoke(JSON.stringify({ - name: name, - seq:seq, - args: Array.prototype.slice.call(arguments), - })); - return promise; - } - })())"; - init(js.c_str()); - bindings[name] = new binding_t(f); - } - -private: - void on_message(const char *msg) { - auto seq = json_parse(msg, "seq", 0); - auto name = json_parse(msg, "name", 0); - auto args = json_parse(msg, "args", 0); - auto fn = bindings[name]; - if (fn == nullptr) { - return; - } - std::async(std::launch::async, [=]() { - auto result = (*fn)(args); - dispatch([=]() { - eval(("var b = window['" + name + "'];b['callbacks'][" + seq + "](" + - result + ");b['callbacks'][" + seq + - "] = undefined;b['errors'][" + seq + "] = undefined;") - .c_str()); - }); - }); - } - std::map bindings; -}; -} // namespace webview - -WEBVIEW_API webview_t webview_create(int debug, void *wnd) { - return new webview::webview(debug, wnd); -} - -WEBVIEW_API void webview_destroy(webview_t w) { - delete static_cast(w); -} - -WEBVIEW_API void webview_run(webview_t w) { - static_cast(w)->run(); -} - -WEBVIEW_API void webview_terminate(webview_t w) { - static_cast(w)->terminate(); -} - -WEBVIEW_API void -webview_dispatch(webview_t w, void (*fn)(webview_t w, void *arg), void *arg) { - static_cast(w)->dispatch([=]() { fn(w, arg); }); -} - -WEBVIEW_API void *webview_get_window(webview_t w) { - return static_cast(w)->window(); -} - -WEBVIEW_API void webview_set_title(webview_t w, const char *title) { - static_cast(w)->set_title(title); -} - -WEBVIEW_API void webview_set_bounds(webview_t w, int x, int y, int width, - int height, int flags) { - // TODO: x, y, flags - static_cast(w)->set_size(width, height, true); -} - -WEBVIEW_API void webview_get_bounds(webview_t w, int *x, int *y, int *width, - int *height, int *flags) { - // TODO -} - -WEBVIEW_API void webview_navigate(webview_t w, const char *url) { - static_cast(w)->navigate(url); -} - -WEBVIEW_API void webview_init(webview_t w, const char *js) { - static_cast(w)->init(js); -} - -WEBVIEW_API void webview_eval(webview_t w, const char *js) { - static_cast(w)->eval(js); -} - -#endif /* WEBVIEW_HEADER */ - -#endif /* WEBVIEW_H */ diff --git a/attic/webview/webview_test.cc b/attic/webview/webview_test.cc deleted file mode 100644 index ebf995b1e..000000000 --- a/attic/webview/webview_test.cc +++ /dev/null @@ -1,38 +0,0 @@ -// +build ignore - -#include "webview.h" - -#include -#include - -static void test_terminate() { - webview::webview w(false, nullptr); - w.dispatch([&]() { w.terminate(); }); - w.run(); -} - -static void cb_assert_arg(webview_t w, void *arg) { - assert(w != NULL); - assert(memcmp(arg, "arg", 3) == 0); -} -static void cb_terminate(webview_t w, void *arg) { - assert(arg == NULL); - webview_terminate(w); -} -static void test_c_api() { - webview_t w; - w = webview_create(false, NULL); - webview_set_bounds(w, 100, 100, 480, 320, 0); - webview_set_title(w, "Test"); - webview_navigate(w, "https://github.com/zserge/webview"); - webview_dispatch(w, cb_assert_arg, (void *)"arg"); - webview_dispatch(w, cb_terminate, NULL); - webview_run(w); - webview_destroy(w); -} - -int main() { - test_terminate(); - test_c_api(); - return 0; -} diff --git a/attic/windows-clean.bat b/attic/windows-clean.bat deleted file mode 100644 index 09e5e28b3..000000000 --- a/attic/windows-clean.bat +++ /dev/null @@ -1,9 +0,0 @@ -DEL "ZeroTier One.msi" -DEL zt1_update*.exe -RMDIR /Q /S windows\Build -RMDIR /Q /S windows\copyutil\bin -RMDIR /Q /S windows\copyutil\obj -RMDIR /Q /S windows\WinUI\bin -RMDIR /Q /S windows\WinUI\obj -RMDIR /Q /S windows\ZeroTierOne\Release -RMDIR /Q /S windows\ZeroTierOne\x64 diff --git a/attic/windows/README.md b/attic/windows/README.md deleted file mode 100644 index 9f3f48bb6..000000000 --- a/attic/windows/README.md +++ /dev/null @@ -1,3 +0,0 @@ -This folder contains the Windows driver code, Windows-specific service code, and the Microsoft Visual Studio projects and "solution" for doing Windows builds. - -This code may also build with MinGW but this hasn't been tested. diff --git a/attic/windows/WinUI/APIHandler.cs b/attic/windows/WinUI/APIHandler.cs deleted file mode 100644 index 6a944f0f0..000000000 --- a/attic/windows/WinUI/APIHandler.cs +++ /dev/null @@ -1,458 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Net; -using System.IO; -using System.Windows; -using Newtonsoft.Json; -using System.Diagnostics; -using System.Windows.Threading; - -namespace WinUI -{ - - - public class APIHandler - { - private string authtoken; - - private string url = null; - - private static volatile APIHandler instance; - private static object syncRoot = new Object(); - - public delegate void NetworkListCallback(List networks); - public delegate void StatusCallback(ZeroTierStatus status); - - private string ZeroTierAddress = ""; - - public static APIHandler Instance - { - get - { - if (instance == null) - { - lock (syncRoot) - { - if (instance == null) - { - if (!initHandler()) - { - return null; - } - } - } - } - - return instance; - } - } - - private static bool initHandler(bool resetToken = false) - { - String localZtDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\ZeroTier\\One"; - String globalZtDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\ZeroTier\\One"; - - String authToken = ""; - Int32 port = 9993; - - if (resetToken) - { - instance = null; - if (File.Exists(localZtDir + "\\authtoken.secret")) - { - File.Delete(localZtDir + "\\authtoken.secret"); - } - - if (File.Exists(localZtDir + "\\zerotier-one.port")) - { - File.Delete(localZtDir + "\\zerotier-one.port"); - } - } - - if (!File.Exists(localZtDir + "\\authtoken.secret") || !File.Exists(localZtDir + "\\zerotier-one.port")) - { - // launch external process to copy file into place - String curPath = System.Reflection.Assembly.GetEntryAssembly().Location; - int index = curPath.LastIndexOf("\\"); - curPath = curPath.Substring(0, index); - ProcessStartInfo startInfo = new ProcessStartInfo(curPath + "\\copyutil.exe", "\"" + globalZtDir + "\"" + " " + "\"" + localZtDir + "\""); - startInfo.Verb = "runas"; - - - var process = Process.Start(startInfo); - process.WaitForExit(); - } - - authToken = readAuthToken(localZtDir + "\\authtoken.secret"); - - if ((authToken == null) || (authToken.Length <= 0)) - { - MessageBox.Show("Unable to read ZeroTier One authtoken", "ZeroTier One"); - return false; - } - - port = readPort(localZtDir + "\\zerotier-one.port"); - instance = new APIHandler(port, authToken); - return true; - } - - private static String readAuthToken(String path) - { - String authToken = ""; - - if (File.Exists(path)) - { - try - { - byte[] tmp = File.ReadAllBytes(path); - authToken = System.Text.Encoding.UTF8.GetString(tmp).Trim(); - } - catch - { - MessageBox.Show("Unable to read ZeroTier One Auth Token from:\r\n" + path, "ZeroTier One"); - } - } - - return authToken; - } - - private static Int32 readPort(String path) - { - Int32 port = 9993; - - try - { - byte[] tmp = File.ReadAllBytes(path); - port = Int32.Parse(System.Text.Encoding.ASCII.GetString(tmp).Trim()); - if ((port <= 0) || (port > 65535)) - port = 9993; - } - catch - { - } - - return port; - } - - private APIHandler() - { - url = "http://127.0.0.1:9993"; - } - - public APIHandler(int port, string authtoken) - { - url = "http://127.0.0.1:" + port; - this.authtoken = authtoken; - } - - - - public void GetStatus(StatusCallback cb) - { - var request = WebRequest.Create(url + "/status" + "?auth=" + authtoken) as HttpWebRequest; - if (request != null) - { - request.Method = "GET"; - request.ContentType = "application/json"; - } - - try - { - var httpResponse = (HttpWebResponse)request.GetResponse(); - if (httpResponse.StatusCode == HttpStatusCode.OK) - { - using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) - { - var responseText = streamReader.ReadToEnd(); - - ZeroTierStatus status = null; - try - { - status = JsonConvert.DeserializeObject(responseText); - - if (ZeroTierAddress != status.Address) - { - ZeroTierAddress = status.Address; - } - } - catch (JsonReaderException e) - { - Console.WriteLine(e.ToString()); - } - cb(status); - } - } - else if (httpResponse.StatusCode == HttpStatusCode.Unauthorized) - { - APIHandler.initHandler(true); - } - } - catch (System.Net.Sockets.SocketException) - { - cb(null); - } - catch (System.Net.WebException e) - { - HttpWebResponse res = (HttpWebResponse)e.Response; - if (res != null && res.StatusCode == HttpStatusCode.Unauthorized) - { - APIHandler.initHandler(true); - } - else - { - cb(null); - } - } - } - - - - public void GetNetworks(NetworkListCallback cb) - { - var request = WebRequest.Create(url + "/network" + "?auth=" + authtoken) as HttpWebRequest; - if (request == null) - { - cb(null); - } - - request.Method = "GET"; - request.ContentType = "application/json"; - request.Timeout = 10000; - - try - { - var httpResponse = (HttpWebResponse)request.GetResponse(); - - if (httpResponse.StatusCode == HttpStatusCode.OK) - { - using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) - { - var responseText = streamReader.ReadToEnd(); - - List networkList = null; - try - { - networkList = JsonConvert.DeserializeObject>(responseText); - foreach (ZeroTierNetwork n in networkList) - { - // all networks received via JSON are connected by definition - n.IsConnected = true; - } - } - catch (JsonReaderException e) - { - Console.WriteLine(e.ToString()); - } - cb(networkList); - } - } - else if (httpResponse.StatusCode == HttpStatusCode.Unauthorized) - { - APIHandler.initHandler(true); - } - } - catch (System.Net.Sockets.SocketException) - { - cb(null); - } - catch (System.Net.WebException e) - { - HttpWebResponse res = (HttpWebResponse)e.Response; - if (res != null && res.StatusCode == HttpStatusCode.Unauthorized) - { - APIHandler.initHandler(true); - } - else - { - cb(null); - } - } - } - - public void JoinNetwork(Dispatcher d, string nwid, bool allowManaged = true, bool allowGlobal = false, bool allowDefault = false) - { - Task.Factory.StartNew(() => - { - var request = WebRequest.Create(url + "/network/" + nwid + "?auth=" + authtoken) as HttpWebRequest; - if (request == null) - { - return; - } - - request.Method = "POST"; - request.ContentType = "applicaiton/json"; - request.Timeout = 30000; - try - { - using (var streamWriter = new StreamWriter(((HttpWebRequest)request).GetRequestStream())) - { - string json = "{\"allowManaged\":" + (allowManaged ? "true" : "false") + "," + - "\"allowGlobal\":" + (allowGlobal ? "true" : "false") + "," + - "\"allowDefault\":" + (allowDefault ? "true" : "false") + "}"; - streamWriter.Write(json); - streamWriter.Flush(); - streamWriter.Close(); - } - } - catch (System.Net.WebException) - { - d.BeginInvoke(DispatcherPriority.Normal, new Action(() => - { - MessageBox.Show("Error Joining Network: Cannot connect to ZeroTier service."); - })); - return; - } - - try - { - var httpResponse = (HttpWebResponse)request.GetResponse(); - - if (httpResponse.StatusCode == HttpStatusCode.Unauthorized) - { - APIHandler.initHandler(true); - } - else if (httpResponse.StatusCode != HttpStatusCode.OK) - { - Console.WriteLine("Error sending join network message"); - } - } - catch (System.Net.Sockets.SocketException) - { - d.BeginInvoke(DispatcherPriority.Normal, new Action(() => - { - MessageBox.Show("Error Joining Network: Cannot connect to ZeroTier service."); - })); - } - catch (System.Net.WebException e) - { - HttpWebResponse res = (HttpWebResponse)e.Response; - if (res != null && res.StatusCode == HttpStatusCode.Unauthorized) - { - APIHandler.initHandler(true); - } - d.BeginInvoke(DispatcherPriority.Normal, new Action(() => - { - MessageBox.Show("Error Joining Network: Cannot connect to ZeroTier service."); - })); - } - }); - } - - public void LeaveNetwork(Dispatcher d, string nwid) - { - Task.Factory.StartNew(() => - { - var request = WebRequest.Create(url + "/network/" + nwid + "?auth=" + authtoken) as HttpWebRequest; - if (request == null) - { - return; - } - - request.Method = "DELETE"; - request.Timeout = 30000; - - try - { - var httpResponse = (HttpWebResponse)request.GetResponse(); - - if (httpResponse.StatusCode == HttpStatusCode.Unauthorized) - { - APIHandler.initHandler(true); - } - else if (httpResponse.StatusCode != HttpStatusCode.OK) - { - Console.WriteLine("Error sending leave network message"); - } - } - catch (System.Net.Sockets.SocketException) - { - d.BeginInvoke(DispatcherPriority.Normal, new Action(() => - { - MessageBox.Show("Error Leaving Network: Cannot connect to ZeroTier service."); - })); - } - catch (System.Net.WebException e) - { - HttpWebResponse res = (HttpWebResponse)e.Response; - if (res != null && res.StatusCode == HttpStatusCode.Unauthorized) - { - APIHandler.initHandler(true); - } - d.BeginInvoke(DispatcherPriority.Normal, new Action(() => - { - MessageBox.Show("Error Leaving Network: Cannot connect to ZeroTier service."); - })); - } - catch - { - Console.WriteLine("Error leaving network: Unknown error"); - } - }); - } - - public delegate void PeersCallback(List peers); - - public void GetPeers(PeersCallback cb) - { - var request = WebRequest.Create(url + "/peer" + "?auth=" + authtoken) as HttpWebRequest; - if (request == null) - { - cb(null); - } - - request.Method = "GET"; - request.ContentType = "application/json"; - - try - { - var httpResponse = (HttpWebResponse)request.GetResponse(); - if (httpResponse.StatusCode == HttpStatusCode.OK) - { - using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) - { - var responseText = streamReader.ReadToEnd(); - //Console.WriteLine(responseText); - List peerList = null; - try - { - peerList = JsonConvert.DeserializeObject>(responseText); - } - catch (JsonReaderException e) - { - Console.WriteLine(e.ToString()); - } - cb(peerList); - } - } - else if (httpResponse.StatusCode == HttpStatusCode.Unauthorized) - { - APIHandler.initHandler(true); - } - } - catch (System.Net.Sockets.SocketException) - { - cb(null); - } - catch (System.Net.WebException e) - { - HttpWebResponse res = (HttpWebResponse)e.Response; - if (res != null && res.StatusCode == HttpStatusCode.Unauthorized) - { - APIHandler.initHandler(true); - } - else - { - cb(null); - } - } - } - - public string NodeAddress() - { - return ZeroTierAddress; - } - } -} diff --git a/attic/windows/WinUI/AboutView.xaml b/attic/windows/WinUI/AboutView.xaml deleted file mode 100644 index d07a89476..000000000 --- a/attic/windows/WinUI/AboutView.xaml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/attic/windows/WinUI/AboutView.xaml.cs b/attic/windows/WinUI/AboutView.xaml.cs deleted file mode 100644 index 9c48493d0..000000000 --- a/attic/windows/WinUI/AboutView.xaml.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Navigation; -using System.Windows.Shapes; - -namespace WinUI -{ - /// - /// Interaction logic for AboutView.xaml - /// - public partial class AboutView : Window - { - public AboutView() - { - InitializeComponent(); - } - - private void Hyperlink_MouseLeftButtonDown(object sender, RequestNavigateEventArgs e) - { - var hyperlink = (Hyperlink)sender; - Process.Start(hyperlink.NavigateUri.ToString()); - } - } -} diff --git a/attic/windows/WinUI/App.config b/attic/windows/WinUI/App.config deleted file mode 100644 index 88fa4027b..000000000 --- a/attic/windows/WinUI/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/attic/windows/WinUI/App.xaml b/attic/windows/WinUI/App.xaml deleted file mode 100644 index 12ed85f9a..000000000 --- a/attic/windows/WinUI/App.xaml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - diff --git a/attic/windows/WinUI/App.xaml.cs b/attic/windows/WinUI/App.xaml.cs deleted file mode 100644 index 53ef2f678..000000000 --- a/attic/windows/WinUI/App.xaml.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Data; -using System.Linq; -using System.Threading.Tasks; -using System.Windows; -using Hardcodet.Wpf.TaskbarNotification; - -namespace WinUI -{ - /// - /// Interaction logic for App.xaml - /// - public partial class App : Application - { - private TaskbarIcon tb; - - private void InitApplication() - { - tb = (TaskbarIcon)FindResource("NotifyIcon"); - tb.Visibility = Visibility.Visible; - } - } -} diff --git a/attic/windows/WinUI/CMakeLists.txt b/attic/windows/WinUI/CMakeLists.txt deleted file mode 100644 index 54cbbc6e1..000000000 --- a/attic/windows/WinUI/CMakeLists.txt +++ /dev/null @@ -1,128 +0,0 @@ -cmake_minimum_required(VERSION 3.8) -include(CSharpUtilities) - -project("ZeroTierOneUI" VERSION 1.4.0 LANGUAGES CSharp) - -add_executable( - ${PROJECT_NAME} - app.manifest - App.config - App.xaml - App.xaml.cs - - AboutView.xaml - AboutView.xaml.cs - APIHandler.cs - CentralAPI.cs - CentralLogin.cs - CentralNetwork.cs - CentralServer.cs - CentralToken.cs - CentralUser.cs - ISwitchable.cs - JoinNetworkView.xaml - JoinNetworkView.xaml.cs - NetworkInfoView.xaml - NetworkInfoView.xaml.cs - NetworkListView.xaml - NetworkListView.xaml.cs - NetworkMonitor.cs - NetworkNameGenerator.cs - NetworkRoute.cs - NetworksPage.xaml - NetworksPage.xaml.cs - PeersPage.xaml - PeersPage.xaml.cs - PreferencesView.xaml - PreferencesView.xaml.cs - "Simple Styles.xaml" - ToolbarItem.xaml - ToolbarItem.xaml.cs - ZeroTierNetwork.cs - ZeroTierPeer.cs - ZeroTierPeerPhysicalPath.cs - ZeroTierStatus.cs - - packages.config - - "Properties/AssemblyInfo.cs" - "Properties/Resources.Designer.cs" - "Properties/Resources.resx" - "Properties/Settings.Designer.cs" - "Properties/Settings.settings" - - "Resources/ZeroTierIcon.ico" - ZeroTierIcon.ico -) - -csharp_set_designer_cs_properties( - "Properties/AssemblyInfo.cs" - "Properties/Resources.Designer.cs" - "Properties/Resources.resx" - "Properties/Settings.Designer.cs" - "Properties/Settings.settings" -) - -csharp_set_xaml_cs_properties( - App.xaml - App.xaml.cs - AboutView.xaml - AboutView.xaml.cs - JoinNetworkView.xaml - JoinNetworkView.xaml.cs - NetworkInfoView.xaml - NetworkInfoView.xaml.cs - NetworkListView.xaml - NetworkListView.xaml.cs - NetworksPage.xaml - NetworksPage.xaml.cs - PeersPage.xaml - PeersPage.xaml.cs - PreferencesView.xaml - PreferencesView.xaml.cs - ToolbarItem.xaml - ToolbarItem.xaml.cs -) - -set_property(SOURCE App.xaml PROPERTY VS_XAML_TYPE "ApplicationDefinition") - -set_property(SOURCE ZeroTierIcon.ico PROPERTY VS_TOOL_OVERRIDE "Resource") - -set_target_properties(${PROJECT_NAME} PROPERTIES - VS_GLOBAL_ROOTNAMESPACE "WinUI" - VS_DOTNET_TARGET_FRAMEWORK_VERSION "v4.5.2" - WIN32_EXECUTABLE TRUE - ) - -set_property(TARGET ${PROJECT_NAME} PROPERTY VS_DOTNET_REFERENCES - "Microsoft.CSharp" - "PresentationCore" - "PresentationFramework" - "System" - "System.Core" - "System.Data" - "System.Data.DataSetExtensions" - "System.Drawing" - "System.Net.Http" - "System.Xaml" - "System.Xml" - "System.Xml.Linq" - "WindowsBase" - "Newtonsoft.Json" -) - -set(CMAKE_CSharp_FLAGS "/langversion:6") - -target_compile_options(${PROJECT_NAME} PRIVATE "/win32icon:${CMAKE_CURRENT_SOURCE_DIR}/ZeroTierIcon.ico") -set_property(TARGET ${PROJECT_NAME} PROPERTY VS_DOTNET_REFERENCE_Hardcodet.Wpf.TaskbarNotification "${CMAKE_CURRENT_BINARY_DIR}/packages/Hardcodet.NotifyIcon.Wpf.1.0.8/lib/net45/Hardcodet.Wpf.TaskbarNotification.dll") - -find_program(NUGET nuget) -add_custom_target(nuget-restore - COMMAND ${NUGET} restore ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.sln -) - -configure_file(${CMAKE_CURRENT_SOURCE_DIR}/packages.config - ${CMAKE_CURRENT_BINARY_DIR}/packages.config COPYONLY) - -add_dependencies(${PROJECT_NAME} nuget-restore) - \ No newline at end of file diff --git a/attic/windows/WinUI/CentralAPI.cs b/attic/windows/WinUI/CentralAPI.cs deleted file mode 100644 index 22bdc697c..000000000 --- a/attic/windows/WinUI/CentralAPI.cs +++ /dev/null @@ -1,256 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json; - -namespace WinUI -{ - class CentralAPI - { - private static volatile CentralAPI instance; - private static object syncRoot = new Object(); - - private CookieContainer cookieContainer; - private HttpClientHandler clientHandler; - private HttpClient client; - - private CentralServer server; - public CentralServer Central - { - get - { - return this.server; - } - set - { - this.server = value; - WriteCentralConfig(); - UpdateRequestHeaders(); - } - } - - public static CentralAPI Instance - { - get - { - if (instance == null) - { - lock (syncRoot) - { - if (instance == null) - { - instance = new CentralAPI(); - } - } - } - - return instance; - } - } - - - - private CentralAPI() - { -#if DEBUG - ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; -#endif - cookieContainer = new CookieContainer(); - clientHandler = new HttpClientHandler - { - AllowAutoRedirect = true, - UseCookies = true, - CookieContainer = cookieContainer - }; - - client = new HttpClient(clientHandler); - - string centralConfigPath = CentralConfigFile(); - if (File.Exists(centralConfigPath)) - { - byte[] tmp = File.ReadAllBytes(centralConfigPath); - string json = Encoding.UTF8.GetString(tmp).Trim(); - CentralServer ctmp = JsonConvert.DeserializeObject(json); - if (ctmp != null) - { - Central = ctmp; - } - else - { - Central = new CentralServer(); - } - } - else - { - Central = new CentralServer(); - } - } - - public bool HasAccessToken() - { - if (Central == null) - return false; - - return !string.IsNullOrEmpty(Central.APIKey); - } - - private string ZeroTierDir() - { - return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\ZeroTier\\One"; - } - - private string CentralConfigFile() - { - return ZeroTierDir() + "\\central.conf"; - } - - public void WriteCentralConfig() - { - string json = JsonConvert.SerializeObject(Central); - byte[] tmp = Encoding.UTF8.GetBytes(json); - if (tmp != null) - { - File.WriteAllBytes(CentralConfigFile(), tmp); - } - } - - private void UpdateRequestHeaders() - { - if (client.DefaultRequestHeaders.Contains("Authorization")) - { - client.DefaultRequestHeaders.Remove("Authorization"); - } - - if (!string.IsNullOrEmpty(Central.APIKey)) - { - client.DefaultRequestHeaders.Add("Authorization", "bearer " + Central.APIKey); - } - } - - public async Task Login(string email, string password, bool isNewUser) - { - string postURL = Central.ServerURL + "/api/_auth/local"; - CentralLogin login = new CentralLogin(email, password, isNewUser); - var content = new StringContent(JsonConvert.SerializeObject(login), Encoding.UTF8, "application/json"); - HttpResponseMessage response = await client.PostAsync(postURL, content); - - if (!response.IsSuccessStatusCode) - { - return false; - } - - string resContent = await response.Content.ReadAsStringAsync(); - - CentralUser user = JsonConvert.DeserializeObject(resContent); - - if (user.Tokens.Count == 0) - { - // create token - user = await CreateAuthToken(user); - } - - Central.APIKey = user.Tokens[0]; - - UpdateRequestHeaders(); - WriteCentralConfig(); - - return true; - } - - public async Task CreateAuthToken(CentralUser user) - { - string randomTokenURL = Central.ServerURL + "/api/randomToken"; - HttpResponseMessage response = await client.GetAsync(randomTokenURL); - - if (!response.IsSuccessStatusCode) - { - // TODO: throw an error - return null; - } - - string resContent = await response.Content.ReadAsStringAsync(); - - CentralToken t = JsonConvert.DeserializeObject(resContent); - - user.Tokens.Add(t.Token); - - string tokenObj = "{ \"tokens\": " + JsonConvert.SerializeObject(user.Tokens) + " } "; - - string postURL = Central.ServerURL + "/api/user/" + user.Id; - var postContent = new StringContent(tokenObj, Encoding.UTF8, "application/json"); - response = await client.PostAsync(postURL, postContent); - - if (!response.IsSuccessStatusCode) - { - // TODO: thrown an error - return null; - } - - resContent = await response.Content.ReadAsStringAsync(); - user = JsonConvert.DeserializeObject(resContent); - - return user; - } - - public async Task> GetNetworkList() - { - string networkURL = Central.ServerURL + "/api/network"; - - HttpResponseMessage response = await client.GetAsync(networkURL); - - if (!response.IsSuccessStatusCode) - { - // TODO: Throw Error - return new List(); - } - - string resContent = await response.Content.ReadAsStringAsync(); - - List networkList = JsonConvert.DeserializeObject>(resContent); - - return networkList; - } - - public async Task CreateNewNetwork() - { - string networkURL = Central.ServerURL + "/api/network?easy=1"; - CentralNetwork network = new CentralNetwork(); - network.Config = new CentralNetwork.CentralNetworkConfig(); - network.Config.Name = NetworkNameGenerator.GenerateName(); - string jsonNetwork = JsonConvert.SerializeObject(network); - var postContent = new StringContent(jsonNetwork, Encoding.UTF8, "application/json"); - HttpResponseMessage response = await client.PostAsync(networkURL, postContent); - - if (!response.IsSuccessStatusCode) - { - return null; - } - - string resContent = await response.Content.ReadAsStringAsync(); - - CentralNetwork newNetwork = JsonConvert.DeserializeObject(resContent); - - return newNetwork; - } - - public async Task AuthorizeNode(string nodeAddress, string networkId) - { - string json = "{ \"config\": { \"authorized\": true } }"; - string postURL = Central.ServerURL + "/api/network/" + networkId + "/member/" + nodeAddress; - var postContent = new StringContent(json, Encoding.UTF8, "application/json"); - HttpResponseMessage response = await client.PostAsync(postURL, postContent); - - if (response.IsSuccessStatusCode) - { - return true; - } - - return false; - } - } -} diff --git a/attic/windows/WinUI/CentralLogin.cs b/attic/windows/WinUI/CentralLogin.cs deleted file mode 100644 index 97265dcf8..000000000 --- a/attic/windows/WinUI/CentralLogin.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json; - -namespace WinUI -{ - class CentralLogin - { - - - public CentralLogin(string email, string password, bool isNew) - { - Login = email; - Password = password; - IsNew = isNew; - } - - [JsonProperty("login")] - public string Login { get; set; } - - [JsonProperty("password")] - public string Password { get; set; } - - [JsonProperty("register")] - public bool IsNew { get; set; } - } -} diff --git a/attic/windows/WinUI/CentralNetwork.cs b/attic/windows/WinUI/CentralNetwork.cs deleted file mode 100644 index 26ad5234a..000000000 --- a/attic/windows/WinUI/CentralNetwork.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json; - -namespace WinUI -{ - class CentralNetwork - { - [JsonProperty("id")] - public string Id { get; set; } - - [JsonProperty("type")] - public string Type { get; set; } - - [JsonProperty("clock")] - public UInt64 Clock { get; set; } - - [JsonProperty("rulesSource")] - public string RulesSource { get; set; } - - [JsonProperty("description")] - public string Description { get; set; } - - [JsonProperty("ownerId")] - public string OwnerID { get; set; } - - [JsonProperty("onlineMemberCount")] - public int OnlineMemberCount { get; set; } - - [JsonProperty("config")] - public CentralNetworkConfig Config { get; set; } - - public class CentralNetworkConfig - { - [JsonProperty("id")] - public string Id { get; set; } - - [JsonProperty("nwid")] - public string NetworkID { get; set; } - - [JsonProperty("name")] - public string Name { get; set; } - } - } -} diff --git a/attic/windows/WinUI/CentralServer.cs b/attic/windows/WinUI/CentralServer.cs deleted file mode 100644 index 8e2686534..000000000 --- a/attic/windows/WinUI/CentralServer.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json; - -namespace WinUI -{ - class CentralServer - { - public CentralServer() - { - ServerURL = "https://my.zerotier.com"; - } - - [JsonProperty("server_url")] - public string ServerURL { get; set; } - - [JsonProperty("api_key")] - public string APIKey { get; set; } - } -} diff --git a/attic/windows/WinUI/CentralToken.cs b/attic/windows/WinUI/CentralToken.cs deleted file mode 100644 index 1db548aae..000000000 --- a/attic/windows/WinUI/CentralToken.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json; - -namespace WinUI -{ - class CentralToken - { - [JsonProperty("token")] - public string Token { get; set; } - - [JsonProperty("clock")] - public UInt64 Clock { get; set; } - - [JsonProperty("raw")] - public string Raw { get; set; } - } -} diff --git a/attic/windows/WinUI/CentralUser.cs b/attic/windows/WinUI/CentralUser.cs deleted file mode 100644 index 8a8945a28..000000000 --- a/attic/windows/WinUI/CentralUser.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json; - -namespace WinUI -{ - class CentralUser - { - public class CentralGlobalPermissions - { - [JsonProperty("a")] - public bool Administrator { get; set; } - - [JsonProperty("d")] - public bool Delete { get; set; } - - [JsonProperty("m")] - public bool Modify { get; set; } - - [JsonProperty("r")] - public bool Read { get; set; } - } - - [JsonProperty("id")] - public string Id { get; set; } - - [JsonProperty("type")] - public string Type { get; set; } - - [JsonProperty("clock")] - public UInt64 Clock { get; set; } - - [JsonProperty("globalPermissions")] - public CentralGlobalPermissions GlobalPermissions { get; set; } - - [JsonProperty("displayName")] - public string DisplayName { get; set; } - - [JsonProperty("email")] - public string Email { get; set; } - - [JsonProperty("smsNumber")] - public string SmsNumber { get; set; } - - [JsonProperty("tokens")] - public List Tokens { get; set; } - } -} diff --git a/attic/windows/WinUI/Fonts/segoeui.ttf b/attic/windows/WinUI/Fonts/segoeui.ttf deleted file mode 100644 index fc18ebd0a..000000000 Binary files a/attic/windows/WinUI/Fonts/segoeui.ttf and /dev/null differ diff --git a/attic/windows/WinUI/Fonts/segoeuib.ttf b/attic/windows/WinUI/Fonts/segoeuib.ttf deleted file mode 100644 index 5f31e0ca6..000000000 Binary files a/attic/windows/WinUI/Fonts/segoeuib.ttf and /dev/null differ diff --git a/attic/windows/WinUI/Fonts/segoeuii.ttf b/attic/windows/WinUI/Fonts/segoeuii.ttf deleted file mode 100644 index 7efb70d60..000000000 Binary files a/attic/windows/WinUI/Fonts/segoeuii.ttf and /dev/null differ diff --git a/attic/windows/WinUI/Fonts/segoeuiz.ttf b/attic/windows/WinUI/Fonts/segoeuiz.ttf deleted file mode 100644 index d7bb186b3..000000000 Binary files a/attic/windows/WinUI/Fonts/segoeuiz.ttf and /dev/null differ diff --git a/attic/windows/WinUI/ISwitchable.cs b/attic/windows/WinUI/ISwitchable.cs deleted file mode 100644 index e485a14cb..000000000 --- a/attic/windows/WinUI/ISwitchable.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WinUI -{ - interface ISwitchable - { - void UtilizeState(object state); - } -} diff --git a/attic/windows/WinUI/JoinNetworkView.xaml b/attic/windows/WinUI/JoinNetworkView.xaml deleted file mode 100644 index 1cd1e98d8..000000000 --- a/attic/windows/WinUI/JoinNetworkView.xaml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - -