repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
ZJNixiang/HookZz
|
src/interceptor_routing.c
|
#include "interceptor_routing.h"
#include "thread_support/thread_stack.h"
void interceptor_routing_begin(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR, void *ret_addr_PTR) {
// DEBUG_LOG("target %p call begin-invocation", entry->target_ptr);
thread_stack_manager_t *thread_stack_manager = thread_stack_cclass(shared_instance)();
call_stack_t *call_stack = call_stack_cclass(new)(thread_stack_manager);
thread_stack_cclass(push_call_stack)(thread_stack_manager, call_stack);
// call pre_call
if (entry->pre_call) {
PRECALL pre_call;
HookEntryInfo entryInfo;
entryInfo.hook_id = entry->id;
entryInfo.target_address = entry->target_address;
pre_call = entry->pre_call;
ThreadStackPublic tsp = {thread_stack_manager->thread_id, thread_stack_manager->call_stacks->len};
CallStackPublic csp = {call_stack->call_id};
(*pre_call)(rs, &tsp, &csp, &entryInfo);
}
// set next hop
if (entry->replace_call) {
*(zz_ptr_t *)next_hop_addr_PTR = entry->replace_call;
} else {
*(zz_ptr_t *)next_hop_addr_PTR = entry->on_invoke_trampoline;
}
if (entry->type == HOOK_TYPE_FUNCTION_via_PRE_POST || entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
call_stack->ret_addr = *(zz_ptr_t *)ret_addr_PTR;
*(zz_ptr_t *)ret_addr_PTR = entry->on_leave_trampoline;
}
}
void interceptor_routing_end(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR) {
// DEBUG_LOG("%p call end-invocation", entry->target_ptr);
thread_stack_manager_t *thread_stack_manager = thread_stack_cclass(shared_instance)();
call_stack_t *call_stack = thread_stack_cclass(pop_call_stack)(thread_stack_manager);
// call post_call
if (entry->post_call) {
POSTCALL post_call;
HookEntryInfo entryInfo;
entryInfo.hook_id = entry->id;
entryInfo.target_address = entry->target_address;
post_call = entry->post_call;
ThreadStackPublic tsp = {thread_stack_manager->thread_id, thread_stack_manager->call_stacks->len};
CallStackPublic csp = {call_stack->call_id};
(*post_call)(rs, &tsp, &csp, (const HookEntryInfo *)&entryInfo);
}
// set next hop
*(zz_ptr_t *)next_hop_addr_PTR = call_stack->ret_addr;
call_stack_cclass(destory)(call_stack);
}
void interceptor_routing_dynamic_binary_instrumentation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR) {
// DEBUG_LOG("target %p call dynamic-binary-instrumentation-invocation", entry->target_ptr);
if (entry->dbi_call) {
DBICALL dbi_call;
HookEntryInfo entryInfo;
entryInfo.hook_id = entry->id;
entryInfo.target_address = entry->target_address;
dbi_call = entry->dbi_call;
(*dbi_call)(rs, (const HookEntryInfo *)&entryInfo);
}
*(zz_ptr_t *)next_hop_addr_PTR = entry->on_invoke_trampoline;
}
void interceptor_routing_begin_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) {
hook_entry_t *entry = cb_info->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
void *ret_addr_PTR = get_ret_addr_PTR(rs);
interceptor_routing_begin(rs, entry, next_hop_addr_PTR, ret_addr_PTR);
return;
}
void interceptor_routing_end_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) {
hook_entry_t *entry = cb_info->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
interceptor_routing_end(rs, entry, next_hop_addr_PTR);
return;
}
void interceptor_routing_dynamic_binary_instrumentation_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) {
hook_entry_t *entry = cb_info->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
interceptor_routing_dynamic_binary_instrumentation(rs, entry, next_hop_addr_PTR);
return;
}
void interceptor_routing_common_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) {
USER_CODE_CALL userCodeCall = cb_info->user_code;
// TODO: package as a function `beautiful_stack()`
uintptr_t fp_reg;
fp_reg = get_current_fp_reg();
uintptr_t *none_symbol_PTR = (uintptr_t *)fp_reg + 1;
uintptr_t none_symbol = *none_symbol_PTR;
uintptr_t *ret_addr_PTR = get_ret_addr_PTR(rs);
uintptr_t ret_addr = *ret_addr_PTR;
*none_symbol_PTR = ret_addr;
userCodeCall(rs, cb_info);
*none_symbol_PTR = none_symbol;
return;
}
#if DYNAMIC_CLOSURE_BRIDGE
void interceptor_routing_begin_dynamic_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcb_info) {
hook_entry_t *entry = dcb_info->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
void *ret_addr_PTR = get_ret_addr_PTR(rs);
interceptor_routing_begin(rs, entry, next_hop_addr_PTR, ret_addr_PTR);
return;
}
void interceptor_routing_end_dynamic_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcb_info) {
hook_entry_t *entry = dcb_info->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
interceptor_routing_end(rs, entry, next_hop_addr_PTR);
return;
}
void interceptor_routing_dynamic_common_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcb_info) {
DYNAMIC_USER_CODE_CALL userCodeCall = dcb_info->user_code;
userCodeCall(rs, dcb_info);
return;
}
#endif
|
ZJNixiang/HookZz
|
srcxx/Platforms/backend-posix/PosixThreadManager.h
|
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_POSIXTHREADMANAGER_H
#define HOOKZZ_POSIXTHREADMANAGER_H
#endif //HOOKZZ_POSIXTHREADMANAGER_H
|
ZJNixiang/HookZz
|
src/instruction_relocation.h
|
<gh_stars>1-10
#include "interceptor.h"
#include "macros.h"
PLATFORM_API void instruction_relocation_inspect(void *dest, int *limit_length_PTR);
PLATFORM_API void instruction_relocation_build(void *dest, void *src, int length);
|
ZJNixiang/HookZz
|
src/platforms/arch-arm64/interceptor-routing-trampoline-arm64.h
|
/**
* Copyright 2017 jmpews
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef interceptor_routing_trampoline_arm64_h
#define interceptor_routing_trampoline_arm64_h
#include "hookzz.h"
#include "interceptor.h"
#include "memory_manager.h"
#include "reader-arm64.h"
#include "relocator-arm64.h"
#include "writer-arm64.h"
#define CTX_SAVE_STACK_OFFSET (8 + 30 * 8 + 8 * 16)
typedef struct _interceptor_backend_arm64_t {
memory_manager_t *memory_manager;
ARM64Relocator *relocator_arm64;
ARM64AssemblyWriter *writer_arm64;
ARM64AssemblyReader *reader_arm64;
} interceptor_backend_arm64_t;
typedef struct _hook_entry_backend_arm64_t {
int limit_relocate_inst_size;
} hook_entry_backend_arm64_t;
#endif
|
ZJNixiang/HookZz
|
src/platforms/backend-x86/custom-bridge-handler.c
|
<filename>src/platforms/backend-x86/custom-bridge-handler.c
//
// Created by z on 2018/4/7.
//
#include "custom-bridge-handler.h"
#include "closure-bridge-x86.h"
#include <CommonKit/log/log_kit.h>
#include <debuglog.h>
#include <hookzz.h>
void context_begin_invocation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR, void *ret_addr_PTR) {}
void context_begin_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) { return; }
void context_end_invocation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR) {}
void context_end_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) { return; }
void dynamic_binary_instrumentation_invocation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR) {}
void dynamic_binary_instrumentationn_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) { return; }
|
ZJNixiang/HookZz
|
src/interceptor_routing_trampoline.c
|
<filename>src/interceptor_routing_trampoline.c
#include "interceptor_routing_trampoline.h"
void interceptor_trampoline_cclass(build_all)(hook_entry_t *entry) {
if (entry->type == HOOK_TYPE_FUNCTION_via_PRE_POST) {
interceptor_trampoline_cclass(prepare)(entry);
interceptor_trampoline_cclass(build_for_enter)(entry);
interceptor_trampoline_cclass(build_for_invoke)(entry);
interceptor_trampoline_cclass(build_for_leave)(entry);
} else if (entry->type == HOOK_TYPE_FUNCTION_via_REPLACE) {
interceptor_trampoline_cclass(prepare)(entry);
interceptor_trampoline_cclass(build_for_enter_transfer)(entry);
interceptor_trampoline_cclass(build_for_invoke)(entry);
} else if (entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
// trampoline_prepare(self, entry);
interceptor_trampoline_cclass(build_for_enter)(entry);
interceptor_trampoline_cclass(build_for_leave)(entry);
} else if (entry->type == HOOK_TYPE_INSTRUCTION_via_DBI) {
interceptor_trampoline_cclass(prepare)(entry);
interceptor_trampoline_cclass(build_for_dynamic_binary_instrumentation)(entry);
interceptor_trampoline_cclass(build_for_invoke)(entry);
}
return;
}
|
ZJNixiang/HookZz
|
src/platforms/backend-darwin/dynamic-closure-bridge-darwin.c
|
#include "closure_bridge.h"
DynamicClosureBridge *DynamicClosureBridgeCClass(SharedInstance)() { return NULL; }
DynamicClosureBridgeInfo *DynamicClosureBridgeCClass(AllocateDynamicClosureBridge)(DynamicClosureBridge *self,
void *user_data, void *user_code) {
return NULL;
}
DynamicClosureBridgeTrampolineTable *
DynamicClosureBridgeCClass(AllocateDynamicClosureBridgeTrampolineTable)(DynamicClosureBridge *self) {
return NULL;
}
|
ZJNixiang/HookZz
|
srcxx/Platforms/arch-arm64/ARM64Helper.h
|
//
// Created by jmpews on 2018/6/15.
//
#ifndef HOOKZZ_ARM64HELPER_H
#define HOOKZZ_ARM64HELPER_H
#endif //HOOKZZ_ARM64HELPER_H
|
ZJNixiang/HookZz
|
src/macros.h
|
#ifndef macros_h
#define macros_h
#include <stdint.h>
#define INT5_MASK 0x0000001f
#define INT8_MASK 0x000000ff
#define INT10_MASK 0x000003ff
#define INT11_MASK 0x000007ff
#define INT12_MASK 0x00000fff
#define INT14_MASK 0x00003fff
#define INT16_MASK 0x0000ffff
#define INT18_MASK 0x0003ffff
#define INT19_MASK 0x0007ffff
#define INT24_MASK 0x00ffffff
#define INT26_MASK 0x03ffffff
#define INT28_MASK 0x0fffffff
#define THUMB_FUNCTION_ADDRESS(address) ((uintptr_t)address & ~(uintptr_t)1)
#define INSTRUCTION_IS_THUMB(insn_addr) (((uintptr_t)insn_addr & 0x1) == 0x1)
#define ALIGN_FLOOR(address, range) ((uintptr_t)address & ~((uintptr_t)range - 1))
#define ALIGN_CEIL(address, range) (((uintptr_t)address + (uintptr_t)range - 1) & ~((uintptr_t)range - 1))
#endif
|
ZJNixiang/HookZz
|
src/platforms/backend-x86/custom-bridge-handler.h
|
//
// Created by z on 2018/4/7.
//
#ifndef CUSTOM_BRIDGE_HANDLER_H
#define CUSTOM_BRIDGE_HANDLER_H
#include "closure-bridge-x86.h"
#include "hookzz.h"
#include "interceptor.h"
#include "zkit.h"
void context_end_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info);
void context_begin_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info);
void dynamic_binary_instrumentationn_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info);
#endif //CUSTOM_BRIDGE_HANDLER_H
|
ZJNixiang/HookZz
|
srcxx/Interceptor.h
|
//
// Created by z on 2018/6/14.
//
#ifndef HOOKZZ_INTERCEPTOR_H
#define HOOKZZ_INTERCEPTOR_H
#include "MemoryManager.h"
#include "ThreadManager.h"
#include "hookzz.h"
#include <iostream>
#include <vector>
typedef struct _FunctionBackup {
void *address;
int size;
char data[32];
} FunctionBackup;
class Interceptor;
class InterceptorBackend;
struct HookEntryBackend;
typedef struct _HookEntry {
void *target_address;
HookType type;
unsigned int id;
bool isEnabled;
bool isTryNearJump;
bool isNearJump;
PRECALL pre_call;
POSTCALL post_call;
STUBCALL stub_call;
void *replace_call;
void *on_enter_transfer_trampoline;
void *on_enter_trampoline;
void *on_invoke_trampoline;
void *on_leave_trampoline;
void *on_dynamic_binary_instrumentation_trampoline;
FunctionBackup origin_prologue;
struct HookEntryBackend *backend;
Interceptor *interceptor;
} HookEntry;
class Interceptor {
private:
static int t;
static Interceptor *priv_interceptor;
MemoryManager *mm;
public:
bool isSupportRXMemory;
std::vector<HookEntry *> hook_entries;
public:
static Interceptor *GETInstance();
HookEntry *findHookEntry(void *target_address);
void addHookEntry(HookEntry *hook_entry);
void initializeBackend(MemoryManager *mm);
private:
Interceptor() {}
};
#endif //HOOKZZ_INTERCEPTOR_H
|
ZJNixiang/HookZz
|
src/std_kit/std_macros.h
|
<reponame>ZJNixiang/HookZz
#ifndef thread_local
#if __STDC_VERSION__ >= 201112 && !defined __STDC_NO_THREADS__
#define thread_local _Thread_local
#elif defined _WIN32 && (defined _MSC_VER || defined __ICL || defined __DMC__ || defined __BORLANDC__)
#define thread_local __declspec(thread)
/* note that ICC (linux) and Clang are covered by __GNUC__ */
#elif defined __GNUC__ || defined __SUNPRO_C || defined __xlC__
#define thread_local __thread
#else
#undef thread_local
// #error "Cannot define thread_local"
#endif
#endif
|
ZJNixiang/HookZz
|
src/platforms/arch-arm64/interceptor-routing-trampoline-arm64.c
|
<reponame>ZJNixiang/HookZz
#include "interceptor-routing-trampoline-arm64.h"
#include "closure_bridge.h"
#include "interceptor.h"
#include "interceptor_routing.h"
#include "interceptor_routing_trampoline.h"
#include "logging.h"
#include "macros.h"
#include "memory_manager.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#define ARM64_TINY_REDIRECT_SIZE 4
#define ARM64_FULL_REDIRECT_SIZE 16
#define ARM64_NEAR_JUMP_RANGE ((1 << 25) << 2)
void interceptor_cclass(initialize_interceptor_backend)(memory_manager_t *memory_manager) {
if (memory_manager == NULL) {
memory_manager = memory_manager_cclass(shared_instance)();
}
interceptor_backend_arm64_t *backend = SAFE_MALLOC_TYPE(interceptor_backend_arm64_t);
backend->reader_arm64 = SAFE_MALLOC_TYPE(ARM64AssemblyReader);
backend->writer_arm64 = SAFE_MALLOC_TYPE(ARM64AssemblyWriter);
backend->relocator_arm64 = SAFE_MALLOC_TYPE(ARM64Relocator);
backend->memory_manager = memory_manager;
}
ARCH_API void interceptor_trampoline_cclass(prepare)(hook_entry_t *entry) {
int limit_relocate_inst_size = 0;
hook_entry_backend_arm64_t *entry_backend = SAFE_MALLOC_TYPE(hook_entry_backend_arm64_t);
entry->backend = (struct _hook_entry_backend_t *)entry_backend;
if (entry->is_try_near_jump) {
entry_backend->limit_relocate_inst_size = ARM64_TINY_REDIRECT_SIZE;
} else {
arm64_assembly_relocator_cclass(try_relocate)(entry->target_address, ARM64_FULL_REDIRECT_SIZE,
&limit_relocate_inst_size);
if (limit_relocate_inst_size != 0 && limit_relocate_inst_size > ARM64_TINY_REDIRECT_SIZE &&
limit_relocate_inst_size < ARM64_FULL_REDIRECT_SIZE) {
entry->is_near_jump = true;
entry_backend->limit_relocate_inst_size = ARM64_TINY_REDIRECT_SIZE;
} else if (limit_relocate_inst_size != 0 && limit_relocate_inst_size < ARM64_TINY_REDIRECT_SIZE) {
return;
} else {
entry_backend->limit_relocate_inst_size = ARM64_FULL_REDIRECT_SIZE;
}
}
// save original prologue
memcpy(entry->origin_prologue.data, entry->target_address, entry_backend->limit_relocate_inst_size);
entry->origin_prologue.size = entry_backend->limit_relocate_inst_size;
entry->origin_prologue.address = entry->target_address;
}
ARCH_API void interceptor_trampoline_cclass(active)(hook_entry_t *entry) {
hook_entry_backend_arm64_t *entry_backend = (hook_entry_backend_arm64_t *)entry->backend;
ARM64AssemblyWriter *writer_arm64 = NULL;
writer_arm64 = arm64_assembly_writer_cclass(new)(entry->target_address);
// if use near jump, all is same
if (entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
arm64_assembly_writer_cclass(put_b_imm)(writer_arm64, (zz_addr_t)entry->on_enter_transfer_trampoline -
(zz_addr_t)writer_arm64->start_pc);
} else {
arm64_assembly_writer_cclass(put_ldr_reg_imm)(writer_arm64, ARM64_REG_X17, 0x8);
arm64_assembly_writer_cclass(put_br_reg)(writer_arm64, ARM64_REG_X17);
if (entry->type == HOOK_TYPE_FUNCTION_via_REPLACE) {
arm64_assembly_writer_cclass(put_bytes)(writer_arm64, &entry->on_enter_transfer_trampoline, sizeof(void *));
} else if (entry->type == HOOK_TYPE_INSTRUCTION_via_DBI) {
arm64_assembly_writer_cclass(put_bytes)(writer_arm64, &entry->on_dynamic_binary_instrumentation_trampoline,
sizeof(void *));
} else {
arm64_assembly_writer_cclass(put_bytes)(writer_arm64, &entry->on_enter_trampoline, sizeof(void *));
}
}
memory_manager_t *memory_manager = memory_manager_cclass(shared_instance)();
memory_manager_cclass(patch_code)(memory_manager, entry->target_address, writer_arm64->inst_bytes->data,
writer_arm64->inst_bytes->size);
arm64_assembly_writer_cclass(destory)(writer_arm64);
{
char buffer[1024] = {};
sprintf(buffer + strlen(buffer), "\n======= Logging ======= \n");
sprintf(buffer + strlen(buffer), "\tTargetAddress: %p\n", entry->target_address);
sprintf(buffer + strlen(buffer), "\tArchitecture: ARM64\n");
if (entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
sprintf(buffer + strlen(buffer), "\tBrachJumpType: Near Jump(B xxx)\n");
} else if (entry_backend->limit_relocate_inst_size == ARM64_FULL_REDIRECT_SIZE) {
sprintf(buffer + strlen(buffer), "\ttBrachJumpType: Abs Jump(ldr r17, #4; .long address)\n");
}
if (entry->is_near_jump && entry->on_enter_transfer_trampoline)
sprintf(buffer + strlen(buffer), "\ton_enter_transfer_trampoline: %p\n",
entry->on_enter_transfer_trampoline);
if (entry->type == HOOK_TYPE_INSTRUCTION_via_DBI) {
sprintf(buffer + strlen(buffer), "\tHook Type: HOOK_TYPE_INSTRUCTION_via_DBI\n");
sprintf(buffer + strlen(buffer), "\ton_dynamic_binary_instrumentation_trampoline: %p\n",
entry->on_dynamic_binary_instrumentation_trampoline);
sprintf(buffer + strlen(buffer), "\ton_invoke_trampoline: %p\n", entry->on_invoke_trampoline);
} else if (entry->type == HOOK_TYPE_FUNCTION_via_PRE_POST) {
sprintf(buffer + strlen(buffer), "\tHook Type: HOOK_TYPE_FUNCTION_via_PRE_POST\n");
sprintf(buffer + strlen(buffer), "\ton_enter_trampoline: %p\n", entry->on_enter_trampoline);
sprintf(buffer + strlen(buffer), "\ton_leave_trampoline: %p\n", entry->on_leave_trampoline);
sprintf(buffer + strlen(buffer), "\ton_invoke_trampoline: %p\n", entry->on_invoke_trampoline);
} else if (entry->type == HOOK_TYPE_FUNCTION_via_REPLACE) {
sprintf(buffer + strlen(buffer), "\tHook Type: HOOK_TYPE_FUNCTION_via_REPLACE\n");
sprintf(buffer + strlen(buffer), "\ton_enter_transfer_trampoline: %p\n",
entry->on_enter_transfer_trampoline);
sprintf(buffer + strlen(buffer), "\ton_invoke_trampoline: %p\n", entry->on_invoke_trampoline);
} else if (entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
sprintf(buffer + strlen(buffer), "\tHook Type: HOOK_TYPE_FUNCTION_via_GOT\n");
sprintf(buffer + strlen(buffer), "\ton_enter_trampoline: %p\n", entry->on_enter_trampoline);
sprintf(buffer + strlen(buffer), "\ton_leave_trampoline: %p\n", entry->on_leave_trampoline);
}
Logging("%s", buffer);
}
}
ARCH_API void interceptor_trampoline_cclass(build_for_enter_transfer)(hook_entry_t *entry) {
hook_entry_backend_arm64_t *entry_backend = (hook_entry_backend_arm64_t *)entry->backend;
ARM64AssemblyWriter *writer_arm64 = NULL;
writer_arm64 = arm64_assembly_writer_cclass(new)(0);
arm64_assembly_writer_cclass(put_ldr_reg_imm)(writer_arm64, ARM64_REG_X17, 0x8);
arm64_assembly_writer_cclass(put_br_reg)(writer_arm64, ARM64_REG_X17);
if (entry->type == HOOK_TYPE_FUNCTION_via_REPLACE) {
arm64_assembly_writer_cclass(put_bytes)(writer_arm64, &entry->replace_call, sizeof(void *));
} else if (entry->type == HOOK_TYPE_INSTRUCTION_via_DBI) {
arm64_assembly_writer_cclass(put_bytes)(writer_arm64, &entry->on_dynamic_binary_instrumentation_trampoline,
sizeof(void *));
} else {
arm64_assembly_writer_cclass(put_bytes)(writer_arm64, &entry->on_enter_trampoline, sizeof(void *));
}
memory_manager_t *memory_manager = memory_manager_cclass(shared_instance)();
if (entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
CodeCave *cc = NULL;
cc = memory_manager_cclass(search_code_cave)(memory_manager, entry->target_address,
arm64_assembly_writer_cclass(bxxx_range)(),
writer_arm64->inst_bytes->size);
XCHECK(cc);
arm64_assembly_writer_cclass(patch_to)(writer_arm64, cc->address);
entry->on_enter_transfer_trampoline = (void *)cc->address;
SAFE_FREE(cc);
} else {
CodeSlice *cs = NULL;
cs = memory_manager_cclass(allocate_code_slice)(memory_manager, writer_arm64->inst_bytes->size);
XCHECK(cs);
arm64_assembly_writer_cclass(patch_to)(writer_arm64, cs->data);
entry->on_enter_transfer_trampoline = (void *)cs->data;
SAFE_FREE(cs);
}
}
ARCH_API void interceptor_trampoline_cclass(build_for_enter)(hook_entry_t *entry) {
hook_entry_backend_arm64_t *entry_backend = (hook_entry_backend_arm64_t *)entry->backend;
#if DYNAMIC_CLOSURE_BRIDGE
if (entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
DynamicClosureBridgeInfo *dcbInfo = NULL;
DynamicClosureBridge *dcb = DynamicClosureBridgeCClass(SharedInstance)();
DynamicClosureBridgeCClass(AllocateDynamicClosureBridge)(
dcb, entry, (void *)interceptor_routing_begin_dynamic_bridge_handler);
if (dcbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_enter_trampoline = dcbInfo->redirect_trampoline;
}
#else
if (entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
ClosureBridgeInfo *cbInfo = NULL;
ClosureBridge *cb = ClosureBridgeCClass(SharedInstance)();
cbInfo =
ClosureBridgeCClass(AllocateClosureBridge)(cb, entry, (void *)interceptor_routing_begin_bridge_handler);
if (cbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_enter_trampoline = cbInfo->redirect_trampoline;
}
#endif
if (entry->type != HOOK_TYPE_FUNCTION_via_GOT) {
ClosureBridgeInfo *cbInfo = NULL;
ClosureBridge *cb = ClosureBridgeCClass(SharedInstance)();
cbInfo =
ClosureBridgeCClass(AllocateClosureBridge)(cb, entry, (void *)interceptor_routing_begin_bridge_handler);
if (cbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_enter_trampoline = cbInfo->redirect_trampoline;
}
// build the double trampline aka enter_transfer_trampoline
if (entry_backend && entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
if (entry->type != HOOK_TYPE_FUNCTION_via_GOT) {
interceptor_trampoline_cclass(build_for_enter_transfer)(entry);
}
}
}
ARCH_API void interceptor_trampoline_cclass(build_for_invoke)(hook_entry_t *entry) {
hook_entry_backend_arm64_t *entry_backend = (hook_entry_backend_arm64_t *)entry->backend;
zz_addr_t origin_next_inst_addr;
ARM64AssemblyReader *reader_arm64 = arm64_assembly_reader_cclass(new)(entry->target_address, entry->target_address);
ARM64AssemblyWriter *writer_arm64 = arm64_assembly_writer_cclass(new)(0);
ARM64Relocator *relocator_arm64 = arm64_assembly_relocator_cclass(new)(reader_arm64, writer_arm64);
do {
arm64_assembly_reader_cclass(read_inst)(relocator_arm64->input);
arm64_assembly_relocator_cclass(relocate_write)(relocator_arm64);
} while (relocator_arm64->input->inst_bytes->size < entry_backend->limit_relocate_inst_size);
assert(entry_backend->limit_relocate_inst_size == relocator_arm64->input->inst_bytes->size);
origin_next_inst_addr = (zz_addr_t)entry->target_address + relocator_arm64->input->inst_bytes->size;
arm64_assembly_writer_cclass(put_ldr_reg_imm)(writer_arm64, ARM64_REG_X17, 0x8);
arm64_assembly_writer_cclass(put_br_reg)(writer_arm64, ARM64_REG_X17);
arm64_assembly_writer_cclass(put_bytes)(writer_arm64, &origin_next_inst_addr, sizeof(void *));
memory_manager_t *memory_manager = memory_manager_cclass(shared_instance)();
CodeSlice *cs = NULL;
cs = memory_manager_cclass(allocate_code_slice)(memory_manager, relocator_arm64->output->inst_bytes->size);
XCHECK(cs);
arm64_assembly_relocator_cclass(double_write)(relocator_arm64, cs->data);
arm64_assembly_writer_cclass(patch_to)(relocator_arm64->output, cs->data);
entry->on_invoke_trampoline = (void *)cs->data;
SAFE_FREE(cs);
}
ARCH_API void interceptor_trampoline_cclass(build_for_leave)(hook_entry_t *entry) {
hook_entry_backend_arm64_t *entry_backend = (hook_entry_backend_arm64_t *)entry->backend;
#if DYNAMIC_CLOSURE_BRIDGE
if (entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
DynamicClosureBridgeInfo *dcbInfo = NULL;
DynamicClosureBridge *dcb = DynamicClosureBridgeCClass(SharedInstance)();
dcbInfo = DynamicClosureBridgeCClass(AllocateDynamicClosureBridge)(
dcb, entry, (void *)interceptor_routing_end_dynamic_bridge_handler);
if (dcbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_leave_trampoline = dcbInfo->redirect_trampoline;
}
#else
if (entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
ClosureBridgeInfo *cbInfo = NULL;
ClosureBridge *cb = ClosureBridgeCClass(SharedInstance)();
cbInfo = ClosureBridgeCClass(AllocateClosureBridge)(cb, entry, (void *)interceptor_routing_end_bridge_handler);
if (cbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_leave_trampoline = cbInfo->redirect_trampoline;
}
#endif
if (entry->type != HOOK_TYPE_FUNCTION_via_GOT) {
ClosureBridgeInfo *cbInfo = NULL;
ClosureBridge *cb = ClosureBridgeCClass(SharedInstance)();
cbInfo = ClosureBridgeCClass(AllocateClosureBridge)(cb, entry, (void *)interceptor_routing_end_bridge_handler);
if (cbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_leave_trampoline = cbInfo->redirect_trampoline;
}
}
ARCH_API void interceptor_trampoline_cclass(build_for_dynamic_binary_instrumentation)(hook_entry_t *entry) {
hook_entry_backend_arm64_t *entry_backend = (hook_entry_backend_arm64_t *)entry->backend;
ClosureBridgeInfo *cbInfo = NULL;
ClosureBridge *cb = ClosureBridgeCClass(SharedInstance)();
cbInfo = ClosureBridgeCClass(AllocateClosureBridge)(
cb, entry, (void *)interceptor_routing_dynamic_binary_instrumentation_bridge_handler);
if (cbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_dynamic_binary_instrumentation_trampoline = cbInfo->redirect_trampoline;
// build the double trampline aka enter_transfer_trampoline
if (entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
if (entry->type != HOOK_TYPE_FUNCTION_via_GOT) {
interceptor_trampoline_cclass(build_for_enter_transfer)(entry);
}
}
}
|
ZJNixiang/HookZz
|
src/platforms/arch-arm64/relocator-arm64.h
|
<gh_stars>1-10
#ifndef platforms_arch_arm64_relocator_h
#define platforms_arch_arm64_relocator_h
#include "instruction.h"
#include "reader-arm64.h"
#include "register-arm64.h"
#include "writer-arm64.h"
#include "std_kit/std_buffer_array.h"
#include "std_kit/std_kit.h"
#include "std_kit/std_list.h"
typedef struct _io_index_t {
int input_index;
int output_index;
} io_index_t;
typedef struct _ARM64Relocator {
ARM64AssemblyReader *input;
ARM64AssemblyWriter *output;
list_t *literal_instCTXs;
list_t *io_indexs;
} ARM64Relocator;
#define arm64_assembly_relocator_cclass(member) cclass(arm64_relocator, member)
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
ARM64Relocator *arm64_assembly_relocator_cclass(new)(ARM64AssemblyReader *input, ARM64AssemblyWriter *output);
void arm64_assembly_relocator_cclass(reset)(ARM64Relocator *self, ARM64AssemblyReader *input, ARM64AssemblyWriter *output);
void arm64_assembly_relocator_cclass(try_relocate)(void *address, int bytes_min, int *bytes_max);
void arm64_assembly_relocator_cclass(relocate_to)(ARM64Relocator *self, void *target_address);
void arm64_assembly_relocator_cclass(double_write)(ARM64Relocator *self, void *target_address);
void arm64_assembly_relocator_cclass(register_literal_instCTX)(ARM64Relocator *self, ARM64InstructionCTX *instCTX);
void arm64_assembly_relocator_cclass(relocate_write)(ARM64Relocator *self);
void arm64_assembly_relocator_cclass(relocate_write_all)(ARM64Relocator *self);
void arm64_assembly_relocator_cclass(rewrite_LoadLiteral)(ARM64Relocator *self, ARM64InstructionCTX *instCTX);
void arm64_assembly_relocator_cclass(rewrite_BaseCmpBranch)(ARM64Relocator *self, ARM64InstructionCTX *instCTX);
void arm64_assembly_relocator_cclass(rewrite_BranchCond)(ARM64Relocator *self, ARM64InstructionCTX *instCTX);
void arm64_assembly_relocator_cclass(rewrite_B)(ARM64Relocator *self, ARM64InstructionCTX *instCTX);
void arm64_assembly_relocator_cclass(rewrite_BL)(ARM64Relocator *self, ARM64InstructionCTX *instCTX);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif
|
ZJNixiang/HookZz
|
src/platforms/backend-x86/interceptor-x86.c
|
#include "interceptor-x86.h"
#include "backend-x86-helper.h"
#include "closure-bridge-x86.h"
#include "custom-bridge-handler.h"
#include <debuglog.h>
#include <stdlib.h>
#include <string.h>
#define ZZ_X86_TINY_REDIRECT_SIZE 4
#define ZZ_X86_FULL_REDIRECT_SIZE 16
InterceptorBackend *InteceptorBackendNew(ExecuteMemoryManager *emm) { return NULL; }
void trampoline_free(hook_entry_t *entry) {
if (entry->on_invoke_trampoline) {
//TODO
}
if (entry->on_enter_trampoline) {
//TODO
}
if (entry->on_enter_transfer_trampoline) {
//TODO
}
if (entry->on_leave_trampoline) {
//TODO
}
if (entry->on_invoke_trampoline) {
//TODO
}
return;
}
void trampoline_prepare(InterceptorBackend *self, hook_entry_t *entry) { return; }
// double jump
void trampoline_build_for_enter_transfer(InterceptorBackend *self, hook_entry_t *entry) { return; }
void trampoline_build_for_enter(InterceptorBackend *self, hook_entry_t *entry) { return; }
void trampoline_build_for_dynamic_binary_instrumentation(InterceptorBackend *self, hook_entry_t *entry) { return; }
void trampoline_build_for_invoke(InterceptorBackend *self, hook_entry_t *entry) { return; }
void trampoline_build_for_leave(InterceptorBackend *self, hook_entry_t *entry) { return; }
void trampoline_active(InterceptorBackend *self, hook_entry_t *entry) { return; }
|
ZJNixiang/HookZz
|
src/std_kit/std_kit.h
|
#ifndef std_kit_std_kit_h
#define std_kit_std_kit_h
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* malloc with 0 and NULL check */
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
void *safe_malloc(size_t size);
#ifdef __cplusplus
}
#endif //__cplusplus
/* malloc macro */
#define SAFE_MALLOC_TYPE(TYPE) (TYPE *)safe_malloc(sizeof(TYPE));
/* safe free*/
#define SAFE_FREE(obj) \
do { \
free(obj); \
obj = NULL; \
} while (0);
#include <errno.h>
#if ENABLE_COLOR_LOG
#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"
#define RESET "\x1B[0m"
#else
#define RED ""
#define GRN ""
#define YEL ""
#define BLU ""
#define MAG ""
#define CYN ""
#define WHT ""
#define RESET ""
#endif
#define ENABLE_PRINT_ERROR_STRING 0
#define ERROR_LOG_ERRNO() \
do { \
fprintf(stderr, "======= ERRNO [%d] STRING ======= \n", errno); \
perror((const char *)strerror(errno)); \
} while (0);
#define ERROR_LOG(fmt, ...) \
do { \
fprintf(stderr, \
RED "[!] " \
"%s:%d:%s(): " fmt RESET "\n", \
__FILE__, __LINE__, __func__, __VA_ARGS__); \
} while (0)
#define ERROR_LOG_STR(MSG) ERROR_LOG("%s", MSG)
#define ERROR_LOG_LINE() ERROR_LOG_STR(">>> ERROR <<<")
#define XCHECK(repr) \
do { \
if (repr) { /*pass*/ \
} else { \
ERROR_LOG_LINE(); \
} \
} while (0);
#endif
|
ZJNixiang/HookZz
|
src/interceptor_routing_trampoline.h
|
#ifndef interceptor_routing_trampoline_h
#define interceptor_routing_trampoline_h
#include "core.h"
#include "hookzz.h"
#include "interceptor.h"
#define interceptor_trampoline_cclass(member) cclass(interceptor_trampoline, member)
void interceptor_trampoline_cclass(free)(hook_entry_t *entry);
void interceptor_trampoline_cclass(build_all)(hook_entry_t *entry);
ARCH_API void interceptor_trampoline_cclass(prepare)(hook_entry_t *entry);
ARCH_API void interceptor_trampoline_cclass(active)(hook_entry_t *entry);
ARCH_API void interceptor_trampoline_cclass(build_for_enter)(hook_entry_t *entry);
ARCH_API void interceptor_trampoline_cclass(build_for_enter_transfer)(hook_entry_t *entry);
ARCH_API void interceptor_trampoline_cclass(build_for_invoke)(hook_entry_t *entry);
ARCH_API void interceptor_trampoline_cclass(build_for_leave)(hook_entry_t *entry);
ARCH_API void interceptor_trampoline_cclass(build_for_dynamic_binary_instrumentation)(hook_entry_t *entry);
#endif
|
ZJNixiang/HookZz
|
srcxx/Platforms/backend-darwin/memory-helper-darwin.c
|
#include "memory-helper-darwin.h"
#include <unistd.h>
int darwin_memory_helper_cclass(get_page_size)() { return getpagesize(); }
void darwin_memory_helper_cclass(get_memory_info)(void *address, vm_prot_t *prot, vm_inherit_t *inherit) {
vm_address_t region = (vm_address_t)address;
vm_size_t region_size = 0;
struct vm_region_submap_short_info_64 info;
mach_msg_type_number_t info_count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64;
natural_t max_depth = 99999;
kern_return_t kr;
kr = vm_region_recurse_64(mach_task_self(), ®ion, ®ion_size, &max_depth, (vm_region_recurse_info_t)&info,
&info_count);
if (kr != KERN_SUCCESS) {
return;
}
*prot = info.protection;
*inherit = info.inheritance;
}
void darwin_memory_helper_cclass(set_page_memory_permission)(void *address, int prot) {
kern_return_t kr;
int page_size = memory_manager_cclass(get_page_size)();
kr = mach_vm_protect(mach_task_self(), (vm_address_t)address, page_size, FALSE, prot);
if (kr != KERN_SUCCESS) {
// LOG-NEED
}
}
|
ZJNixiang/HookZz
|
src/core.h
|
#ifndef core_h
#define core_h
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "logging.h"
#include "std_kit/std_kit.h"
#include "std_kit/std_macros.h"
/* define a macro to make abbreviation */
#define cclass(class, member) class##_##member
#define cxxclass(class, member) class##member
/* indicate this API's implemention is System dependent */
#define PLATFORM_API
/* indicate this API's implemention is Architecture dependent */
#define ARCH_API
/* indicate this API's implemention is public */
#define PUBLIC_API
/* hidden funtion */
#define VIS_HIDDEN __attribute__((visibility("hidden")))
#endif
|
ZJNixiang/HookZz
|
src/platforms/backend-arm/custom-bridge-handler.c
|
<reponame>ZJNixiang/HookZz
//
// Created by z on 2018/4/7.
//
#include "custom-bridge-handler.h"
#include "closure-bridge-arm.h"
#include <CommonKit/log/log_kit.h>
#include <debuglog.h>
#include <hookzz.h>
void context_begin_invocation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR, void *ret_addr_PTR) {
// DEBUG_LOG("target %p call begin-invocation", entry->target_ptr);
// For iOS Easy Debug Breakpoint
// if (!strcmp((char *)(rs->general.regs.x1), "_beginBackgroundTaskWithName:expirationHandler:")) {
// }
ThreadStack *threadstack = ThreadStackGetByThreadLocalKey(entry->thread_local_key);
if (!threadstack) {
threadstack = ThreadStackAllocate(entry->thread_local_key);
}
CallStack *callstack = CallStackAllocate();
ThreadStackPushCallStack(threadstack, callstack);
// call pre_call
if (entry->pre_call) {
PRECALL pre_call;
HookEntryInfo entryInfo;
entryInfo.hook_id = entry->id;
entryInfo.target_address = entry->target_ptr;
pre_call = entry->pre_call;
(*pre_call)(rs, (ThreadStackPublic *)threadstack, (CallStackPublic *)callstack, &entryInfo);
}
// set next hop
if (entry->replace_call) {
*(zz_ptr_t *)next_hop_addr_PTR = entry->replace_call;
} else {
*(zz_ptr_t *)next_hop_addr_PTR = entry->on_invoke_trampoline;
}
if (entry->type == HOOK_TYPE_FUNCTION_via_PRE_POST || entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
callstack->ret_addr_PTR = *(zz_ptr_t *)ret_addr_PTR;
*(zz_ptr_t *)ret_addr_PTR = entry->on_leave_trampoline;
}
}
void context_begin_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) {
hook_entry_t *entry = cb_info->user_data;
void *nextHopPTR = (void *)&rs->general.regs.r12;
void *regLRPTR = (void *)&rs->lr;
context_begin_invocation(rs, entry, nextHopPTR, regLRPTR);
return;
}
void context_end_invocation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR) {
// DEBUG_LOG("%p call end-invocation", entry->target_ptr);
ThreadStack *threadstack = ThreadStackGetByThreadLocalKey(entry->thread_local_key);
if (!threadstack) {
}
CallStack *callstack = ThreadStackPopCallStack(threadstack);
// call post_call
if (entry->post_call) {
POSTCALL post_call;
HookEntryInfo entryInfo;
entryInfo.hook_id = entry->id;
entryInfo.target_address = entry->target_ptr;
post_call = entry->post_call;
(*post_call)(rs, (ThreadStackPublic *)threadstack, (CallStackPublic *)callstack,
(const HookEntryInfo *)&entryInfo);
}
// set next hop
*(zz_ptr_t *)next_hop_addr_PTR = callstack->ret_addr_PTR;
CallStackFree(callstack);
}
void context_end_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) {
hook_entry_t *entry = cb_info->user_data;
void *nextHopPTR = (void *)&rs->general.regs.r12;
context_end_invocation(rs, entry, nextHopPTR);
return;
}
void dynamic_binary_instrumentation_invocation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR) {
DEBUG_LOG("target %p call dynamic-binary-instrumentation-invocation", entry->target_ptr);
/* call pre_call */
if (entry->dbi_call) {
DBICALL dbi_call;
HookEntryInfo entryInfo;
entryInfo.hook_id = entry->id;
entryInfo.target_address = entry->target_ptr;
dbi_call = entry->dbi_call;
(*dbi_call)(rs, (const HookEntryInfo *)&entryInfo);
}
*(zz_ptr_t *)next_hop_addr_PTR = entry->on_invoke_trampoline;
}
void dynamic_binary_instrumentationn_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) {
hook_entry_t *entry = cb_info->user_data;
void *nextHopPTR = (void *)&rs->general.regs.r12;
dynamic_binary_instrumentation_invocation(rs, entry, nextHopPTR);
return;
}
|
ZJNixiang/HookZz
|
src/thread_support/thread_stack.c
|
<filename>src/thread_support/thread_stack.c
#include "thread_stack.h"
#include "core.h"
#include "thread_local_storage.h"
thread_stack_manager_t *thread_stack_cclass(shared_instance)() {
thread_stack_manager_t *g_thread_stack_manager = (thread_stack_manager_t *)get_thread_variable_value();
if (g_thread_stack_manager == NULL) {
g_thread_stack_manager = SAFE_MALLOC_TYPE(thread_stack_manager_t);
g_thread_stack_manager->thread_id = (uintptr_t)g_thread_stack_manager;
g_thread_stack_manager->call_stacks = list_new();
set_thread_variable_value((void *)g_thread_stack_manager);
}
return g_thread_stack_manager;
}
void thread_stack_cclass(push_call_stack)(thread_stack_manager_t *self, call_stack_t *call_stack) {
list_rpush(self->call_stacks, list_node_new(call_stack));
}
call_stack_t *thread_stack_cclass(pop_call_stack)(thread_stack_manager_t *self) {
call_stack_t *call_stack = (call_stack_t *)(list_rpop(self->call_stacks)->val);
return call_stack;
}
call_stack_t *call_stack_cclass(new)(thread_stack_manager_t *thread_stack_manager) {
call_stack_t *call_stack = SAFE_MALLOC_TYPE(call_stack_t);
call_stack->call_id = (uintptr_t)call_stack;
call_stack->context_kv = map_new();
call_stack->thread_stack_manager = thread_stack_manager;
return call_stack;
}
void call_stack_cclass(destory)(call_stack_t *self) {
map_destory(self->context_kv);
SAFE_FREE(self);
}
PUBLIC_API void call_stack_cclass(kv_set)(CallStackPublic *csp, char *key, void *value) {
call_stack_t *call_stack = (call_stack_t *)csp->call_id;
map_value_t mv;
mv._pointer = value;
map_set_value(call_stack->context_kv, key, mv);
}
PUBLIC_API void *call_stack_cclass(kv_get)(CallStackPublic *csp, char *key) {
call_stack_t *call_stack = (call_stack_t *)csp->call_id;
map_value_t mv;
mv = map_get_value(call_stack->context_kv, key);
return mv._pointer;
}
|
ZJNixiang/HookZz
|
src/closure_bridge.c
|
<gh_stars>1-10
#include "closure_bridge.h"
#include "memory_manager.h"
ClosureBridge *gClosureBridge = NULL;
ClosureBridge *ClosureBridgeCClass(SharedInstance)() {
if (gClosureBridge == NULL) {
gClosureBridge = SAFE_MALLOC_TYPE(ClosureBridge);
gClosureBridge->bridge_infos = list_new();
gClosureBridge->trampoline_tables = list_new();
}
return gClosureBridge;
}
ClosureBridgeTrampolineTable *ClosureBridgeCClass(AllocateClosureBridgeTrampolineTable)(ClosureBridge *self) {
void *mmap_page = NULL;
long page_size = 0;
memory_manager_t *memory_manager = memory_manager_cclass(shared_instance)();
void *page_ptr = memory_manager_cclass(allocate_page)(memory_manager, PROT_R_X, 1);
ClosureBridgeTrampolineTable *table = SAFE_MALLOC_TYPE(ClosureBridgeTrampolineTable);
ClosureBridgeCClass(InitializeTablePage)(table, page_ptr);
list_rpush(self->trampoline_tables, list_node_new(table));
return table;
}
ClosureBridgeInfo *ClosureBridgeCClass(AllocateClosureBridge)(ClosureBridge *self, void *user_data, void *user_code) {
ClosureBridgeInfo *cb_info = NULL;
ClosureBridgeTrampolineTable *table = NULL;
list_iterator_t *it = list_iterator_new(self->trampoline_tables, LIST_HEAD);
for (int i = 0; i < self->trampoline_tables->len; i++) {
ClosureBridgeTrampolineTable *tmp_table =
(ClosureBridgeTrampolineTable *)(list_at(self->trampoline_tables, i)->val);
if (tmp_table->free_count > 0) {
table = tmp_table;
}
}
if (!table) {
table = ClosureBridgeCClass(AllocateClosureBridgeTrampolineTable)(self);
}
cb_info = SAFE_MALLOC_TYPE(ClosureBridgeInfo);
ClosureBridgeCClass(InitializeClosureBridgeInfo)(table, cb_info, user_data, user_code);
list_rpush(self->bridge_infos, list_node_new(cb_info));
return cb_info;
}
|
ZJNixiang/HookZz
|
src/platforms/backend-arm/interceptor-arm.c
|
#include "interceptor-arm.h"
#include "backend-arm-helper.h"
#include "custom-bridge-handler.h"
#include <debuglog.h>
#include <stdlib.h>
#define ZZ_THUMB_TINY_REDIRECT_SIZE 4
#define ZZ_THUMB_FULL_REDIRECT_SIZE 8
#define ARM_TINY_REDIRECT_SIZE 4
#define ARM_FULL_REDIRECT_SIZE 8
InterceptorBackend *InteceptorBackendNew(ExecuteMemoryManager *emm) {
if (!MemoryHelperIsSupportAllocateRXMemory()) {
DEBUG_LOG_STR("memory is not support allocate r-x Page!");
return NULL;
}
RetStatus status;
InterceptorBackend *backend = (InterceptorBackend *)malloc0(sizeof(InterceptorBackend));
arm_writer_init(&backend->arm_writer, 0, 0);
arm_reader_init(&backend->arm_reader, 0);
arm_relocator_init(&backend->arm_relocator, &backend->arm_reader, &backend->arm_writer);
thumb_writer_init(&backend->thumb_writer, 0, 0);
thumb_reader_init(&backend->thumb_reader, 0);
thumb_relocator_init(&backend->thumb_relocator, &backend->thumb_reader, &backend->thumb_writer);
backend->emm = emm;
backend->enter_bridge = NULL;
backend->leave_bridge = NULL;
backend->dynamic_binary_instrumentation_bridge = NULL;
if (DebugLogControlerIsEnableLog()) {
char buffer[1024] = {};
sprintf(buffer + strlen(buffer), "\n======= Global interceptor_t Info ======= \n");
sprintf(buffer + strlen(buffer), "\tenter_bridge: %p\n", backend->enter_bridge);
sprintf(buffer + strlen(buffer), "\tleave_bridge: %p\n", backend->leave_bridge);
sprintf(buffer + strlen(buffer), "\tdynamic_binary_instrumentation_bridge: %p\n",
backend->dynamic_binary_instrumentation_bridge);
DEBUGLOG_COMMON_LOG("%s", buffer);
}
if (status == RS_FAILED) {
DEBUG_LOG("%s", "BridgeBuildAll return RS_FAILED\n");
return NULL;
}
return backend;
}
void trampoline_free(hook_entry_t *entry) {
if (entry->on_invoke_trampoline) {
//TODO
}
if (entry->on_enter_trampoline) {
//TODO
}
if (entry->on_enter_transfer_trampoline) {
//TODO
}
if (entry->on_leave_trampoline) {
//TODO
}
if (entry->on_invoke_trampoline) {
//TODO
}
return;
}
void trampoline_prepare(InterceptorBackend *self, hook_entry_t *entry) {
bool is_thumb = FALSE;
zz_addr_t target_addr = (zz_addr_t)entry->target_ptr;
zz_size_t redirect_limit = 0;
ARMHookEntryBackend *entry_backend;
entry_backend = (ARMHookEntryBackend *)malloc0(sizeof(ARMHookEntryBackend));
entry->backend = (struct _HookEntryBackend *)entry_backend;
is_thumb = INSTRUCTION_IS_THUMB((zz_addr_t)entry->target_ptr);
if (is_thumb)
target_addr = THUMB_FUNCTION_ADDRESS(entry->target_ptr);
if (is_thumb) {
if (entry->try_near_jump) {
entry_backend->redirect_code_size = ZZ_THUMB_TINY_REDIRECT_SIZE;
} else {
// check the first few instructions, preparatory work of instruction-fixing
thumb_relocator_try_relocate((zz_ptr_t)target_addr, ZZ_THUMB_FULL_REDIRECT_SIZE, &redirect_limit);
if (redirect_limit != 0 && redirect_limit > ZZ_THUMB_TINY_REDIRECT_SIZE &&
redirect_limit < ZZ_THUMB_FULL_REDIRECT_SIZE) {
entry->try_near_jump = TRUE;
entry_backend->redirect_code_size = ZZ_THUMB_TINY_REDIRECT_SIZE;
} else if (redirect_limit != 0 && redirect_limit < ZZ_THUMB_TINY_REDIRECT_SIZE) {
return;
} else {
// put nop to align !!!!
entry_backend->redirect_code_size = ZZ_THUMB_FULL_REDIRECT_SIZE;
if (target_addr % 4) {
entry_backend->redirect_code_size += 2;
}
}
}
self->thumb_relocator.try_relocated_length = entry_backend->redirect_code_size;
} else {
if (entry->try_near_jump) {
entry_backend->redirect_code_size = ARM_TINY_REDIRECT_SIZE;
} else {
// check the first few instructions, preparatory work of instruction-fixing
arm_relocator_try_relocate((zz_ptr_t)target_addr, ARM_FULL_REDIRECT_SIZE, &redirect_limit);
if (redirect_limit != 0 && redirect_limit > ARM_TINY_REDIRECT_SIZE &&
redirect_limit < ARM_FULL_REDIRECT_SIZE) {
entry->try_near_jump = TRUE;
entry_backend->redirect_code_size = ARM_TINY_REDIRECT_SIZE;
} else if (redirect_limit != 0 && redirect_limit < ARM_TINY_REDIRECT_SIZE) {
return;
} else {
entry_backend->redirect_code_size = ARM_FULL_REDIRECT_SIZE;
}
}
self->arm_relocator.try_relocated_length = entry_backend->redirect_code_size;
}
// save original prologue
memcpy(entry->origin_prologue.data, (zz_ptr_t)target_addr, entry_backend->redirect_code_size);
entry->origin_prologue->size = entry_backend->redirect_code_size;
entry->origin_prologue.address = (zz_ptr_t)target_addr;
// relocator initialize
arm_relocator_init(&self->arm_relocator, &self->arm_reader, &self->arm_writer);
thumb_relocator_init(&self->thumb_relocator, &self->thumb_reader, &self->thumb_writer);
return;
}
void trampoline_build_for_enter_transfer(InterceptorBackend *self, hook_entry_t *entry) {
char temp_codeslice[256] = {0};
ARMAssemblerWriter *arm_writer = NULL;
ARMAssemblerWriter *thumb_writer = NULL;
CodeSlice *codeslice = NULL;
ARMHookEntryBackend *entry_backend = (ARMHookEntryBackend *)entry->backend;
RetStatus status = RS_SUCCESS;
bool is_thumb = TRUE;
zz_addr_t target_addr = (zz_addr_t)entry->target_ptr;
is_thumb = INSTRUCTION_IS_THUMB((zz_addr_t)entry->target_ptr);
if (is_thumb)
target_addr = THUMB_FUNCTION_ADDRESS(entry->target_ptr);
if (is_thumb) {
thumb_writer = &self->thumb_writer;
thumb_writer_reset(thumb_writer, ALIGN_CEIL(temp_codeslice, 4), 0);
if (entry->type == HOOK_TYPE_FUNCTION_via_REPLACE) {
thumb_writer_put_ldr_reg_address(thumb_writer, ARM_REG_PC, (zz_addr_t)entry->replace_call);
} else if (entry->type == HOOK_TYPE_INSTRUCTION_via_DBI) {
thumb_writer_put_ldr_reg_address(thumb_writer, ARM_REG_PC,
(zz_addr_t)entry->on_dynamic_binary_instrumentation_trampoline);
} else {
thumb_writer_put_ldr_reg_address(thumb_writer, ARM_REG_PC, (zz_addr_t)entry->on_enter_trampoline);
}
if (entry_backend->redirect_code_size == ZZ_THUMB_TINY_REDIRECT_SIZE) {
codeslice =
thumb_code_patch(thumb_writer, self->emm, target_addr, thumb_writer_near_jump_range_size() - 0x10);
} else {
codeslice = thumb_code_patch(thumb_writer, self->emm, 0, 0);
}
if (codeslice)
entry->on_enter_transfer_trampoline = codeslice->data + 1;
else
return;
} else {
arm_writer = &self->arm_writer;
arm_writer_reset(arm_writer, ALIGN_CEIL(temp_codeslice, 4), 0);
if (entry->type == HOOK_TYPE_FUNCTION_via_REPLACE) {
arm_writer_put_ldr_reg_address(arm_writer, ARM_REG_PC, (zz_addr_t)entry->replace_call);
} else if (entry->type == HOOK_TYPE_INSTRUCTION_via_DBI) {
arm_writer_put_ldr_reg_address(arm_writer, ARM_REG_PC,
(zz_addr_t)entry->on_dynamic_binary_instrumentation_trampoline);
} else {
arm_writer_put_ldr_reg_address(arm_writer, ARM_REG_PC, (zz_addr_t)entry->on_enter_trampoline);
}
if (entry_backend->redirect_code_size == ARM_TINY_REDIRECT_SIZE) {
codeslice = arm_code_patch(arm_writer, self->emm, target_addr, arm_writer_near_jump_range_size() - 0x10);
} else {
codeslice = arm_code_patch(arm_writer, self->emm, 0, 0);
}
if (codeslice)
entry->on_enter_transfer_trampoline = codeslice->data;
else
return;
}
// DELETE ?
#if 0
if (DebugLogControlerIsEnableLog()) {
char buffer[1024] = {};
sprintf(buffer + strlen(buffer), "\n======= EnterTransferTrampoline ======= \n");
sprintf(buffer + strlen(buffer), "\ton_enter_transfer_trampoline: %p\n", entry->on_enter_transfer_trampoline);
sprintf(buffer + strlen(buffer), "\ttrampoline_length: %ld\n", codeslice->size);
sprintf(buffer + strlen(buffer), "\thook_entry: %p\n", (void *)entry);
if (entry->type == HOOK_TYPE_FUNCTION_via_REPLACE) {
sprintf(buffer + strlen(buffer), "\tjump_target: replace_call(%p)\n", (void *)entry->replace_call);
} else if (entry->type == HOOK_TYPE_INSTRUCTION_via_DBI) {
sprintf(buffer + strlen(buffer), "\tjump_target: on_dynamic_binary_instrumentation_trampoline(%p)\n",
(void *)entry->on_dynamic_binary_instrumentation_trampoline);
} else {
sprintf(buffer + strlen(buffer), "\tjump_target: on_enter_trampoline(%p)\n",
(void *)entry->on_enter_trampoline);
}
DEBUGLOG_COMMON_LOG("%s", buffer);
}
#endif
free(codeslice);
return;
}
void trampoline_build_for_enter(InterceptorBackend *self, hook_entry_t *entry) {
ARMHookEntryBackend *entry_backend = (ARMHookEntryBackend *)entry->backend;
RetStatus status = RS_SUCCESS;
bool is_thumb;
is_thumb = INSTRUCTION_IS_THUMB((zz_addr_t)entry->target_ptr);
ClosureBridgeInfo *bridgeData;
bridgeData = ClosureBridgeAllocate(entry, context_begin_invocation_bridge_handler);
if (bridgeData == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_enter_trampoline = bridgeData->redirect_trampoline;
// build the double trampline aka enter_transfer_trampoline
if (entry_backend)
if ((is_thumb && entry_backend->redirect_code_size == ZZ_THUMB_TINY_REDIRECT_SIZE) ||
(!is_thumb && entry_backend->redirect_code_size == ARM_TINY_REDIRECT_SIZE)) {
if (entry->type != HOOK_TYPE_FUNCTION_via_GOT) {
trampoline_build_for_enter_transfer(self, entry);
}
}
// DELETE ?
#if 0
// debug log
if (DebugLogControlerIsEnableLog()) {
char buffer[1024] = {};
sprintf(buffer + strlen(buffer), "\n======= EnterTrampoline ======= \n");
sprintf(buffer + strlen(buffer), "\ton_enter_trampoline: %p\n", entry->on_enter_trampoline);
DEBUGLOG_COMMON_LOG("%s", buffer);
}
#endif
return;
}
void trampoline_build_for_dynamic_binary_instrumentation(InterceptorBackend *self, hook_entry_t *entry) {
ARMHookEntryBackend *entry_backend = (ARMHookEntryBackend *)entry->backend;
RetStatus status = RS_SUCCESS;
bool is_thumb;
is_thumb = INSTRUCTION_IS_THUMB((zz_addr_t)entry->target_ptr);
ClosureBridgeInfo *bridgeData;
bridgeData = ClosureBridgeAllocate(entry, context_begin_invocation_bridge_handler);
if (bridgeData == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_dynamic_binary_instrumentation_trampoline = bridgeData->redirect_trampoline;
// build the double trampline aka enter_transfer_trampoline
if ((is_thumb && entry_backend->redirect_code_size == ZZ_THUMB_TINY_REDIRECT_SIZE) ||
(!is_thumb && entry_backend->redirect_code_size == ARM_TINY_REDIRECT_SIZE)) {
if (entry->type != HOOK_TYPE_FUNCTION_via_GOT) {
trampoline_build_for_enter_transfer(self, entry);
}
}
// DELETE ?
#if 0
// debug log
if (DebugLogControlerIsEnableLog()) {
char buffer[1024] = {};
sprintf(buffer + strlen(buffer), "\n======= DynamicBinaryInstrumentationTrampoline ======= \n");
sprintf(buffer + strlen(buffer), "\tdynamic_binary_instrumentation_trampoline: %p\n",
entry->on_dynamic_binary_instrumentation_trampoline);
DEBUGLOG_COMMON_LOG("%s", buffer);
}
#endif
return;
}
void trampoline_build_for_invoke(InterceptorBackend *self, hook_entry_t *entry) {
char temp_codeslice[256] = {0};
CodeSlice *codeslice = NULL;
ARMHookEntryBackend *entry_backend = (ARMHookEntryBackend *)entry->backend;
RetStatus status = RS_SUCCESS;
bool is_thumb = TRUE;
zz_addr_t target_addr = (zz_addr_t)entry->target_ptr;
zz_ptr_t restore_next_insn_addr;
is_thumb = INSTRUCTION_IS_THUMB((zz_addr_t)entry->target_ptr);
if (is_thumb)
target_addr = THUMB_FUNCTION_ADDRESS(entry->target_ptr);
if (is_thumb) {
ThumbRelocator *thumb_relocator;
ThumbAssemblerWriter *thumb_writer;
ARMReader *thumb_reader;
thumb_relocator = &self->thumb_relocator;
thumb_writer = &self->thumb_writer;
thumb_reader = &self->thumb_reader;
thumb_writer_reset(thumb_writer, ALIGN_CEIL(temp_codeslice, 4), 0);
thumb_reader_reset(thumb_reader, (zz_ptr_t)target_addr);
thumb_relocator_reset(thumb_relocator, thumb_reader, thumb_writer);
{
do {
thumb_relocator_read_one(thumb_relocator, NULL);
} while (thumb_relocator->input->insns_size < entry_backend->redirect_code_size);
thumb_relocator_write_all(thumb_relocator);
}
// jump to rest function instructions address
restore_next_insn_addr = (zz_ptr_t)((zz_addr_t)target_addr + thumb_relocator->input->insns_size);
thumb_writer_put_ldr_reg_address(thumb_writer, ARM_REG_PC, (zz_addr_t)(restore_next_insn_addr + 1));
// code patch
codeslice = thumb_relocate_code_patch(thumb_relocator, thumb_writer, self->emm, 0, 0);
if (codeslice)
entry->on_invoke_trampoline = codeslice->data + 1;
else
return;
} else {
ARMRelocator *arm_relocator;
ARMAssemblerWriter *arm_writer;
ARMReader *arm_reader;
arm_relocator = &self->arm_relocator;
arm_writer = &self->arm_writer;
arm_reader = &self->arm_reader;
arm_writer_reset(arm_writer, ALIGN_CEIL(temp_codeslice, 4), 0);
arm_reader_reset(arm_reader, (zz_ptr_t)target_addr);
arm_relocator_reset(arm_relocator, arm_reader, arm_writer);
{
do {
arm_relocator_read_one(arm_relocator, NULL);
} while (arm_relocator->input->insns_size < entry_backend->redirect_code_size);
arm_relocator_write_all(arm_relocator);
}
// jump to rest target address
restore_next_insn_addr = (zz_ptr_t)((zz_addr_t)target_addr + arm_relocator->input->insns_size);
arm_writer_put_ldr_reg_address(arm_writer, ARM_REG_PC, (zz_addr_t)restore_next_insn_addr);
codeslice = arm_relocate_code_patch(arm_relocator, arm_writer, self->emm, 0, 0);
if (codeslice)
entry->on_invoke_trampoline = codeslice->data;
else
return;
}
// debug log
if (DebugLogControlerIsEnableLog()) {
char buffer[1024] = {};
char origin_prologue[256] = {0};
int t = 0;
sprintf(buffer + strlen(buffer), "======= Origin Code Relocator ======= \n");
if (is_thumb) {
for (int i = 0; i < self->thumb_relocator.input->insnCTXs_count; i++) {
sprintf(origin_prologue + t, "0x%.2x ", self->thumb_relocator.input->insnCTXs[i]->insn);
}
sprintf(buffer + strlen(buffer), "\t\tThumb Origin Prologue:: %s\n", origin_prologue);
sprintf(buffer + strlen(buffer), "\tThumb Relocator Input Start Address: %p\n",
(zz_ptr_t)self->thumb_relocator.input->insns_buffer);
sprintf(buffer + strlen(buffer), "\tThumb Relocator Input Instruction Number: %ld\n",
self->thumb_relocator.input->insnCTXs_count);
sprintf(buffer + strlen(buffer), "\tThumb Relocator Input Size: %p\n",
(zz_ptr_t)self->thumb_relocator.input->insns_size);
sprintf(buffer + strlen(buffer), "\tThumb Relocator Output Start Address: %p\n", codeslice->data);
sprintf(buffer + strlen(buffer), "\tThumb Relocator Output Instruction Number: %p\n",
(zz_ptr_t)self->thumb_relocator.input->insnCTXs_count);
sprintf(buffer + strlen(buffer), "\tThumb Relocator Output Size: %ld\n",
self->thumb_relocator.input->insns_size);
for (int i = 0; i < self->thumb_relocator.relocated_insnCTXs_count; i++) {
sprintf(buffer + strlen(buffer),
"\t\torigin input(%p) -> relocated ouput(%p), relocate %ld instruction\n",
(zz_ptr_t)self->thumb_relocator.relocator_insnCTXs[i].origin_insn->address,
(zz_ptr_t)self->thumb_relocator.relocator_insnCTXs[i].relocated_insnCTXs[0]->address,
self->thumb_relocator.relocator_insnCTXs[i].relocated_insnCTXs_count);
}
} else {
for (int i = 0; i < self->arm_relocator.input->insnCTXs_count; i++) {
sprintf(origin_prologue + t, "0x%.2x ", self->arm_relocator.input->insnCTXs[i]->insn);
}
sprintf(buffer + strlen(buffer), "\tARM Origin Prologue: %s\n", origin_prologue);
sprintf(buffer + strlen(buffer), "\tARM Relocator Input Start Address: %p\n",
(zz_ptr_t)self->arm_relocator.input->insns_buffer);
sprintf(buffer + strlen(buffer), "\tARM Relocator Input Instruction Number: %ld\n",
self->arm_relocator.input->insnCTXs_count);
sprintf(buffer + strlen(buffer), "\tARM Relocator Input Size: %p\n",
(zz_ptr_t)self->arm_relocator.input->insns_size);
sprintf(buffer + strlen(buffer), "\tARM Relocator Output Start Address: %p\n", codeslice->data);
sprintf(buffer + strlen(buffer), "\tARM Relocator Output Instruction Number: %p\n",
(zz_ptr_t)self->arm_relocator.input->insnCTXs_count);
sprintf(buffer + strlen(buffer), "\tARM Relocator Output Size: %ld\n",
self->arm_relocator.input->insns_size);
for (int i = 0; i < self->arm_relocator.relocated_insnCTXs_count; i++) {
sprintf(buffer + strlen(buffer),
"\t\torigin input(%p) -> relocated ouput(%p), relocate %ld instruction\n",
(zz_ptr_t)self->arm_relocator.relocator_insnCTXs[i].origin_insn->address,
(zz_ptr_t)self->arm_relocator.relocator_insnCTXs[i].relocated_insnCTXs[0]->address,
self->arm_relocator.relocator_insnCTXs[i].relocated_insnCTXs_count);
}
}
DEBUGLOG_COMMON_LOG("%s", buffer);
}
free(codeslice);
return;
}
void trampoline_build_for_leave(InterceptorBackend *self, hook_entry_t *entry) {
ClosureBridgeInfo *bridgeData;
bridgeData = ClosureBridgeAllocate(entry, context_end_invocation_bridge_handler);
if (bridgeData == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_leave_trampoline = bridgeData->redirect_trampoline;
// DELETE ?
#if 0
// debug log
if (DebugLogControlerIsEnableLog()) {
char buffer[1024] = {};
sprintf(buffer + strlen(buffer), "\n======= LeaveTrampoline ======= \n");
sprintf(buffer + strlen(buffer), "\ton_leave_trampoline: %p\n", entry->on_leave_trampoline);
DEBUGLOG_COMMON_LOG("%s", buffer);
}
#endif
return;
}
void trampoline_active(InterceptorBackend *self, hook_entry_t *entry) {
char temp_codeslice[256] = {0};
CodeSlice *codeslice = NULL;
ARMHookEntryBackend *entry_backend = (ARMHookEntryBackend *)entry->backend;
RetStatus status = RS_SUCCESS;
bool is_thumb = TRUE;
zz_addr_t target_addr = (zz_addr_t)entry->target_ptr;
is_thumb = INSTRUCTION_IS_THUMB((zz_addr_t)entry->target_ptr);
if (is_thumb)
target_addr = THUMB_FUNCTION_ADDRESS(entry->target_ptr);
if (is_thumb) {
ThumbAssemblerWriter *thumb_writer;
thumb_writer = &self->thumb_writer;
thumb_writer_reset(thumb_writer, ALIGN_CEIL(temp_codeslice, 4), target_addr);
if (entry->type == HOOK_TYPE_FUNCTION_via_REPLACE) {
if (entry_backend->redirect_code_size == ZZ_THUMB_TINY_REDIRECT_SIZE) {
thumb_writer_put_b_imm32(thumb_writer, THUMB_FUNCTION_ADDRESS(entry->on_enter_transfer_trampoline) -
(zz_addr_t)thumb_writer->start_pc);
} else {
// target address is not aligne 4, need align
if ((target_addr % 4) && entry_backend->redirect_code_size == (ZZ_THUMB_FULL_REDIRECT_SIZE + 2))
thumb_writer_put_nop(thumb_writer);
thumb_writer_put_ldr_reg_address(thumb_writer, ARM_REG_PC,
(zz_addr_t)entry->on_enter_transfer_trampoline);
}
} else {
if (entry_backend->redirect_code_size == ZZ_THUMB_TINY_REDIRECT_SIZE) {
thumb_writer_put_b_imm32(thumb_writer, THUMB_FUNCTION_ADDRESS(entry->on_enter_transfer_trampoline) -
(zz_addr_t)thumb_writer->start_pc);
} else {
// target address is not aligne 4, need align
if ((target_addr % 4) && entry_backend->redirect_code_size == (ZZ_THUMB_FULL_REDIRECT_SIZE + 2))
thumb_writer_put_nop(thumb_writer);
thumb_writer_put_ldr_reg_address(thumb_writer, ARM_REG_PC, (zz_addr_t)entry->on_enter_trampoline);
}
}
if (!MemoryHelperPatchCode((zz_addr_t)target_addr, (zz_ptr_t)thumb_writer->insns_buffer,
thumb_writer->insns_size))
return;
// thumb_writer_free(thumb_writer);
} else {
ARMAssemblerWriter *arm_writer;
arm_writer = &self->arm_writer;
arm_writer_reset(arm_writer, ALIGN_CEIL(temp_codeslice, 4), target_addr);
if (entry->type == HOOK_TYPE_FUNCTION_via_REPLACE) {
if (entry_backend->redirect_code_size == ARM_TINY_REDIRECT_SIZE) {
arm_writer_put_b_imm(arm_writer,
(zz_addr_t)entry->on_enter_transfer_trampoline - (zz_addr_t)arm_writer->start_pc);
} else {
arm_writer_put_ldr_reg_address(arm_writer, ARM_REG_PC, (zz_addr_t)entry->on_enter_transfer_trampoline);
}
} else {
if (entry_backend->redirect_code_size == ARM_TINY_REDIRECT_SIZE) {
arm_writer_put_b_imm(arm_writer,
(zz_addr_t)entry->on_enter_transfer_trampoline - (zz_addr_t)arm_writer->start_pc);
} else {
arm_writer_put_ldr_reg_address(arm_writer, ARM_REG_PC, (zz_addr_t)entry->on_enter_trampoline);
}
}
if (!MemoryHelperPatchCode((zz_addr_t)target_addr, (zz_ptr_t)arm_writer->insns_buffer, arm_writer->insns_size))
return;
// arm_writer_free(arm_writer);
}
// debug log
if (DebugLogControlerIsEnableLog()) {
char buffer[1024] = {};
sprintf(buffer + strlen(buffer), "======= Trampoline Summary ======= \n");
sprintf(buffer + strlen(buffer), "\tHookZz Target Address: %p\n", entry->target_ptr);
if (is_thumb) {
sprintf(buffer + strlen(buffer), "\tHookZz Target Address Arch Mode: Thumb\n");
if (entry_backend->redirect_code_size == ZZ_THUMB_TINY_REDIRECT_SIZE) {
sprintf(buffer + strlen(buffer), "\tThumb Brach Jump Type: Near Jump(B xxx)\n");
} else if (entry_backend->redirect_code_size == ZZ_THUMB_FULL_REDIRECT_SIZE) {
sprintf(buffer + strlen(buffer), "\tThumb Brach Jump Type: Abs Jump(ldr pc, [pc, #x])\n");
} else if ((((zz_addr_t)entry->target_ptr) % 4) &&
entry_backend->redirect_code_size == (ZZ_THUMB_FULL_REDIRECT_SIZE + 2)) {
sprintf(buffer + strlen(buffer), "\tThumb Brach Jump Type: Align Abs Jump(nop; ldr pc, [pc, #x])\n");
}
} else {
sprintf(buffer + strlen(buffer), "\tHookZz Target Address Arch Mode: ARM\n");
if (entry_backend->redirect_code_size == ARM_TINY_REDIRECT_SIZE) {
sprintf(buffer + strlen(buffer), "\tARM Jump Type: Near Jump(B xxx)\n");
} else if (entry_backend->redirect_code_size == ARM_FULL_REDIRECT_SIZE) {
sprintf(buffer + strlen(buffer), "\tARM Brach Jump Type: Abs Jump(ldr pc, [pc, #-4])\n");
}
}
if (entry->try_near_jump && entry->on_enter_transfer_trampoline)
sprintf(buffer + strlen(buffer), "\ton_enter_transfer_trampoline: %p\n",
entry->on_enter_transfer_trampoline);
if (entry->type == HOOK_TYPE_INSTRUCTION_via_DBI) {
sprintf(buffer + strlen(buffer), "\tHook Type: HOOK_TYPE_INSTRUCTION_via_DBI\n");
sprintf(buffer + strlen(buffer), "\ton_dynamic_binary_instrumentation_trampoline: %p\n",
entry->on_dynamic_binary_instrumentation_trampoline);
sprintf(buffer + strlen(buffer), "\ton_invoke_trampoline: %p\n", entry->on_invoke_trampoline);
} else if (entry->type == HOOK_TYPE_FUNCTION_via_PRE_POST) {
sprintf(buffer + strlen(buffer), "\tHook Type: HOOK_TYPE_FUNCTION_via_PRE_POST\n");
sprintf(buffer + strlen(buffer), "\ton_enter_trampoline: %p\n", entry->on_enter_trampoline);
sprintf(buffer + strlen(buffer), "\ton_leave_trampoline: %p\n", entry->on_leave_trampoline);
sprintf(buffer + strlen(buffer), "\ton_invoke_trampoline: %p\n", entry->on_invoke_trampoline);
} else if (entry->type == HOOK_TYPE_FUNCTION_via_REPLACE) {
sprintf(buffer + strlen(buffer), "\tHook Type: HOOK_TYPE_FUNCTION_via_REPLACE\n");
sprintf(buffer + strlen(buffer), "\ton_enter_transfer_trampoline: %p\n",
entry->on_enter_transfer_trampoline);
sprintf(buffer + strlen(buffer), "\ton_invoke_trampoline: %p\n", entry->on_invoke_trampoline);
} else if (entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
sprintf(buffer + strlen(buffer), "\tHook Type: HOOK_TYPE_FUNCTION_via_GOT\n");
sprintf(buffer + strlen(buffer), "\ton_enter_trampoline: %p\n", entry->on_enter_trampoline);
sprintf(buffer + strlen(buffer), "\ton_leave_trampoline: %p\n", entry->on_leave_trampoline);
}
DEBUGLOG_COMMON_LOG("%s", buffer);
}
return;
}
|
ZJNixiang/HookZz
|
src/closure_bridge.h
|
<reponame>ZJNixiang/HookZz<filename>src/closure_bridge.h
#ifndef closure_bridge_h
#define closure_bridge_h
#include "core.h"
#include "hookzz.h"
#include "std_kit/std_list.h"
#include <stdint.h>
#define PRIVATE
// closure bridge
typedef struct _ClosureBridgeInfo {
void *user_code;
void *user_data;
void *redirect_trampoline;
} ClosureBridgeInfo;
typedef struct _ClosureBridgeTrampolineTable {
void *entry;
void *trampoline_page;
uint16_t used_count;
uint16_t free_count;
} ClosureBridgeTrampolineTable;
typedef struct _ClosureBridge {
list_t *bridge_infos;
list_t *trampoline_tables;
} ClosureBridge;
#define ClosureBridgeCClass(member) cxxclass(ClosureBridge, member)
ClosureBridge *ClosureBridgeCClass(SharedInstance)();
ClosureBridgeInfo *ClosureBridgeCClass(AllocateClosureBridge)(ClosureBridge *self, void *user_data, void *user_code);
ClosureBridgeTrampolineTable *ClosureBridgeCClass(AllocateClosureBridgeTrampolineTable)(ClosureBridge *self);
ARCH_API void ClosureBridgeCClass(InitializeTablePage)(ClosureBridgeTrampolineTable *table, void *page_address);
ARCH_API void ClosureBridgeCClass(InitializeClosureBridgeInfo)(ClosureBridgeTrampolineTable *table,
ClosureBridgeInfo *cb_info, void *user_data,
void *user_code);
typedef void (*USER_CODE_CALL)(RegState *rs, ClosureBridgeInfo *cb_info);
#if DYNAMIC_CLOSURE_BRIDGE
// dynamic closure bridge
typedef struct _DynamicClosureBridgeInfo {
void *trampolineTo PRIVATE;
void *user_code;
void *user_data;
void *redirect_trampoline;
} DynamicClosureBridgeInfo;
typedef struct _DynamicClosureTrampolineTable {
void *entry;
void *trampoline_page;
void *data_page;
uint16_t used_count;
uint16_t free_count;
} DynamicClosureBridgeTrampolineTable;
typedef struct _DynamicClosureBridge {
list_t *dynamic_bridge_infos;
list_t *dynamic_trampoline_tables;
} DynamicClosureBridge;
#define DynamicClosureBridgeCClass(member) cclass(DynamicClosureBridge, member)
DynamicClosureBridge *DynamicClosureBridgeCClass(SharedInstance)();
DynamicClosureBridgeInfo *DynamicClosureBridgeCClass(AllocateDynamicClosureBridge)(DynamicClosureBridge *self,
void *user_data, void *user_code);
DynamicClosureBridgeTrampolineTable *
DynamicClosureBridgeCClass(AllocateDynamicClosureBridgeTrampolineTable)(DynamicClosureBridge *self);
typedef void (*DYNAMIC_USER_CODE_CALL)(RegState *rs, DynamicClosureBridgeInfo *dcb_info);
#endif
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
void closure_bridge_trampoline_template();
void closure_bridge_template();
#if DYNAMIC_CLOSURE_BRIDGE
void dynamic_closure_bridge_template();
void dynamic_closure_trampoline_table_page();
#endif
#ifdef __cplusplus
}
#endif //__cplusplus
#endif
|
ZJNixiang/HookZz
|
src/thread_support/thread_local_storage.h
|
#ifndef thread_local_storage_h
#define thread_local_storage_h
#include "core.h"
#include "hookzz.h"
void *get_thread_variable_value();
void set_thread_variable_value(void *value);
#endif
|
ZJNixiang/HookZz
|
src/hookzz.c
|
<gh_stars>1-10
#include "hookzz.h"
#include "core.h"
#include "hookzz_internal.h"
#include "interceptor.h"
#include "interceptor_routing_trampoline.h"
#include "std_kit/std_kit.h"
bool g_near_jump_flag = false;
void zz_enable_near_jump() { g_near_jump_flag = true; }
bool zz_is_near_jump() { return g_near_jump_flag; }
void zz_disable_near_jump() { g_near_jump_flag = false; }
static void initialize_hook_entry(hook_entry_t *entry) {
if (zz_is_near_jump()) {
entry->is_try_near_jump = true;
}
interceptor_t *interceptor = interceptor_cclass(shared_instance)();
interceptor_cclass(add_hook_entry)(interceptor, entry);
interceptor_trampoline_cclass(build_all)(entry);
interceptor_trampoline_cclass(active)(entry);
}
RetStatus ZzWrap(void *function_address, PRECALL pre_call, POSTCALL post_call) {
hook_entry_t *entry = SAFE_MALLOC_TYPE(hook_entry_t);
entry->id = (uintptr_t)entry;
entry->target_address = function_address;
entry->type = HOOK_TYPE_FUNCTION_via_PRE_POST;
entry->pre_call = pre_call;
entry->post_call = post_call;
Logging("[*] prepare ZzWrap hook %p", function_address);
initialize_hook_entry(entry);
return RS_SUCCESS;
}
RetStatus ZzReplace(void *function_address, void *replace_call, void **origin_call) {
hook_entry_t *entry = SAFE_MALLOC_TYPE(hook_entry_t);
entry->id = (uintptr_t)entry;
entry->target_address = function_address;
entry->type = HOOK_TYPE_FUNCTION_via_REPLACE;
entry->replace_call = replace_call;
Logging("[*] prepare ZzReplace hook %p", function_address);
initialize_hook_entry(entry);
*origin_call = entry->on_invoke_trampoline;
return RS_SUCCESS;
}
RetStatus ZzDynamicBinaryInstrumentation(void *inst_address, DBICALL dbi_call) {
hook_entry_t *entry = SAFE_MALLOC_TYPE(hook_entry_t);
entry->id = (uintptr_t)entry;
entry->target_address = inst_address;
entry->type = HOOK_TYPE_INSTRUCTION_via_DBI;
entry->dbi_call = dbi_call;
Logging("[*] prepare ZzDynamicBinaryInstrumentation hook %p", inst_address);
initialize_hook_entry(entry);
return RS_SUCCESS;
}
|
ZJNixiang/HookZz
|
src/thread_support/thread_local_storage.c
|
#include "thread_local_storage.h"
#ifdef thread_local
thread_local void *_thread_variable;
void *get_thread_variable_value() { return _thread_variable; }
void set_thread_variable_value(void *value) { _thread_variable = value; }
#endif
|
ZJNixiang/HookZz
|
include/hookzz.h
|
#ifndef hookzz_h
#define hookzz_h
// clang-format off
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
#include <stdbool.h>
#include <stdint.h>
typedef uintptr_t zz_addr_t;
typedef void * zz_ptr_t;
#ifndef REGISTER_STATE_STRUCT
#define REGISTER_STATE_STRUCT
#if defined(__arm64__) || defined(__aarch64__)
#define Tx(type) type##arm64
#define TX() type##ARM64
#define xT() arm64##type
#define XT() ARM64##type
typedef union _FPReg {
__int128_t q;
struct {
double d1;
double d2;
} d;
struct {
float f1;
float f2;
float f3;
float f4;
} f;
} FPReg;
typedef struct _RegState {
uint64_t dmmpy_0;
union {
uint64_t x[29];
struct {
uint64_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21,
x22, x23, x24, x25, x26, x27, x28;
} regs;
} general;
uint64_t fp;
uint64_t lr;
union {
FPReg q[8];
struct {
FPReg q0, q1, q2, q3, q4, q5, q6, q7;
} regs;
} floating;
} RegState;
#elif defined(__arm__)
#define Tx(type) type##arm
#define TX() type##ARM
#define xT() arm##type
#define XT() ARM##type
typedef struct _RegState {
uint32_t dummy_0;
uint32_t dummy_1;
union {
uint32_t r[13];
struct {
uint32_t r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12;
} regs;
} general;
uint32_t lr;
} RegState;
#elif defined(__i386__)
#define Tx(type) type##arm
#define TX() type##ARM
#define xT() arm##type
#define XT() ARM##type
typedef struct _RegState {
} RegState;
#elif defined(__x86_64__)
#define Tx(type) type##x64
#define TX() type##X64
#define xT() x64##type
#define XT() X64##type
typedef struct _RegState {
} RegState;
#endif
#define REG_SP(rs) (void *)((uintptr_t)rs + sizeof(RegState))
#endif
typedef enum _RetStatus {
RS_UNKOWN = -1,
RS_DONE = 0,
RS_SUCCESS,
RS_FAILED
} RetStatus;
typedef enum _HookType {
// HOOK_TYPE_SINGLE_INSTRUCTION_DELETED = 0,
HOOK_TYPE_FUNCTION_via_PRE_POST = 0,
HOOK_TYPE_FUNCTION_via_REPLACE,
HOOK_TYPE_FUNCTION_via_GOT,
HOOK_TYPE_INSTRUCTION_via_DBI
}HookType;
typedef struct _CallStackPublic {
uintptr_t call_id;
} CallStackPublic;
typedef struct _ThreadStackPublic {
uintptr_t thread_id;
unsigned long call_stack_count;
} ThreadStackPublic;
typedef struct _HookEntryInfo {
uintptr_t hook_id;
void *target_address;
} HookEntryInfo;
typedef void (*PRECALL)(RegState *rs, ThreadStackPublic *tsp, CallStackPublic *csp, const HookEntryInfo *info);
typedef void (*POSTCALL)(RegState *rs, ThreadStackPublic *tsp, CallStackPublic *csp, const HookEntryInfo *info);
typedef void (*DBICALL)(RegState *rs, const HookEntryInfo *info);
void call_stack_kv_set(CallStackPublic *csp, char *key, void *value);
void *call_stack_kv_get(CallStackPublic *csp, char *key);
// open near jump, use code cave & b xxx
void zz_enable_near_jump();
// close near jump, use `ldr x17, #0x8; br x17; .long 0x0; .long 0x0`
void zz_disable_near_jump();
// use pre_call and post_call wrap a function
RetStatus ZzWrap(void *function_address, PRECALL pre_call, POSTCALL post_call);
// use inline hook to replace function
RetStatus ZzReplace(void *function_address, void *replace_call, void **origin_call);
// use pre_call and post_call wrap a GOT(imported) function
RetStatus ZzWrapGOT(void *image_header, char *image_name, char *function_name, PRECALL pre_call, POSTCALL post_call);
// replace got
RetStatus ZzReplaceGOT(void *image_header, char *image_name, char *function_name, void *replace_call, void **origin_call);
// hook instruction with DBI
RetStatus ZzDynamicBinaryInstrumentation(void *inst_address, DBICALL dbi_call);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif
|
ZJNixiang/HookZz
|
src/std_kit/std_buffer_array.h
|
<gh_stars>1-10
#ifndef std_buffer_array_h
#define std_buffer_array_h
#include <stdlib.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _buffer_array_t {
void *data;
int size;
int capacity;
} buffer_array_t;
buffer_array_t *buffer_array_create(int default_capacity);
void buffer_array_put(buffer_array_t *self, void *data, int length);
void buffer_array_clear(buffer_array_t *self);
void buffer_array_destory(buffer_array_t *self);
#ifdef __cplusplus
}
#endif
#endif
|
ZJNixiang/HookZz
|
src/platforms/backend-darwin/memory-helper-darwin.h
|
#ifndef platforms_backend_darwin_memory_helper_darwin_h
#define platforms_backend_darwin_memory_helper_darwin_h
#include "core.h"
#include "hookzz.h"
#include "memory_manager.h"
#include "std_kit/std_kit.h"
#include "mach_vm.h"
#include <mach-o/dyld.h>
#include <mach/mach.h>
#include <mach/vm_map.h>
#include <sys/mman.h>
#define darwin_memory_helper_cclass(member) cclass(darwin_memory_helper, member)
int darwin_memory_helper_cclass(get_page_size)();
void darwin_memory_helper_cclass(get_memory_info)(void *address, vm_prot_t *prot, vm_inherit_t *inherit);
void darwin_memory_helper_cclass(set_page_permission)(void *address, int prot, int n);
#endif
|
ZJNixiang/HookZz
|
src/std_kit/std_buffer_array.c
|
#include "std_buffer_array.h"
buffer_array_t *buffer_array_create(int default_capacity) {
if (default_capacity == 0) {
default_capacity = 64;
}
unsigned char *data = (unsigned char *)malloc(default_capacity);
buffer_array_t *buffer_array = (buffer_array_t *)malloc(sizeof(buffer_array_t));
if (!buffer_array) {
return NULL;
}
buffer_array->data = data;
buffer_array->size = 0;
buffer_array->capacity = default_capacity;
return buffer_array;
}
void buffer_array_put(buffer_array_t *self, void *data, int length) {
if (self->size + length > self->capacity) {
unsigned char *data = (unsigned char *)realloc(self->data, self->capacity * 2);
if (!data) {
return;
}
self->capacity = self->capacity * 2;
self->data = data;
}
memcpy(self->data + self->size, data, length);
self->size += length;
}
void buffer_array_clear(buffer_array_t *self) {
self->size = 0;
memset(self->data, 0, self->capacity);
return;
}
void buffer_array_destory(buffer_array_t *self) {
free(self->data);
self->data = NULL;
free(self);
return;
}
|
ZJNixiang/HookZz
|
src/hookzz_internal.h
|
<filename>src/hookzz_internal.h<gh_stars>1-10
#ifndef hookzz_internal_h
#define hookzz_internal_h
#include "core.h"
#include "hookzz.h"
bool zz_is_near_jump();
#endif
|
GDXRepo/AHLaunchCtl
|
AHLaunchCtl/AHLaunchJob.h
|
// AHLaunchJob.h
// Copyright (c) 2014 <NAME> ( https://github.com/eahrold/AHLaunchCtl )
//
// 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.
#import <Foundation/Foundation.h>
#import <AHLaunchCtl/AHLaunchJobSchedule.h>
/**
* AHLaunchDomain Launch Domain specifying which context the job should run
* under and where the launchd.plist file is located
*/
typedef NS_ENUM(NSInteger, AHLaunchDomain) {
/**
* User Launch Agents ~/Library/LaunchAgents. Loaded by the Console user.
*/
kAHUserLaunchAgent = 1,
/**
* Administrator provided LaunchAgents /Library/LaunchAgents/. Loaded by
* the console user
*/
kAHGlobalLaunchAgent,
/**
* Apple provided LaunchAgents /System/Library/LaunchAgents/. Loaded by
* root user
*/
kAHSystemLaunchAgent,
/**
* Administrator provided LaunchDaemon /Library/LaunchDaemons/. Loaded by
* root user
*/
kAHGlobalLaunchDaemon,
/**
* Apple provided LaunchDaemon /System/Library/LaunchDaemons/. Loaded by
* root user.
*/
kAHSystemLaunchDaemon,
};
/**
* Job Object to loaded by AHLaunchCtl. Conforms to the keys of launchd.plist.
* See the Apple documentation for more info
*/
@interface AHLaunchJob : NSObject
/**
* Label
*/
@property (copy, nonatomic) NSString *Label;
/**
* Disabled
*/
@property (nonatomic) BOOL Disabled;
#pragma mark -
/**
* Program
*/
@property (copy, nonatomic) NSString *Program;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSArray *ProgramArguments;
/**
* see man launchd.plist
*/
@property (nonatomic) NSInteger StartInterval;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *ServiceDescription;
#pragma mark -
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *UserName;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *GroupName;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSDictionary *inetdCompatibility;
#pragma mark -
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSArray *LimitLoadToHosts;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSArray *LimitLoadFromHosts;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *LimitLoadToSessionType;
#pragma mark -
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL EnableGlobbing;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL EnableTransactions;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL BeginTransactionAtShutdown;
#pragma mark -
/**
* KeepAlive dictionary or Number use @YES and @NO
*/
@property (nonatomic) id KeepAlive;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL OnDemand;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL RunAtLoad;
#pragma mark -
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *RootDirectory;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *WorkingDirectory;
#pragma mark -
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSDictionary *EnvironmentVariables;
/**
* see man launchd.plist
*/
@property (nonatomic) NSInteger Umask;
/**
* see man launchd.plist
*/
@property (nonatomic) NSInteger TimeOut;
/**
* see man launchd.plist
*/
@property (nonatomic) NSInteger ExitTimeOut;
/**
* see man launchd.plist
*/
@property (nonatomic) NSInteger ThrottleInterval;
#pragma mark -
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL InitGroups;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSArray *WatchPaths;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSArray *QueueDirectories;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL StartOnMount;
#pragma mark - Schedule
/**
* StartCalendarInterval AHLaunchJobSchedule of integers or array of
* AHLaunchJobSchedules
*/
@property (copy, nonatomic) id StartCalendarInterval;
/**
* Array Of AHLaunchJobSchedule for scheduling multiple runs with the same
* Launch Job
*/
@property (copy, nonatomic) NSArray *StartCalendarIntervalArray __deprecated_msg("Use StartCalendarInterval instead.");
#pragma mark - In/Out
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *StandardInPath;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *StandardOutPath;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *StandardErrorPath;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL Debug;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL WaitForDebugger;
#pragma mark -
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSDictionary *SoftResourceLimits;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSDictionary *HardResourceLimits;
#pragma mark -
/**
* see man launchd.plist
*/
@property (nonatomic) NSInteger Nice;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *ProcessType;
#pragma mark -
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL AbandonProcessGroup;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL LowPriorityIO;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL LowPriorityBackgroundIO;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL LaunchOnlyOnce;
#pragma mark -
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSDictionary *MachServices;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSDictionary *Sockets;
#pragma mark - Specialized / Undocumented Apple Keys
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSDictionary *LaunchEvents;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSDictionary *PerJobMachServices;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *MachExceptionHandler;
#pragma mark -
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *POSIXSpawnType;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *PosixSpawnType;
#pragma mark -
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL ServiceIPC;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL XPCDomainBootstrapper;
#pragma mark -
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *CFBundleIdentifier;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSString *SHAuthorizationRight;
#pragma mark -
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSDictionary *JetsamProperties;
/**
* see man launchd.plist
*/
@property (copy, nonatomic) NSArray *BinaryOrderPreference;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL SessionCreate;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL MultipleInstances;
#pragma mark -
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL HopefullyExitsLast;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL ShutdownMonitor;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL EventMonitor;
/**
* see man launchd.plist
*/
@property (nonatomic) BOOL IgnoreProcessGroupAtShutdown;
#pragma mark - Read only properties...
/**
* Associated Launch Domain
*/
@property (nonatomic, readonly) AHLaunchDomain domain;
/**
* Process ID for the managed executable
*/
@property (nonatomic, readonly) NSInteger PID;
/**
* Last exit status of the managed executable
*/
@property (nonatomic, readonly) NSInteger LastExitStatus;
/**
* wether or not the current job is loaded
*/
@property (nonatomic, readonly) BOOL isCurrentlyLoaded;
#pragma mark;
/**
* The dictionary value of the Launch Job.
*
* @return The dictionary that will be submitted to launchd
*/
- (NSDictionary *)dictionary;
/**
* The version number of the executable if it was compiled with an embedded
* Info.plist This is primarily used for determining the version on a
* privileged helper application
*
* @return Version String Value
*/
- (NSString *)executableVersion;
#pragma mark - Class Methods
/**
* Create a job from a dictionary
*
* @param dict dictionary with KVC attributes
*
* @return allocated AHLaunchJob with corresponding keys
*/
+ (AHLaunchJob *)jobFromDictionary:(NSDictionary *)dict
inDomain:(AHLaunchDomain)domain;
/**
* Create a job from a launchd.plist
*
* @param file path to launchd.plist
*
* @return allocated AHLaunchJob with corresponding keys
*/
+ (AHLaunchJob *)jobFromFile:(NSString *)file;
@end
|
GDXRepo/AHLaunchCtl
|
AHLaunchCtl/AHLaunchCtl.h
|
// AHLaunchCtl.h
//
// Copyright (c) 2014 <NAME> ( https://github.com/eahrold/AHLaunchCtl )
//
// 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.
#import <Foundation/Foundation.h>
#import <AHLaunchCtl/AHLaunchJob.h>
/**
* AHLaunchCtlErrorCodes
*/
typedef NS_ENUM(NSInteger, AHLaunchCtlErrorCodes) {
/**
* No Error
*/
kAHErrorSuccess,
/**
* Error encountered when job label that is not in dot syntax or has spaces
*/
kAHErrorJobLabelNotValid,
/**
* job requires Label and Program Arguments
*/
kAHErrorJobMissingRequiredKeys,
/**
* Error encountered when job is not Loaded
*/
kAHErrorJobNotLoaded,
/**
* Error encountered when job already exists
*/
kAHErrorJobAlreadyExists,
/**
* Error Encountered when job already loaded
*/
kAHErrorJobAlreadyLoaded,
/**
* Error Encountered when trying to load a job
*/
kAHErrorCouldNotLoadJob,
/**
* Error Encountered when trying to load a helper tool
*/
kAHErrorCouldNotLoadHelperTool,
/**
* Error Encountered when trying a helper tool could not be removed
*/
kAHErrorCouldNotUnloadHelperTool,
/**
* Error Encountered when trying a helper tool could not be removed
*/
kAHErrorHelperToolNotLoaded,
/**
* Error Encountered when files associated with helper tool could not be
* removed
*/
kAHErrorCouldNotRemoveHelperToolFiles,
/**
* Error Encountered when a job could not be unloaded
*/
kAHErrorCouldNotUnloadJob,
/**
* Error Encountered when a job could not be reloaded
*/
kAHErrorJobCouldNotReload,
/**
* Error Encountered when the launchd.plist file could not be located
*/
kAHErrorFileNotFound,
/**
* Error Encountered when the launchd.plist is actually a directory not a file
*/
kAHErrorFileIsDirectory,
/**
* Error Encountered when the launchd.plist file could not be written or
* insufficient privileges
*/
kAHErrorCouldNotWriteFile,
/**
* Error Encountered when more than one job with the same label exist
*/
kAHErrorMultipleJobsMatching,
/**
* Error Encountered when user is not privileged to install into domain
*/
kAHErrorInsufficientPrivileges,
/**
* Error Encountered when a user is trying to unload another's launch job
*/
kAHErrorExecutingAsIncorrectUser,
/**
* Error Encountered when the program to be loaded is not executable
*/
kAHErrorProgramNotExecutable,
/**
* User Canceled authorization.
*/
kAHErrorUserCanceledAuthorization = errAuthorizationCanceled,
};
/**
* Objective-C Framework For LaunchAgents and LaunchDaemons
*/
@interface AHLaunchCtl : NSObject
/**
* Singleton Object to handle AHLaunchJobs
*
* @return Shared Controller
*/
+ (AHLaunchCtl *)sharedController;
#pragma mark - Public Methods
/**
* Create session wide authorization linked to the controller.
*
* @param prompt String to display for the Authorization creation dialog.
*
* @return Returns `YES` on success, or `NO` on failure.
*/
- (BOOL) authorizeWithPrompt:(NSString *)prompt;
- (BOOL) authorize;
/**
* Deauthorize the session.
* @note This is called when the controller is deallocated.
*/
- (void)deauthorize;
/**
* Write the launchd.plist and load the job into context
*
* @param job AHLaunchJob with desired keys.
* @param domain Corresponding AHLaunchDomain.
* @param error Populated should an error occur.
*
* @return Returns `YES` on success, or `NO` on failure.
*/
- (BOOL)add:(AHLaunchJob *)job
toDomain:(AHLaunchDomain)domain
error:(NSError **)error;
/**
* Remove launchd.plist and unload the job
*
* @param label Name of the running launchctl job.
* @param domain Corresponding AHLaunchDomain
* @param error Populated should an error occur.
*
* @return Returns `YES` on success, or `NO` on failure.
*/
- (BOOL)remove:(NSString *)label
fromDomain:(AHLaunchDomain)domain
error:(NSError **)error;
/**
* Loads launchd job (will not write file)
*
* @param job AHLaunchJob Object, Label and Program keys required.
* @param domain Corresponding AHLaunchDomain
* @param error Populated should an error occur.
*
* @return Returns `YES` on success, or `NO` on failure.
*/
- (BOOL)load:(AHLaunchJob *)job
inDomain:(AHLaunchDomain)domain
error:(NSError **)error;
/**
* Unloads a launchd job (will not remove file)
*
* @param label Name of the running launchctl job.
* @param domain Corresponding AHLaunchDomain
* @param error Populated should an error occur.
*
* @return Returns `YES` on success, or `NO` on failure.
*/
- (BOOL)unload:(NSString *)label
inDomain:(AHLaunchDomain)domain
error:(NSError **)error;
/**
* Loads and existing launchd.plist
*
* @param label Name of the launchctl file.
* @param domain Corresponding AHLaunchDomain
* @param error Populated should an error occur.
*
* @return Returns `YES` on success, or `NO` on failure.
*/
- (BOOL)start:(NSString *)label
inDomain:(AHLaunchDomain)domain
error:(NSError **)error;
/**
* Stops a running launchd job, synonomus with unload
*
* @param label Name of the running launchctl job.
* @param error Populated should an error occur.
* @param domain Corresponding AHLaunchDomain
*
* @return Returns `YES` on success, or `NO` on failure.
*/
- (BOOL)stop:(NSString *)label
inDomain:(AHLaunchDomain)domain
error:(NSError **)error;
/**
* Restarts a launchd job with an existsing launchd.plist file.
*
* @param label Name of the running launchctl job.
* @param domain Corresponding AHLaunchDomain
* @param error Populated should an error occur.
*
* @return Returns `YES` on success, or `NO` on failure.
*/
- (BOOL)restart:(NSString *)label
inDomain:(AHLaunchDomain)domain
error:(NSError **)error;
#pragma mark - Class Methods
/**
* Launch an application at login.
*
* @param app Path to the Application
* @param launch YES to launch, NO to stop launching
* @param global YES to launch for all users, NO to launch for current user.
* @param keepAlive YES to relaunch in the event of a crash or an attempt to quit
* @param error Populated should an error occur.
*
* @return Returns `YES` on success, or `NO` on failure.
*/
+ (BOOL)launchAtLogin:(NSString *)app
launch:(BOOL)launch
global:(BOOL)global
keepAlive:(BOOL)keepAlive
error:(NSError **)error;
/**
* Schedule a LaunchD Job to run at an interval.
*
* @param label uniquely identifier for launchd. This should be in the form of a reverse domain
* @param program Path to the executable to run
* @param interval How often (in seconds) to run.
* @param domain Corresponding AHLaunchDomain
* @param reply Reply block executed on completion that has no return value and
*takes on argument NSError.
*/
+ (void)scheduleJob:(NSString *)label
program:(NSString *)program
interval:(int)interval
domain:(AHLaunchDomain)domain
reply:(void (^)(NSError *error))reply;
/**
* Schedule a LaunchD Job to run at an interval.
*
* @param label uniquely identifier for launchd. This should be in the form of a reverse domain
* @param program Path to the executable to run
* @param programArguments Array of arguments to pass to the executable.
* @param interval How often (in seconds) to run.
* @param domain Corresponding AHLaunchDomain
* @param reply Reply block executed on completion that has no return value and
*takes on argument NSError.
*/
+ (void)scheduleJob:(NSString *)label
program:(NSString *)program
programArguments:(NSArray *)programArguments
interval:(int)interval
domain:(AHLaunchDomain)domain
reply:(void (^)(NSError *error))reply;
/**
* Create a job object based on a launchd.plist file
*
* @param label uniquely identifier for launchd. This should be in the form of a reverse domain
* @param domain Corresponding AHLaunchDomain
*
* @return an allocated AHLaunchJob with the corresponding keys
*/
+ (AHLaunchJob *)jobFromFileNamed:(NSString *)label
inDomain:(AHLaunchDomain)domain;
/**
* Create a job object based on currently running Launchd Job
*
* @param label uniquely identifier for launchd. This should be in the form of a reverse domain
* @param domain Corresponding AHLaunchDomain
*
* @return an allocated AHLaunchJob with the corresponding keys
*/
+ (AHLaunchJob *)runningJobWithLabel:(NSString *)label
inDomain:(AHLaunchDomain)domain;
/**
* List with all Jobs available based of files in the specified domain
*
* @param domain Corresponding AHLaunchDomain
*
* @return Array of allocated AHLaunchJob with the corresponding keys
*/
+ (NSArray *)allJobsFromFilesInDomain:(AHLaunchDomain)domain;
/**
* List with all currently running jobs in the specified domain
*
* @param domain Corresponding AHLaunchDomain
*
* @return Array of allocated AHLaunchJob with the corresponding keys
*/
+ (NSArray *)allRunningJobsInDomain:(AHLaunchDomain)domain;
/**
* List of running Jobs based on criteria
*
* @param match string to match.
* @param domain AHLaunchDomain
*
* @return Array of allocated AHLaunchJob with the corresponding keys
*/
+ (NSArray *)runningJobsMatching:(NSString *)match
inDomain:(AHLaunchDomain)domain;
/**
* Installs a privileged helper tool with the specified label using a custom prompt.
*
* @param label label of the Helper Tool
* @param prompt message to prefix the authorization prompt
* @param error populated should error occur
*
* @return YES for success NO on failure;
* @warning Must be code singed properly, and have an embedded Info.plist and
*Launchd.plist, and located in the applications
*MainBundle/Library/LaunchServices
*/
+ (BOOL)installHelper:(NSString *)label
prompt:(NSString *)prompt
error:(NSError **)error;
/**
* Uninstalls HelperTool with specified label using a custom prompt.
*
* @param label Label of the Helper Tool.
* @param prompt Message to prefix the authorization prompt.
* @param error Error object populated if an error occurs.
* @return YES for success NO on failure;
*/
+ (BOOL)uninstallHelper:(NSString *)label
prompt:(NSString *)prompt
error:(NSError *__autoreleasing *)error;
/**
* Uninstalls HelperTool with specified label.
*
* @param label label of the Helper Tool
* @param error error object populated if an error occurs.
*
* @return YES for success NO on failure;
*/
+ (BOOL)uninstallHelper:(NSString *)label
error:(NSError *__autoreleasing *)error
__attribute__((deprecated));
/**
* Cleans up files associated with the helper tool that SMJobBless leaves behind
*
* @param label label of the Helper Tool
* @param error error object populated if an error occurs.
*
* @return YES for success NO on failure;
*/
+ (BOOL)removeFilesForHelperWithLabel:(NSString *)label
error:(NSError *__autoreleasing *)error;
#pragma mark - Domain Error
/**
* Convenience Method for populating an NSError using message and code. It
*also can be used to provide a return value for escaping another method. e.g.
*on failure of a previous condition you could do "return [AHLaunchCtl
*errorWithMessage:@"your message" andCode:1 error:error]" and you'll get
*escaped out, if method return you're using on has BOOL return and error is
*already an __autoreleasing error pointer
*
* @param message Human readable error message
* @param code error Code
* @param error error pointer
*
* @return YES if error code passed is 0, NO on all other error codes passed
*into;
*/
+ (BOOL)errorWithMessage:(NSString *)message
andCode:(NSInteger)code
error:(NSError **)error;
@end
|
GDXRepo/AHLaunchCtl
|
AHLaunchCtl/AHServiceManagement.h
|
<gh_stars>10-100
// AHServiceManagement.h
// AHLaunchCtl
//
// Copyright (c) 2014 <NAME> ( https://github.com/eahrold/AHLaunchCtl )
//
// 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.
#import <Foundation/Foundation.h>
#import <AHLaunchCtl/AHLaunchJob.h>
/** ~/Library/LaunchAgents/
* @warning Make sure to expand the tilde if necissary for checking!
*/
extern NSString *const kAHUserLaunchAgentTildeDirectory;
/** /Library/LaunchDaemons/ */
extern NSString *const kAHGlobalLaunchDaemonDirectory;
/** /Library/LaunchAgents/ */
extern NSString *const kAHGlobalLaunchAgentDirectory;
/** /System/Library/LaunchDaemons/ */
extern NSString *const kAHSystemLaunchDaemonDirectory;
/** /System/Library/LaunchAgents/ */
extern NSString *const kAHSystemLaunchAgentDirectory;
/**
* Function to test whether the job is currently running
*
* @param label Label of the LaunchD job
* @param domain AHLaunchDomain
*
* @return YES if Loaded, NO otherwise
*/
extern BOOL jobIsRunning(NSString *label, AHLaunchDomain domain);
/**
* More expensive version of jobIsRunning(), but will not cause "launchadd: FAILURE:" messages to appear in the system.log when the job is not loaded.
*
* @param label Label of the LaunchD job
* @param domain AHLaunchDomain
*
* @return YES if Loaded, NO otherwise
*/
extern BOOL jobIsRunning2(NSString *label, AHLaunchDomain domain);
#pragma mark - Bridged ServiceManagement
/**
* Dictionary representation of the LaunchD job
*
* @param domain Domain of the job
* @param label Label of the job
*
* @return Populated dictionary if job exists
*/
extern NSDictionary *AHJobCopyDictionary(AHLaunchDomain domain,
NSString *label);
/**
* Array of Jobs
*
* @param domain Domain to get jobs from
*
* @return Array of Jobs
*/
extern NSArray *AHCopyAllJobDictionaries(AHLaunchDomain domain);
/**
* Submit a job to load
*
* @param domain Domain for the job
* @param dictionary Job object and keys
* @param authRef Authorization data for job
* @param error Pointer to error to populate should one occur
*
* @return YES if job was successfully loaded, NO otherwise
*/
extern BOOL AHJobSubmit(AHLaunchDomain domain,
NSDictionary *dictionary,
AuthorizationRef authRef,
NSError **error);
/**
* Submit a job to load and create requisite files for persistence.
*
* @param domain Domain for the job
* @param dictionary Job object and keys
* @param authRef Authorization data for job
* @param error Pointer to error to populate should one occur
*
* @return YES if job was successfully loaded, NO otherwise
*/
BOOL AHJobSubmitCreatingFile(AHLaunchDomain domain,
NSDictionary *dictionary,
AuthorizationRef authRef,
NSError *__autoreleasing *error);
/**
* Remove a loaded job
*
* @param domain Domain for the job
* @param label Label of the job
* @param authRef Authorization data for job
* @param error Pointer to error to populate should one occur
*
* @return YES if job was successfully loaded, NO otherwise
*/
extern BOOL AHJobRemove(AHLaunchDomain domain,
NSString *label,
AuthorizationRef authRef,
NSError **error);
/**
* Remove a loaded job from the registry and delete the file.
*
* @param domain Domain for the job
* @param label Label of the job
* @param authRef Authorization data for job
* @param error Pointer to error to populate should one occur
*
* @return YES if job was successfully loaded, NO otherwise
*/
extern BOOL AHJobRemoveIncludingFile(AHLaunchDomain domain,
NSString *label,
AuthorizationRef authRef,
NSError **error);
/**
* Submits the executable for the given label as a launchd job.
* @param domain Domain for the job
* @param label Label of the executable
* @param authRef Authorization data for job
* @param error Pointer to error to populate should one occur
*
* @return YES if job was successfully loaded, NO otherwise
*/
extern BOOL AHJobBless(AHLaunchDomain domain,
NSString *label,
AuthorizationRef authRef,
NSError **error);
/**
* Removes the executable, and unloads the job.
* @param domain Domain for the job
* @param label Label of the executable
* @param authRef Authorization data for job
* @param error Pointer to error to populate should one occur
*
* @return YES if job was successfully loaded, NO otherwise
*/
extern BOOL AHJobUnbless(AHLaunchDomain domain,
NSString *label,
AuthorizationRef authRef,
NSError **error);
|
GDXRepo/AHLaunchCtl
|
AHLaunchCtl/AHServiceManagement_Private.h
|
<gh_stars>10-100
//
// AHServiceManagement_Private.h
// AHLaunchCtl
//
// Created by Eldon on 2/21/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
#ifndef AHLaunchCtl_AHServiceManagement_Private_h
#define AHLaunchCtl_AHServiceManagement_Private_h
/**
* Directory path for launchd.plist files based on the supplied domain.
*
* @param domain AHLaunchDomain.
*
* @return Directory path for domain.
*/
extern NSString *launchdJobFileDirectory(AHLaunchDomain domain);
/**
* Get the file path to the launchd.plist based on the supplied domain.
*
* @param label label of the launchd plist
* @param domain AHLaunchDomain
*
* @return File path to the launchd.plist
*/
extern NSString *launchdJobFile(NSString *label, AHLaunchDomain domain);
/**
* Convert an AHLaunchDomain to an Service Management domain
*
* @param domain AHLaunchDomain
*
* @return the Service management domain to pass into SM functions.
*/
extern NSString *SMDomain(AHLaunchDomain domain);
BOOL AHCreatePrivilegedLaunchdPlist(AHLaunchDomain domain,
NSDictionary *dictionary,
AuthorizationRef authRef,
NSError *__autoreleasing *error);
BOOL AHRemovePrivilegedFile(AHLaunchDomain domain,
NSString *filePath,
AuthorizationRef authRef,
NSError *__autoreleasing *error);
#endif
|
GDXRepo/AHLaunchCtl
|
AHLaunchCtl/AHLaunchJobSchedule.h
|
<filename>AHLaunchCtl/AHLaunchJobSchedule.h
//
// NSDateComponents+AHLaunchCtlSchedule.h
// AHLaunchCtl
//
// Created by Eldon on 4/26/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
/**
* Used as a wildcard in schedule
*/
extern NSInteger AHUndefinedScheduleComponent;
/**
* Schedule Class for StartCalendarIntervals
*/
@interface AHLaunchJobSchedule : NSDateComponents
// Init with a dictionary of keys, such as a dictionary
- (instancetype)initWithDictionary:(NSDictionary *)dictionary;
- (NSDictionary *)dictionary;
/**
* Set up a custom AHLaunchCtl Schedule
* @discussion Pass AHUndefinedScheduleComponent to any unused parameter.
*
* @param minute minute of the hour
* @param hour hour of the day
* @param day day of the month
* @param weekday day of the week (0 is sunday)
* @param month month of the year
*
* @return Initialized AHLaunchJobSchedule object
*/
+ (instancetype)scheduleWithMinute:(NSInteger)minute
hour:(NSInteger)hour
day:(NSInteger)day
weekday:(NSInteger)weekday
month:(NSInteger)month;
/**
* setup a daily run
*
* @param hour hour of the day
* @param minute minute of the hour
*
* @return Initialized AHLaunchJobSchedule object
*/
+ (instancetype)dailyRunAtHour:(NSInteger)hour minute:(NSInteger)minute;
/**
* setup a weekly run
*
* @param weekday day of the week (0 is sunday)
* @param hour hour of the day
*
* @return Initialized AHLaunchJobSchedule object
*/
+ (instancetype)weeklyRunOnWeekday:(NSInteger)weekday hour:(NSInteger)hour;
/**
* setup a monthly run
*
* @param day day of the month
* @param hour hour of the day
*
* @return Initialized AHLaunchJobSchedule object
*/
+ (instancetype)monthlyRunOnDay:(NSInteger)day hour:(NSInteger)hour;
@end
|
GDXRepo/AHLaunchCtl
|
AHLaunchCtl/AHAuthorizer.h
|
// AHAuthorizer.h
// Copyright (c) 2014 <NAME> ( https://github.com/eahrold/AHLaunchCtl )
//
// 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.
#import <Foundation/Foundation.h>
/**
* Authorization Class for AHLaunchCtl jobs where authorization is required.
*/
@interface AHAuthorizer : NSObject
/**
* Prompt for authorization to the System Daemon
*
* @param label Unique name of the job getting authorized. Should be similar to
*a reverse domain.
* @param prompt String used during the authorization dialog.
*
* @return AuthorizationRef
*/
+ (OSStatus)authorizeSystemDaemonWithLabel:(NSString *)label
prompt:(NSString *)prompt
authRef:(AuthorizationRef *)authRef;
/**
* Prompt for authorization to the Service Management system
*
* @param prompt string to include in the prompt dialog
*
* @return AuthorizationRef
*/
+ (OSStatus)authorizeSMJobBlessWithPrompt:(NSString *)prompt
authRef:(AuthorizationRef *)authRef;
/**
* Free the AuthorizationRef object
*
* @param authRef the AuthorizationRef to be freed
*/
+ (void)authorizationFree:(AuthorizationRef)authRef;
@end
|
BioBox/calcurse
|
src/io.c
|
/*
* Calcurse - text-based organizer
*
* Copyright (c) 2004-2020 calcurse Development Team <<EMAIL>>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Send your feedback or comments to : <EMAIL>
* Calcurse home page : http://calcurse.org
*
*/
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <signal.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
#include <errno.h>
#include "calcurse.h"
#include "sha1.h"
struct ht_keybindings_s {
const char *label;
enum vkey key;
HTABLE_ENTRY(ht_keybindings_s);
};
static void load_keys_ht_getkey(struct ht_keybindings_s *, const char **,
int *);
static int load_keys_ht_compare(struct ht_keybindings_s *,
struct ht_keybindings_s *);
#define HSIZE 256
HTABLE_HEAD(ht_keybindings, HSIZE, ht_keybindings_s);
HTABLE_PROTOTYPE(ht_keybindings, ht_keybindings_s)
HTABLE_GENERATE(ht_keybindings, ht_keybindings_s, load_keys_ht_getkey,
load_keys_ht_compare)
static int modified = 0;
static char apts_sha1[SHA1_DIGESTLEN * 2 + 1];
static char todo_sha1[SHA1_DIGESTLEN * 2 + 1];
/* Ask user for a file name to export data to. */
static FILE *get_export_stream(enum export_type type)
{
FILE *stream;
char *home, *stream_name;
const char *question =
_("Choose the file used to export calcurse data:");
const char *wrong_name =
_("The file cannot be accessed, please enter another file name.");
const char *press_enter = _("Press [ENTER] to continue.");
const char *file_ext[IO_EXPORT_NBTYPES] = { "ical", "txt" };
stream = NULL;
if ((home = getenv("HOME")) != NULL)
asprintf(&stream_name, "%s/calcurse.%s", home, file_ext[type]);
else
asprintf(&stream_name, "%s/calcurse.%s", get_tempdir(),
file_ext[type]);
while (stream == NULL) {
status_mesg(question, "");
if (updatestring(win[STA].p, &stream_name, 0, 1)) {
mem_free(stream_name);
return NULL;
}
stream = fopen(stream_name, "w");
if (stream == NULL) {
status_mesg(wrong_name, press_enter);
keys_wait_for_any_key(win[KEY].p);
}
}
mem_free(stream_name);
return stream;
}
/* Append a line to a file. */
unsigned io_fprintln(const char *fname, const char *fmt, ...)
{
FILE *fp;
va_list ap;
char *buf;
int ret;
fp = fopen(fname, "a");
RETVAL_IF(!fp, 0, _("Failed to open \"%s\", - %s\n"), fname,
strerror(errno));
va_start(ap, fmt);
ret = vasprintf(&buf, fmt, ap);
RETVAL_IF(ret < 0, 0, _("Failed to build message\n"));
va_end(ap);
ret = fprintf(fp, "%s", buf);
RETVAL_IF(ret < 0, 0, _("Failed to print message \"%s\"\n"), buf);
ret = fclose(fp);
RETVAL_IF(ret != 0, 0, _("Failed to close \"%s\" - %s\n"),
fname, strerror(errno));
mem_free(buf);
return 1;
}
/*
* Initialization of data paths. The cfile argument is the variable
* which contains the calendar file. If none is given, then the default
* one (~/.local/share/calcurse/apts) is taken. If the one given does not exist,
* it is created.
* The datadir argument can be used to specify an alternative data root dir.
* The confdir argument can be used to specify an alternative configuration dir.
* If ~/.calcurse exists, it will be used instead for backward compatibility.
*/
void io_init(const char *cfile, const char *datadir, const char *confdir)
{
char* home_dir = getenv("HOME");
char* legacy_dir = NULL;
if (home_dir) {
asprintf(&legacy_dir, "%s%s", home_dir, "/" DIR_NAME_LEGACY);
if (!io_dir_exists(legacy_dir)) {
mem_free(legacy_dir);
legacy_dir = NULL;
}
}
if (datadir)
asprintf(&path_ddir, "%s%s", datadir, "/");
else if (legacy_dir)
path_ddir = mem_strdup(legacy_dir);
else if ((path_ddir = getenv("XDG_DATA_HOME")))
asprintf(&path_ddir, "%s%s", path_ddir, "/" DIR_NAME);
else if (home_dir)
asprintf(&path_ddir, "%s%s", home_dir, "/.local/share/" DIR_NAME);
else
path_ddir = mem_strdup("./." DIR_NAME);
if (confdir)
asprintf(&path_cdir, "%s%s", confdir, "/");
else if (datadir)
path_cdir = mem_strdup(path_ddir);
else if (legacy_dir)
path_cdir = mem_strdup(legacy_dir);
else if ((path_cdir = getenv("XDG_CONFIG_HOME")))
asprintf(&path_cdir, "%s%s", path_cdir, "/" DIR_NAME);
else if (home_dir)
asprintf(&path_cdir, "%s%s", home_dir, "/.config/" DIR_NAME);
else
path_cdir = mem_strdup("./." DIR_NAME);
if (legacy_dir)
mem_free(legacy_dir);
/* Data files */
if (cfile) {
path_apts = mem_strdup(cfile);
EXIT_IF(!io_file_exists(path_apts), _("%s does not exist"),
path_apts);
} else {
asprintf(&path_apts, "%s%s", path_ddir, APTS_PATH_NAME);
}
asprintf(&path_todo, "%s%s", path_ddir, TODO_PATH_NAME);
asprintf(&path_cpid, "%s%s", path_ddir, CPID_PATH_NAME);
asprintf(&path_dpid, "%s%s", path_ddir, DPID_PATH_NAME);
asprintf(&path_notes, "%s%s", path_ddir, NOTES_DIR_NAME);
asprintf(&path_dmon_log, "%s%s", path_ddir, DLOG_PATH_NAME);
/* Configuration files */
asprintf(&path_conf, "%s%s", path_cdir, CONF_PATH_NAME);
asprintf(&path_keys, "%s%s", path_cdir, KEYS_PATH_NAME);
asprintf(&path_hooks, "%s%s", path_cdir, HOOKS_DIR_NAME);
}
void io_extract_data(char *dst_data, const char *org, int len)
{
int i;
for (; *org == ' ' || *org == '\t'; org++) ;
for (i = 0; i < len - 1; i++) {
if (*org == '\n' || *org == '\0')
break;
*dst_data++ = *org++;
}
*dst_data = '\0';
}
static pthread_mutex_t io_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t io_periodic_save_mutex = PTHREAD_MUTEX_INITIALIZER;
static void io_mutex_lock(void)
{
pthread_mutex_lock(&io_mutex);
}
static void io_mutex_unlock(void)
{
pthread_mutex_unlock(&io_mutex);
}
/* Print all appointments and events to stdout. */
void io_dump_apts(const char *fmt_apt, const char *fmt_rapt,
const char *fmt_ev, const char *fmt_rev)
{
llist_item_t *i;
LLIST_FOREACH(&recur_elist, i) {
struct recur_event *rev = LLIST_GET_DATA(i);
time_t day = DAY(rev->day);
print_recur_event(fmt_rev, day, rev);
}
LLIST_TS_FOREACH(&recur_alist_p, i) {
struct recur_apoint *rapt = LLIST_GET_DATA(i);
time_t day = DAY(rapt->start);
print_recur_apoint(fmt_rapt, day, rapt->start, rapt);
}
LLIST_TS_FOREACH(&alist_p, i) {
struct apoint *apt = LLIST_TS_GET_DATA(i);
time_t day = DAY(apt->start);
print_apoint(fmt_apt, day, apt);
}
LLIST_FOREACH(&eventlist, i) {
struct event *ev = LLIST_TS_GET_DATA(i);
time_t day = DAY(ev->day);
print_event(fmt_ev, day, ev);
}
}
/*
* Save the apts data file, which contains the
* appointments first, and then the events.
* Recursive items are written first.
*/
unsigned io_save_apts(const char *aptsfile)
{
llist_item_t *i;
FILE *fp;
if (aptsfile) {
if (read_only)
return 1;
if ((fp = fopen(aptsfile, "w")) == NULL)
return 0;
} else {
fp = stdout;
}
recur_save_data(fp);
if (ui_mode == UI_CURSES)
LLIST_TS_LOCK(&alist_p);
LLIST_TS_FOREACH(&alist_p, i) {
struct apoint *apt = LLIST_TS_GET_DATA(i);
apoint_write(apt, fp);
}
if (ui_mode == UI_CURSES)
LLIST_TS_UNLOCK(&alist_p);
LLIST_FOREACH(&eventlist, i) {
struct event *ev = LLIST_TS_GET_DATA(i);
event_write(ev, fp);
}
if (aptsfile)
file_close(fp, __FILE_POS__);
return 1;
}
/* Print all todo items to stdout. */
void io_dump_todo(const char *fmt_todo)
{
llist_item_t *i;
LLIST_FOREACH(&todolist, i) {
struct todo *todo = LLIST_TS_GET_DATA(i);
print_todo(fmt_todo, todo);
}
}
/* Save the todo data file. */
unsigned io_save_todo(const char *todofile)
{
llist_item_t *i;
FILE *fp;
if (todofile) {
if (read_only)
return 1;
if ((fp = fopen(todofile, "w")) == NULL)
return 0;
} else {
fp = stdout;
}
LLIST_FOREACH(&todolist, i) {
struct todo *todo = LLIST_TS_GET_DATA(i);
todo_write(todo, fp);
}
if (todofile)
file_close(fp, __FILE_POS__);
return 1;
}
/* Save user-defined keys */
unsigned io_save_keys(void)
{
FILE *fp;
if (read_only)
return 1;
if ((fp = fopen(path_keys, "w")) == NULL)
return 0;
keys_save_bindings(fp);
file_close(fp, __FILE_POS__);
return 1;
}
static int io_compute_hash(const char *path, char *buf)
{
FILE *fp = fopen(path, "r");
if (!fp)
return 0;
sha1_stream(fp, buf);
fclose(fp);
return 1;
}
/* A merge implies a save operation and must be followed by reload of data. */
static void io_merge_data(void)
{
char *path_apts_new, *path_todo_new;
const char *new_ext = ".new";
asprintf(&path_apts_new, "%s%s", path_apts, new_ext);
asprintf(&path_todo_new, "%s%s", path_todo, new_ext);
io_save_apts(path_apts_new);
io_save_todo(path_todo_new);
/*
* We do not directly write to the data files here; however, the
* external merge tool might incorporate changes from the new file into
* the main data files.
*/
run_hook("pre-save");
if (!io_files_equal(path_apts, path_apts_new)) {
const char *arg_apts[] = { conf.mergetool, path_apts,
path_apts_new, NULL };
wins_launch_external(arg_apts);
}
if (!io_files_equal(path_todo, path_todo_new)) {
const char *arg_todo[] = { conf.mergetool, path_todo,
path_todo_new, NULL };
wins_launch_external(arg_todo);
}
mem_free(path_apts_new);
mem_free(path_todo_new);
/*
* We do not directly write to the data files here; however, the
* external merge tool will likely have incorporated changes from the
* new file into the main data files at this point.
*/
run_hook("post-save");
/*
* The user has merged, so override the modified flag
* (and follow up with reload of the data files).
*/
io_unset_modified();
}
/* For the return values, see io_save_cal() below. */
static int resolve_save_conflict(void)
{
char *msg_um_asktype = NULL;
const char *msg_um_prefix =
_("Data files have changed and will be overwritten:");
const char *msg_um_overwrite = _("(c)ontinue");
const char *msg_um_merge = _("(m)erge");
const char *msg_um_keep = _("c(a)ncel");
const char *msg_um_choice = _("[cma]");
int ret = IO_SAVE_CANCEL;
asprintf(&msg_um_asktype, "%s %s, %s, %s", msg_um_prefix,
msg_um_overwrite, msg_um_merge, msg_um_keep);
switch (status_ask_choice(msg_um_asktype, msg_um_choice, 3)) {
case 1:
ret = IO_SAVE_CTINUE;
break;
case 2:
io_merge_data();
io_load_data(NULL, FORCE);
ret = IO_SAVE_RELOAD;
break;
case 3:
/* FALLTHROUGH */
default:
ret = IO_SAVE_CANCEL;
}
mem_free(msg_um_asktype);
return ret;
}
/*
* Return codes for new_data() and io_load_data().
* Note that they are file internal.
*/
#define NONEW 0
#define APTS (1 << 0)
#define TODO (1 << 1)
#define APTS_TODO APTS | TODO
#define NOKNOW -1
static int new_data()
{
char sha1_new[SHA1_DIGESTLEN * 2 + 1];
int ret = NONEW;
if (io_compute_hash(path_apts, sha1_new)) {
if (strncmp(sha1_new, apts_sha1, SHA1_DIGESTLEN * 2) != 0) {
ret |= APTS;
}
} else {
ret = NOKNOW;
goto exit;
}
if (io_compute_hash(path_todo, sha1_new)) {
if (strncmp(sha1_new, todo_sha1, SHA1_DIGESTLEN * 2) != 0) {
ret |= TODO;
}
} else {
ret = NOKNOW;
goto exit;
}
exit:
return ret;
}
/*
* Save the calendar data.
* The return value tells how a possible save conflict should be/was resolved:
* IO_SAVE_CTINUE: continue save operation and overwrite the data files
* IO_SAVE_RELOAD: cancel save operation (data files changed and reloaded)
* IO_SAVE_CANCEL: cancel save operation (user's decision, keep data files, no reload)
* IO_SAVE_NOOP: cancel save operation (nothing has changed)
* IO_SAVE_ERROR: cannot access data
*/
int io_save_cal(enum save_type s_t)
{
int ret, new;
if (read_only)
return IO_SAVE_CANCEL;
io_mutex_lock();
if ((new = new_data()) == NOKNOW) {
ret = IO_SAVE_ERROR;
goto cleanup;
}
if (new) { /* New data */
if (s_t == periodic) {
ret = IO_SAVE_CANCEL;
goto cleanup;
}
/* Interactively decide what to do. */
if ((ret = resolve_save_conflict()))
goto cleanup;
} else /* No new data */
if (!io_get_modified()) {
ret = IO_SAVE_NOOP;
goto cleanup;
}
ret = IO_SAVE_CTINUE;
run_hook("pre-save");
if (io_save_todo(path_todo) &&
io_save_apts(path_apts)) {
io_compute_hash(path_apts, apts_sha1);
io_compute_hash(path_todo, todo_sha1);
io_unset_modified();
} else
ret = IO_SAVE_ERROR;
run_hook("post-save");
cleanup:
io_mutex_unlock();
return ret;
}
static void io_load_error(const char *filename, unsigned line,
const char *mesg)
{
EXIT("%s:%u: %s", filename, line, mesg);
}
/*
* Check what type of data is written in the appointment file,
* and then load either: a new appointment, a new event, or a new
* recursive item (which can also be either an event or an appointment).
*/
void io_load_app(struct item_filter *filter)
{
FILE *data_file;
int c, is_appointment, is_event, is_recursive;
struct tm start, end, until, lt;
struct rpt rpt;
time_t t;
int id = 0;
char type, state = 0L;
char note[MAX_NOTESIZ + 1], *notep;
unsigned line = 0;
char *scan_error;
t = time(NULL);
localtime_r(&t, <);
start = end = until = lt;
data_file = fopen(path_apts, "r");
EXIT_IF(data_file == NULL, _("failed to open appointment file"));
sha1_stream(data_file, apts_sha1);
rewind(data_file);
for (;;) {
is_appointment = is_event = is_recursive = 0;
line++;
scan_error = NULL;
c = getc(data_file);
if (c == EOF)
break;
ungetc(c, data_file);
/* Read the date first: it is common to both events
* and appointments.
*/
if (fscanf(data_file, "%d / %d / %d ",
&start.tm_mon, &start.tm_mday,
&start.tm_year) != 3)
io_load_error(path_apts, line,
_("syntax error in the item date"));
/* Read the next character : if it is an '@' then we have
* an appointment, else if it is an '[' we have en event.
*/
c = getc(data_file);
if (c == '@')
is_appointment = 1;
else if (c == '[')
is_event = 1;
else
io_load_error(path_apts, line,
_("no event nor appointment found"));
/* Read the remaining informations. */
if (is_appointment) {
if (fscanf
(data_file,
" %d : %d -> %d / %d / %d @ %d : %d ",
&start.tm_hour, &start.tm_min, &end.tm_mon,
&end.tm_mday, &end.tm_year, &end.tm_hour,
&end.tm_min) != 7)
io_load_error(path_apts, line,
_("syntax error in item time or duration"));
} else if (is_event) {
if (fscanf(data_file, " %d ", &id) != 1
|| getc(data_file) != ']')
io_load_error(path_apts, line,
_("syntax error in item identifier"));
while ((c = getc(data_file)) == ' ') ;
ungetc(c, data_file);
} else {
io_load_error(path_apts, line,
_("wrong format in the appointment or event"));
/* NOTREACHED */
}
/* Check if we have a recursive item. */
c = getc(data_file);
if (c == '{') {
is_recursive = 1;
if (fscanf(data_file, " %d%c ", &rpt.freq, &type) != 2)
io_load_error(path_apts, line,
_("syntax error in item repetition"));
else
rpt.type = recur_char2def(type);
c = getc(data_file);
/* Optional until date */
if (c == '-' && getc(data_file) == '>') {
if (fscanf
(data_file, " %d / %d / %d ",
&until.tm_mon, &until.tm_mday,
&until.tm_year) != 3)
io_load_error(path_apts, line,
_("syntax error in until date"));
if (!check_date(until.tm_year, until.tm_mon,
until.tm_mday))
io_load_error(path_apts, line,
_("until date error"));
until.tm_hour = 0;
until.tm_min = 0;
until.tm_sec = 0;
until.tm_isdst = -1;
until.tm_year -= 1900;
until.tm_mon--;
rpt.until = mktime(&until);
c = getc(data_file);
} else
rpt.until = 0;
/* Optional bymonthday list */
if (c == 'd') {
if (rpt.type == RECUR_WEEKLY)
io_load_error(path_apts, line,
_("BYMONTHDAY illegal with WEEKLY"));
ungetc(c, data_file);
recur_bymonthday(&rpt.bymonthday, data_file);
c = getc(data_file);
} else
LLIST_INIT(&rpt.bymonthday);
/* Optional bywday list */
if (c == 'w') {
ungetc(c, data_file);
recur_bywday(rpt.type, &rpt.bywday, data_file);
c = getc(data_file);
} else
LLIST_INIT(&rpt.bywday);
/* Optional bymonth list */
if (c == 'm') {
ungetc(c, data_file);
recur_bymonth(&rpt.bymonth, data_file);
c = getc(data_file);
} else
LLIST_INIT(&rpt.bymonth);
/* Optional exception dates */
if (c == '!') {
ungetc(c, data_file);
recur_exc_scan(&rpt.exc, data_file);
c = getc(data_file);
} else
LLIST_INIT(&rpt.exc);
/* End of recurrence rule */
if (c != '}')
io_load_error(path_apts, line,
_("missing end of recurrence"));
while ((c = getc(data_file)) == ' ') ;
}
/* Check if a note is attached to the item. */
if (c == '>') {
note_read(note, data_file);
c = getc(data_file);
notep = note;
} else
notep = NULL;
/*
* Last: read the item description and load it into its
* corresponding linked list, depending on the item type.
*/
if (is_appointment) {
if (c == '!')
state |= APOINT_NOTIFY;
else if (c == '|')
state = 0L;
else
io_load_error(path_apts, line,
_("syntax error in item state"));
if (is_recursive)
scan_error = recur_apoint_scan(data_file, start, end, state,
notep, filter, &rpt);
else
scan_error = apoint_scan(data_file, start, end, state,
notep, filter);
} else if (is_event) {
ungetc(c, data_file);
if (is_recursive)
scan_error = recur_event_scan(data_file, start, id, notep,
filter, &rpt);
else
scan_error = event_scan(data_file, start, id, notep, filter);
} else {
io_load_error(path_apts, line,
_("wrong format in the appointment or event"));
/* NOTREACHED */
}
if (scan_error)
io_load_error(path_apts, line, scan_error);
}
file_close(data_file, __FILE_POS__);
}
/* Load the todo data */
void io_load_todo(struct item_filter *filter)
{
FILE *data_file;
char *newline;
int c, id, completed, cond;
char buf[BUFSIZ], e_todo[BUFSIZ], note[MAX_NOTESIZ + 1];
unsigned line = 0;
data_file = fopen(path_todo, "r");
EXIT_IF(data_file == NULL, _("failed to open todo file"));
sha1_stream(data_file, todo_sha1);
rewind(data_file);
for (;;) {
line++;
c = getc(data_file);
if (c == EOF) {
break;
} else if (c == '[') {
/* new style with id */
c = getc(data_file);
if (c == '-') {
completed = 1;
} else {
completed = 0;
ungetc(c, data_file);
}
if (fscanf(data_file, " %d ", &id) != 1
|| getc(data_file) != ']')
io_load_error(path_todo, line,
_("syntax error in item identifier"));
while ((c = getc(data_file)) == ' ') ;
ungetc(c, data_file);
} else {
id = 9;
completed = 0;
ungetc(c, data_file);
}
/* Now read the attached note, if any. */
c = getc(data_file);
if (c == '>') {
note_read(note, data_file);
} else {
note[0] = '\0';
ungetc(c, data_file);
}
/* Then read todo description. */
if (!fgets(buf, sizeof buf, data_file))
buf[0] = '\0';
newline = strchr(buf, '\n');
if (newline)
*newline = '\0';
io_extract_data(e_todo, buf, sizeof buf);
/* Filter item. */
struct todo *todo = NULL;
if (filter) {
cond = (
!(filter->type_mask & TYPE_MASK_TODO) ||
(filter->regex && regexec(filter->regex, e_todo, 0, 0, 0)) ||
(filter->priority && id != filter->priority) ||
(filter->completed && !completed) ||
(filter->uncompleted && completed)
);
if (filter->hash) {
todo = todo_add(e_todo, id, completed, note);
char *hash = todo_hash(todo);
cond = cond || !hash_matches(filter->hash, hash);
mem_free(hash);
}
if ((!filter->invert && cond) || (filter->invert && !cond)) {
if (filter->hash)
todo_delete(todo);
continue;
}
}
if (!todo)
todo = todo_add(e_todo, id, completed, note);
}
file_close(data_file, __FILE_POS__);
}
/*
* Load appointments and todo items.
* Unless told otherwise, the function will only load a file that has changed
* since last saved or loaded. The new_data() return code is passed on when
* force is false. When force is true (FORCE), the return code is of no use.
*/
int io_load_data(struct item_filter *filter, int force)
{
run_hook("pre-load");
if (force)
force = APTS_TODO;
else
force = new_data();
if (force == NOKNOW)
goto exit;
if (force & APTS) {
apoint_llist_free();
event_llist_free();
recur_apoint_llist_free();
recur_event_llist_free();
apoint_llist_init();
event_llist_init();
recur_apoint_llist_init();
recur_event_llist_init();
io_load_app(filter);
}
if (force & TODO) {
todo_free_list();
todo_init_list();
io_load_todo(filter);
}
io_unset_modified();
exit:
run_hook("post-load");
return force;
}
/*
* The return codes reflect the user choice in case of unsaved in-memory changes.
*/
int io_reload_data(void)
{
char *msg_um_asktype = NULL;
int load = NOFORCE;
int ret = IO_RELOAD_LOAD;
io_mutex_lock();
if (io_get_modified()) {
const char *msg_um_prefix =
_("Screen data have changed and will be lost:");
const char *msg_um_discard = _("(c)ontinue");
const char *msg_um_merge = _("(m)erge");
const char *msg_um_keep = _("c(a)ncel");
const char *msg_um_choice = _("[cma]");
asprintf(&msg_um_asktype, "%s %s, %s, %s", msg_um_prefix,
msg_um_discard, msg_um_merge, msg_um_keep);
switch (status_ask_choice(msg_um_asktype, msg_um_choice, 3)) {
case 1:
load = FORCE;
ret = IO_RELOAD_CTINUE;
break;
case 2:
io_merge_data();
load = FORCE;
ret = IO_RELOAD_MERGE;
break;
case 3:
ret = IO_RELOAD_CANCEL;
/* FALLTHROUGH */
default:
goto cleanup;
}
}
load = io_load_data(NULL, load);
if (load == NONEW)
ret = IO_RELOAD_NOOP;
else if (load == NOKNOW)
ret = IO_RELOAD_ERROR;
cleanup:
io_mutex_unlock();
mem_free(msg_um_asktype);
return ret;
}
static void
load_keys_ht_getkey(struct ht_keybindings_s *data, const char **key,
int *len)
{
*key = data->label;
*len = strlen(data->label);
}
static int
load_keys_ht_compare(struct ht_keybindings_s *data1,
struct ht_keybindings_s *data2)
{
const int KEYLEN = strlen(data1->label);
if (strlen(data2->label) == KEYLEN
&& !memcmp(data1->label, data2->label, KEYLEN))
return 0;
else
return 1;
}
/*
* Load user-definable keys from file.
* A hash table is used to speed up loading process in avoiding string
* comparisons.
* A log file is also built in case some errors were found in the key
* configuration file.
*/
void io_load_keys(const char *pager)
{
struct ht_keybindings_s virt_keys[NBVKEYS], *ht_elm, ht_entry;
FILE *keyfp;
char buf[BUFSIZ], key_label[BUFSIZ], key_str[BUFSIZ];
char *p, *msg;
struct io_file *log;
int i, n, skipped, loaded, line, assigned, undefined, key;
keys_init();
struct ht_keybindings ht_keys = HTABLE_INITIALIZER(&ht_keys);
for (i = 0; i < NBVKEYS; i++) {
virt_keys[i].key = (enum vkey)i;
virt_keys[i].label = keys_get_label((enum vkey)i);
HTABLE_INSERT(ht_keybindings, &ht_keys, &virt_keys[i]);
}
keyfp = fopen(path_keys, "r");
EXIT_IF(keyfp == NULL, _("failed to open key file"));
log = io_log_init();
skipped = loaded = line = 0;
while (fgets(buf, BUFSIZ, keyfp) != NULL) {
line++;
p = buf;
while (*p == ' ' || *p == '\t') p++;
if (*p == '#' || *p == '\n')
continue;
/* Find the virtual key by key label. */
if (sscanf(p, "%s", key_label) != 1) {
skipped++;
io_log_print(log, line,
_("Could not read key label"));
continue;
}
p += strlen(key_label);
ht_entry.label = key_label;
ht_elm = HTABLE_LOOKUP(ht_keybindings, &ht_keys, &ht_entry);
if (!ht_elm) {
skipped++;
asprintf(&msg,
_("Key label not recognized: \"%s\""),
key_label);
io_log_print(log, line, msg);
mem_free(msg);
continue;
}
/* Assign keyboard keys to the virtual key. */
assigned = undefined = 0;
for (;;) {
if (sscanf(p, "%s%n", key_str, &n) != 1) {
if (assigned || undefined)
loaded++;
else {
skipped++;
asprintf(&msg,
_("No keys assigned to "
"\"%s\"."),
key_label);
io_log_print(log, line, msg);
mem_free(msg);
}
break;
}
p += n;
if (!strcmp(key_str, "UNDEFINED")) {
undefined++;
keys_assign_binding(-1, ht_elm->key);
} else if ((key = keys_str2int(key_str)) < 0) {
skipped++;
asprintf(&msg,
_("Keyname not recognized: \"%s\""),
key_str);
io_log_print(log, line, msg);
mem_free(msg);
} else if (keys_assign_binding(key, ht_elm->key)) {
skipped++;
asprintf(&msg,
_("\"%s\" assigned twice: \"%s\"."),
key_str, key_label);
io_log_print(log, line, msg);
mem_free(msg);
} else
assigned++;
}
}
file_close(keyfp, __FILE_POS__);
if (loaded < NBVKEYS && (i = keys_fill_missing()) < 1) {
skipped++;
strcpy(key_label, keys_get_label((enum vkey)(-i)));
strcpy(key_str, keys_get_binding((enum vkey)(-i)));
asprintf(&msg, _("Action \"%s\" absent, but default key \"%s\" "
"assigned to another action."),
key_label, key_str);
io_log_print(log, line, msg);
mem_free(msg);
}
file_close(log->fd, __FILE_POS__);
if (skipped > 0) {
msg = _("Errors in the keys file.");
io_log_display(log, msg, pager);
WARN_MSG(_("Remove offending line(s) from the keys file, "
"aborting..."));
exit_calcurse(EXIT_FAILURE);
}
io_log_free(log);
/* Default keys were inserted. */
if (loaded < NBVKEYS)
io_save_keys();
/* Should never occur. */
EXIT_IF(keys_check_missing(),
_("Some actions do not have any associated key bindings!"));
}
int io_check_dir(const char *dir)
{
if (read_only)
return -1;
char *path = mem_strdup(dir);
char *index;
int existed = 1, failed = 0;
errno = 0;
for (index = path + 1; *index; index++) {
if (*index == '/') {
*index = '\0';
if (mkdir(path, 0700) != 0) {
if (errno != EEXIST) {
failed = 1;
break;
}
} else {
existed = 0;
}
*index = '/';
}
}
if (!failed && mkdir(path, 0700) != 0) {
if (errno != EEXIST)
failed = 1;
} else {
existed = 0;
}
if(failed) {
fprintf(stderr,
_("FATAL ERROR: could not create %s: %s\n"),
path, strerror(errno));
exit_calcurse(EXIT_FAILURE);
}
mem_free(path);
return existed;
}
unsigned io_dir_exists(const char *path)
{
struct stat st;
return (!stat(path, &st) && S_ISDIR(st.st_mode));
}
unsigned io_file_exists(const char *file)
{
FILE *fd;
if (file && (fd = fopen(file, "r")) != NULL) {
fclose(fd);
return 1;
} else {
return 0;
}
}
int io_check_file(const char *file)
{
if (read_only)
return -1;
errno = 0;
if (io_file_exists(file)) {
return 1;
} else {
FILE *fd;
if ((fd = fopen(file, "w")) == NULL) {
fprintf(stderr,
_("FATAL ERROR: could not create %s: %s\n"),
file, strerror(errno));
exit_calcurse(EXIT_FAILURE);
}
file_close(fd, __FILE_POS__);
return 0;
}
}
/*
* Checks if data files exist. If not, create them.
* The following structure has to be created:
*
* <datadir> <configdir>
* | |
* |__ apts |___ conf
* |__ todo |___ keys
* |__ notes/ |___ hooks/
*
* Defaults:
* - datadir: $XDG_DATA_HOME/calcurse (~/.local/share/calcurse)
* - configdir: $XDG_CONFIG_HOME/calcurse (~/.config/calcurse)
*/
int io_check_data_files(void)
{
int missing = 0;
missing += io_check_dir(path_ddir) ? 0 : 1;
missing += io_check_dir(path_notes) ? 0 : 1;
missing += io_check_file(path_todo) ? 0 : 1;
missing += io_check_file(path_apts) ? 0 : 1;
missing += io_check_dir(path_cdir) ? 0 : 1;
missing += io_check_file(path_conf) ? 0 : 1;
missing += io_check_dir(path_hooks) ? 0 : 1;
if (!io_check_file(path_keys)) {
missing++;
keys_dump_defaults(path_keys);
}
return missing;
}
/* Export calcurse data. */
void io_export_data(enum export_type type, int export_uid)
{
FILE *stream = NULL;
const char *success = _("The data were successfully exported");
const char *enter = _("Press [ENTER] to continue");
if (type < IO_EXPORT_ICAL || type >= IO_EXPORT_NBTYPES)
EXIT(_("unknown export type"));
switch (ui_mode) {
case UI_CMDLINE:
stream = stdout;
break;
case UI_CURSES:
stream = get_export_stream(type);
break;
default:
EXIT(_("wrong export mode"));
/* NOTREACHED */
}
if (stream == NULL)
return;
if (type == IO_EXPORT_ICAL)
ical_export_data(stream, export_uid);
else if (type == IO_EXPORT_PCAL)
pcal_export_data(stream);
if (!quiet && ui_mode == UI_CURSES) {
fclose(stream);
status_mesg(success, enter);
keys_wait_for_any_key(win[KEY].p);
}
}
static FILE *get_import_stream(enum import_type type, char **stream_name)
{
FILE *stream = NULL;
const char *ask_fname =
_("Enter the file name to import data from:");
const char *wrong_file =
_("The file cannot be accessed, please enter another file name.");
const char *press_enter = _("Press [ENTER] to continue.");
*stream_name = mem_malloc(BUFSIZ);
memset(*stream_name, 0, BUFSIZ);
while (stream == NULL) {
status_mesg(ask_fname, "");
if (updatestring(win[STA].p, stream_name, 0, 1)) {
mem_free(*stream_name);
return NULL;
}
stream = fopen(*stream_name, "r");
if (stream == NULL) {
status_mesg(wrong_file, press_enter);
keys_wait_for_any_key(win[KEY].p);
}
}
return stream;
}
/*
* Import data from a given stream (either stdin in non-interactive mode, or the
* user given file in interactive mode).
* A temporary log file is created in /tmp to store the import process report,
* and is cleared at the end.
*/
int io_import_data(enum import_type type, char *stream_name,
const char *fmt_ev, const char *fmt_rev,
const char *fmt_apt, const char *fmt_rapt,
const char *fmt_todo)
{
const char *proc_report =
_("Import process report: %04d lines read");
char *stats_str[4];
FILE *stream = NULL;
struct io_file *log;
struct {
unsigned events, apoints, todos, lines, skipped;
} stats;
EXIT_IF(type < 0
|| type >= IO_IMPORT_NBTYPES, _("unknown import type"));
switch (ui_mode) {
case UI_CMDLINE:
if (!strcmp(stream_name, "-"))
stream = stdin;
else
stream = fopen(stream_name, "r");
EXIT_IF(stream == NULL,
_("FATAL ERROR: the input file cannot be accessed, "
"Aborting..."));
break;
case UI_CURSES:
stream = get_import_stream(type, &stream_name);
break;
default:
EXIT(_("FATAL ERROR: wrong import mode"));
/* NOTREACHED */
}
if (stream == NULL)
return 0;
memset(&stats, 0, sizeof stats);
log = io_log_init();
if (log == NULL) {
if (stream != stdin)
file_close(stream, __FILE_POS__);
return 0;
}
if (type == IO_IMPORT_ICAL)
ical_import_data(stream_name, stream, log->fd, &stats.events,
&stats.apoints, &stats.todos,
&stats.lines, &stats.skipped, fmt_ev, fmt_rev,
fmt_apt, fmt_rapt, fmt_todo);
if (stream != stdin)
file_close(stream, __FILE_POS__);
if (ui_mode == UI_CURSES &&
(stats.apoints > 0 || stats.events > 0 || stats.todos > 0))
io_set_modified();
asprintf(&stats_str[0], ngettext("%d app", "%d apps", stats.apoints),
stats.apoints);
asprintf(&stats_str[1],
ngettext("%d event", "%d events", stats.events),
stats.events);
asprintf(&stats_str[2], ngettext("%d todo", "%d todos", stats.todos),
stats.todos);
asprintf(&stats_str[3], _("%d skipped"), stats.skipped);
if (ui_mode == UI_CURSES && !quiet) {
char *read, *stat;
asprintf(&read, proc_report, stats.lines);
asprintf(&stat, "%s / %s / %s / %s (%s)",
stats_str[0], stats_str[1], stats_str[2],
stats_str[3], _("Press [ENTER] to continue"));
status_mesg(read, stat);
mem_free(read);
mem_free(stat);
keys_wait_for_any_key(win[KEY].p);
} else if (ui_mode == UI_CMDLINE && !quiet) {
printf(proc_report, stats.lines);
printf("\n%s / %s / %s / %s\n", stats_str[0], stats_str[1],
stats_str[2], stats_str[3]);
}
/* User has the choice to look at the log file if some items could not be
imported.
*/
file_close(log->fd, __FILE_POS__);
if (stats.skipped > 0) {
const char *view_log = _("Some items could not be imported.");
io_log_display(log, view_log, conf.pager);
}
mem_free(stats_str[0]);
mem_free(stats_str[1]);
mem_free(stats_str[2]);
mem_free(stats_str[3]);
if (ui_mode == UI_CURSES)
mem_free(stream_name);
if (!stats.skipped) {
io_log_free(log);
return 1;
} else
return 0;
}
struct io_file *io_log_init(void)
{
char *logprefix, *logname;
struct io_file *log = mem_malloc(sizeof(struct io_file));
if (!log) {
ERROR_MSG(_("Warning: could not open temporary log file, Aborting..."));
return NULL;
}
asprintf(&logprefix, "%s/calcurse_log", get_tempdir());
logname = new_tempfile(logprefix);
if (!logname) {
ERROR_MSG(_("Warning: could not create temporary log file, Aborting..."));
goto error;
}
log->name = mem_strdup(logname);
log->fd = fopen(log->name, "w");
if (log->fd == NULL) {
ERROR_MSG(_("Warning: could not open temporary log file, Aborting..."));
goto error;
}
goto cleanup;
error:
mem_free(log);
log = NULL;
cleanup:
mem_free(logprefix);
mem_free(logname);
return log;
}
void io_log_print(struct io_file *log, int line, const char *msg)
{
if (log && log->fd)
fprintf(log->fd, "line %d: %s\n", line, msg);
}
void io_log_display(struct io_file *log, const char *msg, const char *pager)
{
char *msgq;
RETURN_IF(log == NULL, _("No log file to display!"));
if (ui_mode == UI_CMDLINE) {
fprintf(stderr, "\n%s\n", msg);
fprintf(stderr, _("See %s for details."), log->name);
fputc('\n', stderr);
} else {
asprintf(&msgq, "%s %s", msg, _("Display log file?"));
if (status_ask_bool(msgq) == 1) {
const char *arg[] = { pager, log->name, NULL };
wins_launch_external(arg);
}
mem_free(msgq);
wins_erase_status_bar();
}
}
void io_log_free(struct io_file *log)
{
if (!log)
return;
EXIT_IF(unlink(log->name) != 0,
_("Warning: could not erase temporary log file %s, Aborting..."),
log->name);
mem_free(log->name);
mem_free(log);
}
/* Thread used to periodically save data. */
static void *io_psave_thread(void *arg)
{
int delay = conf.periodic_save;
EXIT_IF(delay < 0, _("Invalid delay"));
char *mesg = _("Periodic save cancelled. Data files have changed. "
"Save and merge interactively");
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
for (;;) {
sleep(delay * MININSEC);
pthread_mutex_lock(&io_periodic_save_mutex);
if (io_save_cal(periodic) == IO_SAVE_CANCEL)
que_ins(mesg, now(), 2);
pthread_mutex_unlock(&io_periodic_save_mutex);
}
}
/* Launch the thread which handles periodic saves. */
void io_start_psave_thread(void)
{
pthread_create(&io_t_psave, NULL, io_psave_thread, NULL);
}
/* Stop periodic data saves. */
void io_stop_psave_thread(void)
{
/* Is the thread running? */
if (pthread_equal(io_t_psave, pthread_self()))
return;
/* Lock the mutex to avoid cancelling the thread during saving. */
pthread_mutex_lock(&io_periodic_save_mutex);
pthread_cancel(io_t_psave);
pthread_join(io_t_psave, NULL);
pthread_mutex_unlock(&io_periodic_save_mutex);
io_t_psave = pthread_self();
}
/*
* This sets a lock file to prevent from having two different instances of
* calcurse running.
*
* If the lock cannot be obtained, then warn the user and exit calcurse. Else,
* create a .calcurse.pid file in the user defined directory, which will be
* removed when calcurse exits.
*
* Note: When creating the lock file, the interactive mode is not initialized
* yet.
*/
void io_set_lock(void)
{
FILE *lock = fopen(path_cpid, "r");
int pid;
if (lock != NULL) {
/* If there is a lock file, check whether the process exists. */
if (fscanf(lock, "%d", &pid) == 1) {
fclose(lock);
if (kill(pid, 0) != 0 && errno == ESRCH)
lock = NULL;
} else {
fclose(lock);
}
}
if (lock != NULL) {
fprintf(stderr,
_("\nWARNING: it seems that another calcurse instance is "
"already running.\n"
"If this is not the case, please remove the following "
"lock file: \n\"%s\"\n"
"and restart calcurse.\n"), path_cpid);
exit(EXIT_FAILURE);
}
if (!io_dump_pid(path_cpid))
EXIT(_("FATAL ERROR: could not create %s: %s\n"),
path_cpid, strerror(errno));
}
/*
* Create a new file and write the process pid inside (used to create a simple
* lock for example). Overwrite already existing files.
*/
unsigned io_dump_pid(char *file)
{
pid_t pid;
FILE *fp;
if (!file)
return 0;
pid = getpid();
if (!(fp = fopen(file, "w"))
|| fprintf(fp, "%ld\n", (long)pid) < 0 || fclose(fp) != 0)
return 0;
return 1;
}
/*
* Return the pid number contained in a file previously created with
* io_dump_pid ().
* If no file was found, return 0.
*/
unsigned io_get_pid(char *file)
{
FILE *fp;
unsigned pid;
if (!file)
return 0;
if ((fp = fopen(file, "r")) == NULL)
return 0;
if (fscanf(fp, "%u", &pid) != 1)
return 0;
fclose(fp);
return pid;
}
/*
* Check whether two files are equal.
*/
int io_files_equal(const char *file1, const char *file2)
{
FILE *fp1, *fp2;
int ret = 0;
if (!file1 || !file2)
return 0;
fp1 = fopen(file1, "rb");
fp2 = fopen(file2, "rb");
while (!feof(fp1) && !feof(fp2)) {
if (fgetc(fp1) != fgetc(fp2))
goto cleanup;
}
ret = 1;
cleanup:
fclose(fp1);
fclose(fp2);
return ret;
}
/*
* Copy an existing file to a new location.
*/
int io_file_cp(const char *src, const char *dst)
{
FILE *fp_src, *fp_dst;
char *buffer[BUFSIZ];
unsigned int bytes_read;
if (!(fp_src = fopen(src, "rb")))
return 0;
if (!(fp_dst = fopen(dst, "wb")))
return 0;
while (!feof(fp_src)) {
bytes_read = fread(buffer, 1, BUFSIZ, fp_src);
if (bytes_read > 0) {
if (fwrite(buffer, 1, bytes_read, fp_dst) !=
bytes_read)
return 0;
} else {
return 0;
}
}
fclose(fp_dst);
fclose(fp_src);
return 1;
}
void io_unset_modified(void)
{
modified = 0;
}
void io_set_modified(void)
{
modified = 1;
}
int io_get_modified(void)
{
return modified;
}
|
BioBox/calcurse
|
src/llist.c
|
/*
* Calcurse - text-based organizer
*
* Copyright (c) 2004-2020 calcurse Development Team <<EMAIL>>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Send your feedback or comments to : <EMAIL>
* Calcurse home page : http://calcurse.org
*
*/
#include "calcurse.h"
/*
* Initialize a list.
*/
void llist_init(llist_t * l)
{
l->head = NULL;
l->tail = NULL;
}
/*
* Free a list, but not the contained data.
*/
void llist_free(llist_t * l)
{
llist_item_t *i, *t;
for (i = l->head; i; i = t) {
t = i->next;
mem_free(i);
}
l->head = NULL;
l->tail = NULL;
}
/*
* Free the data contained in a list.
*/
void llist_free_inner(llist_t * l, llist_fn_free_t fn_free)
{
llist_item_t *i;
for (i = l->head; i; i = i->next) {
if (i->data) {
fn_free(i->data);
i->data = NULL;
}
}
}
/*
* Get the first item of a list.
*/
llist_item_t *llist_first(llist_t * l)
{
return l->head;
}
/*
* Get the nth item of a list.
*/
llist_item_t *llist_nth(llist_t * l, int n)
{
llist_item_t *i;
if (n < 0)
return NULL;
for (i = l->head; i && n != 0; n--)
i = i->next;
return i;
}
/*
* Get the successor of a list item.
*/
llist_item_t *llist_next(llist_item_t * i)
{
return i ? i->next : NULL;
}
/*
* Return the predecessor of a list item or, if head, the list item itself,
* or if not in the list, NULL.
* The list item may be supplied either directly (i) or as a pointer to
* the contents (data); the first case takes precedence.
*/
static llist_item_t *llist_prev(llist_t *l, llist_item_t *i, void *data)
{
llist_item_t *j;
if (!i && !data)
return NULL;
if (l->head == i || l->head->data == data)
return l->head;
if (i) {
for (j = l->head; j; j = j->next)
if (j->next == i)
return j;
} else {
for (j = l->head; j && j->next; j = j->next)
if (j->next->data == data)
return j;
}
return NULL;
}
/*
* Return the successor of a list item if it is matched by some filter
* callback. Return NULL otherwise.
*/
llist_item_t *llist_next_filter(llist_item_t * i, void *data,
llist_fn_match_t fn_match)
{
if (i && i->next && fn_match(i->next->data, data))
return i->next;
else
return NULL;
}
/*
* Get the actual data of an item.
*/
void *llist_get_data(llist_item_t * i)
{
return i ? i->data : NULL;
}
/*
* Add an item at the end of a list.
*/
void llist_add(llist_t * l, void *data)
{
llist_item_t *o = mem_malloc(sizeof(llist_item_t));
if (o) {
o->data = data;
o->next = NULL;
if (!l->head) {
l->head = l->tail = o;
} else {
l->tail->next = o;
l->tail = o;
}
}
}
/*
* Insert an existing item in a sorted list.
*/
static void llist_relink(llist_t *l, llist_item_t *i, llist_fn_cmp_t fn_cmp)
{
llist_item_t *j;
if (!i)
return;
i->next = NULL;
if (!l->head) {
l->head = l->tail = i;
} else if (fn_cmp(i->data, l->tail->data) >= 0) {
l->tail->next = i;
l->tail = i;
} else if (fn_cmp(i->data, l->head->data) < 0) {
i->next = l->head;
l->head = i;
} else {
j = l->head;
while (j->next && fn_cmp(i->data, j->next->data) >= 0)
j = j->next;
i->next = j->next;
j->next = i;
}
}
/*
* Unlink an item from a list and return it.
*/
static llist_item_t *llist_unlink(llist_t *l, llist_item_t *i)
{
llist_item_t *p;
if (!i)
return NULL;
p = llist_prev(l, i, NULL);
if (!p)
return NULL;
if (i == l->tail)
l->tail = (i == l->head) ? NULL : p;
if (i == l->head)
l->head = i->next;
else
p->next = i->next;
i->next = NULL;
return i;
}
/*
* Find an item matched by some filter callback; start from a specified item.
*/
static llist_item_t *llist_find_from(llist_item_t *i, void *data,
llist_fn_match_t fn_match)
{
if (!i)
return NULL;
if (fn_match) {
for (; i; i = i->next) {
if (fn_match(i->data, data))
return i;
}
} else {
for (; i; i = i->next) {
if (i->data == data)
return i;
}
}
return NULL;
}
/*
* Add an item to a sorted list.
*/
void llist_add_sorted(llist_t * l, void *data, llist_fn_cmp_t fn_cmp)
{
llist_item_t *o = mem_malloc(sizeof(llist_item_t));
if (o) {
o->data = data;
o->next = NULL;
}
llist_relink(l, o, fn_cmp);
}
/*
* Remove an item from a list.
*/
void llist_remove(llist_t * l, llist_item_t * i)
{
llist_item_t *j = NULL;
if (l->head && i == l->head) {
l->head = i->next;
} else {
for (j = l->head; j && j->next != i; j = j->next) ;
}
if (i) {
if (j)
j->next = i->next;
if (i == l->tail)
l->tail = j;
mem_free(i);
}
}
/*
* Find the first item matched by some filter callback.
*/
llist_item_t *llist_find_first(llist_t * l, void *data,
llist_fn_match_t fn_match)
{
return l ? llist_find_from(l->head, data, fn_match) : NULL;
}
/*
* Find the next item matched by some filter callback.
*/
llist_item_t *llist_find_next(llist_item_t * i, void *data,
llist_fn_match_t fn_match)
{
return i ? llist_find_from(i->next, data, fn_match) : NULL;
}
/*
* Find the nth item matched by some filter callback.
*/
llist_item_t *llist_find_nth(llist_t * l, int n, void *data,
llist_fn_match_t fn_match)
{
llist_item_t *i;
if (n < 0)
return NULL;
for (i = l->head; i; i = i->next, n--) {
i = llist_find_from(i, data, fn_match);
if (!i || !n)
return i;
}
return NULL;
}
/*
* Reorder a sorted linked list when an item has changed.
*/
void llist_reorder(llist_t *l, void *data, llist_fn_cmp_t fn_cmp)
{
llist_item_t *o, *p;
if (!(p = llist_prev(l, NULL, data)))
return;
/* List head? */
if (p->data == data)
o = p;
else
o = p->next;
/* Sorted already?
* Note: p is either the previous element or o itself.
*/
if (o->next &&
fn_cmp(p->data, o->data) <= 0 &&
fn_cmp(o->data, o->next->data) <= 0)
return;
if (!o->next &&
fn_cmp(p->data, o->data) <= 0)
return;
/* Link manipulation only. */
llist_relink(l, llist_unlink(l, o), fn_cmp);
}
|
BioBox/calcurse
|
src/ui-calendar.c
|
<filename>src/ui-calendar.c
/*
* Calcurse - text-based organizer
*
* Copyright (c) 2004-2020 calcurse Development Team <<EMAIL>>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Send your feedback or comments to : <EMAIL>
* Calcurse home page : http://calcurse.org
*
*/
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <math.h>
#include <langinfo.h>
#include "calcurse.h"
static struct date today, slctd_day;
static unsigned ui_calendar_view;
static int wday_start; /* this is used in signed arithmetic */
static pthread_mutex_t date_thread_mutex = PTHREAD_MUTEX_INITIALIZER;
static void draw_monthly_view(struct scrollwin *, struct date *);
static void draw_weekly_view(struct scrollwin *, struct date *);
static void (*draw_calendar[CAL_VIEWS]) (struct scrollwin *,
struct date *) = {draw_monthly_view, draw_weekly_view};
/* Six weeks cover a month. */
static int monthly_view_cache[WEEKINDAYS * 6];
static int monthly_view_cache_valid = 0;
static int monthly_view_cache_month = 0;
/* Switch between calendar views (monthly view is selected by default). */
void ui_calendar_view_next(void)
{
ui_calendar_view++;
if (ui_calendar_view == CAL_VIEWS)
ui_calendar_view = 0;
}
void ui_calendar_view_prev(void)
{
if (ui_calendar_view == 0)
ui_calendar_view = CAL_VIEWS;
ui_calendar_view--;
}
void ui_calendar_set_view(int view)
{
ui_calendar_view = (view < 0
|| view >= CAL_VIEWS) ? CAL_MONTH_VIEW : view;
}
int ui_calendar_get_view(void)
{
return (int)ui_calendar_view;
}
/* Thread needed to update current date in calendar. */
/* ARGSUSED0 */
static void *ui_calendar_date_thread(void *arg)
{
time_t actual, tomorrow;
for (;;) {
tomorrow = date2sec(today, 24, 0);
while ((actual = time(NULL)) < tomorrow)
sleep(tomorrow - actual);
ui_calendar_set_current_date();
ui_calendar_update_panel();
}
return NULL;
}
/* Launch the calendar date thread. */
void ui_calendar_start_date_thread(void)
{
pthread_create(&ui_calendar_t_date, NULL, ui_calendar_date_thread,
NULL);
}
/* Stop the calendar date thread. */
void ui_calendar_stop_date_thread(void)
{
/* Is the thread running? */
if (pthread_equal(ui_calendar_t_date, pthread_self()))
return;
pthread_cancel(ui_calendar_t_date);
pthread_join(ui_calendar_t_date, NULL);
ui_calendar_t_date = pthread_self();
}
/* Set static variable today to current date */
void ui_calendar_set_current_date(void)
{
time_t timer;
struct tm tm;
timer = time(NULL);
localtime_r(&timer, &tm);
pthread_mutex_lock(&date_thread_mutex);
today.dd = tm.tm_mday;
today.mm = tm.tm_mon + 1;
today.yyyy = tm.tm_year + 1900;
pthread_mutex_unlock(&date_thread_mutex);
}
/* Return the current date. */
struct date *ui_calendar_get_today(void)
{
return &today;
}
/* Needed to display sunday or monday as the first day of week in calendar. */
void ui_calendar_set_first_day_of_week(enum wday first_day)
{
if (first_day >= 0 && first_day <= 6)
wday_start = first_day;
else {
ERROR_MSG(_("ERROR setting first day of week"));
wday_start = 0;
}
}
/* Swap first day of week in calendar. */
void ui_calendar_change_first_day_of_week(void)
{
wday_start++;
if(wday_start >= WEEKINDAYS)
wday_start = 0;
}
/* Return 1 if week begins on monday, 0 otherwise. */
int ui_calendar_get_wday_start(void)
{
return wday_start;
}
/* Fill in the given variable with the current date. */
void ui_calendar_store_current_date(struct date *date)
{
pthread_mutex_lock(&date_thread_mutex);
*date = today;
pthread_mutex_unlock(&date_thread_mutex);
}
/* This is to start at the current date in calendar. */
void ui_calendar_init_slctd_day(void)
{
ui_calendar_store_current_date(&slctd_day);
}
/* Return the selected day in calendar */
struct date *ui_calendar_get_slctd_day(void)
{
return &slctd_day;
}
static int ui_calendar_get_wday(struct date *date)
{
struct tm t;
memset(&t, 0, sizeof(struct tm));
t.tm_mday = date->dd;
t.tm_mon = date->mm - 1;
t.tm_year = date->yyyy - 1900;
mktime(&t);
return t.tm_wday;
}
/* Set the selected day in the calendar. */
void ui_calendar_set_slctd_day(struct date day)
{
slctd_day = day;
}
void ui_calendar_monthly_view_cache_set_invalid(void)
{
monthly_view_cache_valid = 0;
}
static int weeknum(const struct tm *t, int wday_start)
{
int wday, wnum;
wday = t->tm_wday;
wnum = ((t->tm_yday + WEEKINDAYS + -modify_wday(wday, -wday_start))
/ WEEKINDAYS);
if (wnum < 0)
wnum = 0;
return wnum;
}
/*
* Compute the week number according to ISO 8601.
*/
static int ISO8601weeknum(const struct tm *t)
{
int wnum, jan1day;
wnum = weeknum(t, MONDAY);
jan1day = t->tm_wday - (t->tm_yday % WEEKINDAYS);
if (jan1day < 0)
jan1day += WEEKINDAYS;
switch (jan1day) {
case MONDAY:
break;
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
wnum++;
break;
case FRIDAY:
case SATURDAY:
case SUNDAY:
if (wnum == 0) {
/* Get week number of last week of last year. */
struct tm dec31ly; /* 12/31 last year */
dec31ly = *t;
dec31ly.tm_year--;
dec31ly.tm_mon = 11;
dec31ly.tm_mday = 31;
dec31ly.tm_wday =
(jan1day == SUNDAY) ? 6 : jan1day - 1;
dec31ly.tm_yday =
364 + ISLEAP(dec31ly.tm_year + 1900);
wnum = ISO8601weeknum(&dec31ly);
}
break;
}
if (t->tm_mon == 11) {
int wday, mday;
wday = t->tm_wday;
mday = t->tm_mday;
if ((wday == MONDAY && (mday >= 29 && mday <= 31))
|| (wday == TUESDAY && (mday == 30 || mday == 31))
|| (wday == WEDNESDAY && mday == 31))
wnum = 1;
}
return wnum;
}
/*
* Return the tm structure for the first day of the first week
* (containing a day) of the selected month.
*/
static struct tm get_first_day(int wday_start)
{
struct tm t;
struct date d;
d = slctd_day;
/* get the first day of the month */
d.dd = 1;
t = date2tm(d, 0, 0);
mktime(&t);
/* get the first day of the week */
date_change(&t, 0, -modify_wday(t.tm_wday, -wday_start));
return t;
}
static struct tm get_first_weekday(int wday_start)
{
int c_wday;
struct tm t;
c_wday = ui_calendar_get_wday(&slctd_day);
t = date2tm(slctd_day, 0, 0);
date_change(&t, 0, -modify_wday(c_wday, -wday_start));
return t;
}
static void draw_week_number(struct scrollwin *sw, struct tm t)
{
int weeknum = ISO8601weeknum(&t);
WINS_CALENDAR_LOCK;
custom_apply_attr(sw->win, ATTR_HIGHEST);
mvwprintw(sw->win, conf.compact_panels ? 0 : 2, sw->w - 9,
"(# %02d)", weeknum);
custom_remove_attr(sw->win, ATTR_HIGHEST);
WINS_CALENDAR_UNLOCK;
}
/* Draw the monthly view inside calendar panel. */
static void
draw_monthly_view(struct scrollwin *sw, struct date *current_day)
{
struct date c_day;
int slctd, w_day, numdays, j, week = 0;
unsigned yr, mo;
int w, monthw, weekw, dayw, ofs_x, ofs_y;
struct tm t, t_first;
char *cp;
char bo, bc;
unsigned attr, day_attr;
int first_day, last_day;
werase(sw->inner);
/*
* number of days to display
*/
first_day = last_day = 0;
/* days in the selected month */
numdays = days[slctd_day.mm - 1];
if (2 == slctd_day.mm && ISLEAP(slctd_day.yyyy))
++numdays;
/*
* Step forward by week until past the last day of the month.
* The first day of the first week may belong to the previous month.
*/
t = t_first = get_first_day(wday_start);
t.tm_mday += WEEKINDAYS;
mktime(&t);
last_day += WEEKINDAYS;
/* following weeks */
for (j = t.tm_mday; j <= numdays; j += WEEKINDAYS )
last_day += WEEKINDAYS;
mo = slctd_day.mm;
yr = slctd_day.yyyy;
/* a week column plus seven day columns */
weekw = 3;
dayw = 4;
monthw = weekw + 7 * dayw;
/* offset for centering calendar in window */
w = wins_sbar_width() - 2;
ofs_y = 0;
ofs_x = (w - monthw) / 2 + ((w - monthw) % 2);
/* invalidate cache if a new month is selected */
if (yr * YEARINMONTHS + mo != monthly_view_cache_month) {
monthly_view_cache_month = yr * YEARINMONTHS + mo;
monthly_view_cache_valid = 0;
}
WINS_CALENDAR_LOCK;
/* Print the day number. */
t = date2tm(slctd_day, 0, 0);
mktime(&t);
custom_apply_attr(sw->win, ATTR_HIGHEST);
mvwprintw(sw->win, conf.compact_panels ? 0 : 2,
ofs_x + monthw - 6,
"(#%3d)", t.tm_yday + 1);
custom_remove_attr(sw->win, ATTR_HIGHEST);
/* Write the current month and year on top of the calendar */
custom_apply_attr(sw->inner, ATTR_HIGHEST);
cp = nl_langinfo(MON_1 + mo - 1);
mvwprintw(sw->inner, ofs_y, (w - (strlen(cp) + 5)) / 2,
"%s %d", cp, slctd_day.yyyy);
custom_remove_attr(sw->inner, ATTR_HIGHEST);
++ofs_y;
/* print the days with regard to the first day of the week */
custom_apply_attr(sw->inner, ATTR_HIGHEST);
for (j = 0; j < WEEKINDAYS; j++) {
mvwaddstr(sw->inner, ofs_y, ofs_x + weekw + 4 * j,
nl_langinfo(ABDAY_1 + modify_wday(j, wday_start)));
}
custom_remove_attr(sw->inner, ATTR_HIGHEST);
WINS_CALENDAR_UNLOCK;
++ofs_y;
/* print the dates */
for (j = first_day, t = t_first, w_day = 0;
j < last_day;
j++, date_change(&t, 0, 1), w_day++, w_day %= WEEKINDAYS) {
c_day.dd = t.tm_mday;
c_day.mm = t.tm_mon + 1;
c_day.yyyy = t.tm_year + 1900;
slctd = !date_cmp(&c_day, &slctd_day);
/* Next line, week over. */
if (!w_day && j != first_day)
ofs_y++;
/* Week number, beware of first and last week of the year. */
if (!w_day) {
if (j == first_day ||
(mo == 1 && j == WEEKINDAYS) ||
(mo == 12 && j >= 4 * WEEKINDAYS)) {
date_change(&t, 0, WDAY(MONDAY));
week = ISO8601weeknum(&t);
date_change(&t, 0, -WDAY(MONDAY));
} else
week++;
}
/* Brackets for the selected day. */
bo = slctd ? '[' : ' ';
bc = slctd ? ']' : ' ';
/* check if the day contains an event or an appointment */
if (monthly_view_cache_valid) {
day_attr = monthly_view_cache[j];
} else {
day_attr = monthly_view_cache[j] =
day_check_if_item(c_day);
}
/* Set day colours. */
if (date_cmp(&c_day, current_day) == 0)
attr = ATTR_LOWEST;
else
attr = day_attr;
WINS_CALENDAR_LOCK;
/* Print week number. */
if (!w_day) {
custom_apply_attr(sw->inner, ATTR_HIGHEST);
mvwprintw(sw->inner, ofs_y, ofs_x, "%2d", week);
custom_remove_attr(sw->inner, ATTR_HIGHEST);
}
/* Print date with attributes.*/
if (attr)
custom_apply_attr(sw->inner, attr);
mvwprintw(sw->inner, ofs_y, ofs_x + weekw + w_day * 4,
"%c%2d%c", bo, c_day.dd, bc);
if (attr)
custom_remove_attr(sw->inner, attr);
/* Colour the brackets. */
if (slctd) {
mvwchgat(sw->inner, ofs_y, ofs_x + weekw + w_day * 4,
1, A_BOLD,
(colorize ? (COLR_RED | A_BOLD) : 0), NULL);
mvwchgat(sw->inner, ofs_y, ofs_x + weekw + 3 + w_day * 4,
1, A_BOLD,
(colorize ? (COLR_RED | A_BOLD) : 0), NULL);
}
WINS_CALENDAR_UNLOCK;
}
monthly_view_cache_valid = 1;
}
/* Draw the weekly view inside calendar panel. */
static void
draw_weekly_view(struct scrollwin *sw, struct date *current_day)
{
#define DAYSLICESNO 6
const int WCALWIDTH = 28;
struct tm t;
int OFFY, OFFX, j;
werase(sw->inner);
OFFY = 0;
OFFX = (wins_sbar_width() - 2 - WCALWIDTH) / 2;
/* Print the week number, calculated from monday. */
t = get_first_weekday(MONDAY);
draw_week_number(sw, t);
/* Now draw calendar view. */
for (j = 0; j < WEEKINDAYS; j++) {
/* get next day */
if (j == 0)
t = get_first_weekday(wday_start);
else
date_change(&t, 0, 1);
struct date date;
unsigned attr, item_this_day;
int i, slices[DAYSLICESNO];
/* print the day names, with regards to the first day of the week */
custom_apply_attr(sw->inner, ATTR_HIGHEST);
mvwaddstr(sw->inner, OFFY, OFFX + 4 * j,
nl_langinfo(ABDAY_1 + modify_wday(j, wday_start)));
custom_remove_attr(sw->inner, ATTR_HIGHEST);
/* Check if the day to be printed has an item or not. */
date.dd = t.tm_mday;
date.mm = t.tm_mon + 1;
date.yyyy = t.tm_year + 1900;
item_this_day = day_check_if_item(date);
/* Print the day numbers with appropriate decoration. */
if (t.tm_mday == current_day->dd
&& current_day->mm == slctd_day.mm
&& current_day->yyyy == slctd_day.yyyy
&& current_day->dd != slctd_day.dd)
attr = ATTR_LOWEST;
else if (t.tm_mday == slctd_day.dd)
attr = ATTR_MIDDLE;
else if (item_this_day == 1)
attr = ATTR_LOW;
else if (item_this_day == 2)
attr = ATTR_TRUE;
else
attr = 0;
WINS_CALENDAR_LOCK;
if (attr)
custom_apply_attr(sw->inner, attr);
mvwprintw(sw->inner, OFFY + 1, OFFX + 1 + 4 * j, "%02d",
t.tm_mday);
if (attr)
custom_remove_attr(sw->inner, attr);
WINS_CALENDAR_UNLOCK;
/* Draw slices indicating appointment times. */
memset(slices, 0, DAYSLICESNO * sizeof *slices);
if (day_chk_busy_slices(date, DAYSLICESNO, slices)) {
for (i = 0; i < DAYSLICESNO; i++) {
if (j != WEEKINDAYS - 1
&& i != DAYSLICESNO - 1) {
WINS_CALENDAR_LOCK;
mvwhline(sw->inner, OFFY + 2 + i,
OFFX + 3 + 4 * j, ACS_S9,
2);
WINS_CALENDAR_UNLOCK;
}
if (slices[i]) {
int highlight;
highlight =
(t.tm_mday ==
slctd_day.dd) ? 1 : 0;
WINS_CALENDAR_LOCK;
if (highlight)
custom_apply_attr(sw->inner,
attr);
wattron(sw->inner, A_REVERSE);
mvwaddstr(sw->inner, OFFY + 2 + i,
OFFX + 1 + 4 * j, " ");
mvwaddstr(sw->inner, OFFY + 2 + i,
OFFX + 2 + 4 * j, " ");
wattroff(sw->inner, A_REVERSE);
if (highlight)
custom_remove_attr(sw->inner,
attr);
WINS_CALENDAR_UNLOCK;
}
}
}
}
/* Draw marks to indicate midday on the sides of the calendar. */
WINS_CALENDAR_LOCK;
custom_apply_attr(sw->inner, ATTR_HIGHEST);
mvwhline(sw->inner, OFFY + 1 + DAYSLICESNO / 2, OFFX, ACS_S9, 1);
mvwhline(sw->inner, OFFY + 1 + DAYSLICESNO / 2,
OFFX + WCALWIDTH - 1, ACS_S9, 1);
custom_remove_attr(sw->inner, ATTR_HIGHEST);
WINS_CALENDAR_UNLOCK;
#undef DAYSLICESNO
}
/* Function used to display the calendar panel. */
void ui_calendar_update_panel(void)
{
struct date current_day;
ui_calendar_store_current_date(¤t_day);
draw_calendar[ui_calendar_view] (&sw_cal, ¤t_day);
wins_scrollwin_display(&sw_cal, NOHILT);
}
/* Set the selected day in calendar to current day. */
void ui_calendar_goto_today(void)
{
struct date today;
ui_calendar_store_current_date(&today);
slctd_day.dd = today.dd;
slctd_day.mm = today.mm;
slctd_day.yyyy = today.yyyy;
}
/*
* Ask for a date to jump to, then check the correctness of that date
* and jump to it.
* If the entered date is empty, automatically jump to the current date.
* slctd_day is updated with the newly selected date.
*/
void ui_calendar_change_day(int datefmt)
{
#define LDAY 11
char selected_day[LDAY] = "";
char *outstr;
int dday, dmonth, dyear;
int wrong_day = 1;
const char *mesg_line1 = _("The day you entered is not valid");
const char *mesg_line2 = _("Press [ENTER] to continue");
const char *request_date =
_("Enter the day to go to [ENTER for today] : %s");
while (wrong_day) {
asprintf(&outstr, request_date, DATEFMT_DESC(datefmt));
status_mesg(outstr, "");
mem_free(outstr);
if (getstring(win[STA].p, selected_day, LDAY, 0, 1) ==
GETSTRING_ESC) {
return;
} else {
if (strlen(selected_day) == 0) {
wrong_day = 0;
ui_calendar_goto_today();
} else
if (parse_date
(selected_day, datefmt, &dyear, &dmonth,
&dday, ui_calendar_get_slctd_day())) {
wrong_day = 0;
/* go to chosen day */
slctd_day.dd = dday;
slctd_day.mm = dmonth;
slctd_day.yyyy = dyear;
}
if (wrong_day) {
status_mesg(mesg_line1, mesg_line2);
keys_wait_for_any_key(win[KEY].p);
}
}
}
return;
}
void ui_calendar_move(enum move move, int count)
{
int ret, days_to_remove, days_to_add;
struct tm t;
memset(&t, 0, sizeof(struct tm));
t.tm_mday = slctd_day.dd;
t.tm_mon = slctd_day.mm - 1;
t.tm_year = slctd_day.yyyy - 1900;
switch (move) {
case DAY_PREV:
ret = date_change(&t, 0, -count);
break;
case DAY_NEXT:
ret = date_change(&t, 0, count);
break;
case WEEK_PREV:
ret = date_change(&t, 0, -count * WEEKINDAYS);
break;
case WEEK_NEXT:
ret = date_change(&t, 0, count * WEEKINDAYS);
break;
case MONTH_PREV:
ret = date_change(&t, -count, 0);
break;
case MONTH_NEXT:
ret = date_change(&t, count, 0);
break;
case YEAR_PREV:
ret = date_change(&t, -count * YEARINMONTHS, 0);
break;
case YEAR_NEXT:
ret = date_change(&t, count * YEARINMONTHS, 0);
break;
case WEEK_START:
mktime(&t);
days_to_remove = WDAY(t.tm_wday);
days_to_remove += (count - 1) * WEEKINDAYS;
ret = date_change(&t, 0, -days_to_remove);
break;
case WEEK_END:
mktime(&t);
days_to_add = modify_wday(-t.tm_wday, wday_start - 1);
days_to_add += (count - 1) * WEEKINDAYS;
ret = date_change(&t, 0, days_to_add);
break;
default:
ret = 1;
/* NOTREACHED */
}
if (ret || !check_date(t.tm_year + 1900, t.tm_mon + 1, t.tm_mday)) {
char *out, *msg = _("The move failed (%d/%d/%d)."), ch;
asprintf(&out, msg, t.tm_mday, t.tm_mon + 1, t.tm_year + 1900);
do {
status_mesg(out, _("Press [ENTER] to continue"));
ch = keys_wgetch(win[KEY].p);
} while (ch != '\n');
mem_free(out);
wins_update(FLAG_STA);
if (t.tm_year < 2) {
t.tm_mday = 1;
t.tm_mon = 0;
t.tm_year = 2;
}
if (t.tm_year > 137) {
t.tm_mday = 31;
t.tm_mon = 11;
t.tm_year = 137;
}
}
slctd_day.dd = t.tm_mday;
slctd_day.mm = t.tm_mon + 1;
slctd_day.yyyy = t.tm_year + 1900;
}
/* Returns the beginning of current year as a long. */
time_t ui_calendar_start_of_year(void)
{
time_t timer;
struct tm tm;
timer = time(NULL);
localtime_r(&timer, &tm);
tm.tm_mon = 0;
tm.tm_mday = 1;
tm.tm_hour = 0;
tm.tm_min = 0;
tm.tm_sec = 0;
timer = mktime(&tm);
return timer;
}
time_t ui_calendar_end_of_year(void)
{
time_t timer;
struct tm tm;
timer = time(NULL);
localtime_r(&timer, &tm);
tm.tm_mon = 0;
tm.tm_mday = 1;
tm.tm_hour = 0;
tm.tm_min = 0;
tm.tm_sec = 0;
tm.tm_year++;
timer = mktime(&tm);
return (timer - 1);
}
|
BioBox/calcurse
|
src/queue.c
|
<reponame>BioBox/calcurse
/*
* Calcurse - text-based organizer
*
* Copyright (c) 2004-2020 calcurse Development Team <<EMAIL>>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Send your feedback or comments to : <EMAIL>
* Calcurse home page : http://calcurse.org
*
*/
#include "calcurse.h"
/*
* A queue for calcurse system messages.
*/
llist_t sysqueue;
static pthread_mutex_t que_mutex = PTHREAD_MUTEX_INITIALIZER;
void que_init(void)
{
LLIST_INIT(&sysqueue);
}
/*
* Test for queued system events.
*/
int que_ued(void)
{
return sysqueue.head ? 1 : 0;
}
/*
* Insert a system event at the tail of the queue.
*/
struct event *que_ins(char *mesg, time_t time, int id)
{
struct event *ev;
ev = mem_malloc(sizeof(struct event));
ev->mesg = mem_strdup(mesg);
ev->day = time;
ev->id = id;
ev->note = NULL;
pthread_mutex_lock(&que_mutex);
LLIST_ADD(&sysqueue, ev);
pthread_mutex_unlock(&que_mutex);
return ev;
}
/*
* Get the system event at the head of the queue.
*/
struct event *que_get(void)
{
return sysqueue.head ? sysqueue.head->data : NULL;
}
/*
* Remove the system event at the head of the queue.
*/
void que_rem(void)
{
struct event *ev;
if (!sysqueue.head)
return;
ev = sysqueue.head->data;
pthread_mutex_lock(&que_mutex);
LLIST_REMOVE(&sysqueue, sysqueue.head);
pthread_mutex_unlock(&que_mutex);
mem_free(ev->mesg);
mem_free(ev);
}
/*
* Display the system event at the head of the queue in a popup window.
*/
void que_show(void)
{
struct event *ev;
char *date;
if (!que_ued())
return;
ev = que_get();
date = date_sec2date_str(ev->day, "%F %T");
item_in_popup(date, "", ev->mesg, _("System event"));
mem_free(date);
}
/*
* Save the system event at the head of the queue as an appointment.
*/
void que_save(void)
{
struct event *ev;
if (!que_ued())
return;
ev = que_get();
apoint_new(ev->mesg, NULL, ev->day, 0, APOINT_NULL);
io_set_modified();
}
|
BioBox/calcurse
|
src/ui-todo.c
|
<filename>src/ui-todo.c<gh_stars>100-1000
/*
* Calcurse - text-based organizer
*
* Copyright (c) 2004-2020 calcurse Development Team <<EMAIL>>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Send your feedback or comments to : <EMAIL>
* Calcurse home page : http://calcurse.org
*
*/
#include "calcurse.h"
#include <ctype.h>
static unsigned ui_todo_view = 0;
static struct todo *ui_todo_selitem(void)
{
return todo_get_item(listbox_get_sel(&lb_todo),
ui_todo_view == TODO_HIDE_COMPLETED_VIEW);
}
static void ui_todo_set_selitem(struct todo *todo)
{
int n = todo_get_position(todo,
ui_todo_view == TODO_HIDE_COMPLETED_VIEW);
if (n >= 0)
listbox_set_sel(&lb_todo, n);
}
/* Request user to enter a new todo item. */
void ui_todo_add(void)
{
int ch;
const char *mesg = _("Enter the new TODO item:");
const char *mesg_id =
_("Enter the TODO priority [0 (none), 1 (highest) - 9 (lowest)]:");
char todo_input[BUFSIZ] = "";
status_mesg(mesg, "");
if (getstring(win[STA].p, todo_input, BUFSIZ, 0, 1) ==
GETSTRING_VALID) {
do {
status_mesg(mesg_id, "");
ch = keys_wgetch(win[KEY].p);
if (ch == RETURN)
ch = '0';
else if (ch == ESCAPE)
return;
} while (!isdigit(ch));
struct todo *todo = todo_add(todo_input, ch - '0', 0, NULL);
ui_todo_load_items();
io_set_modified();
ui_todo_set_selitem(todo);
}
}
/* Delete an item from the TODO list. */
void ui_todo_delete(void)
{
const char *del_todo_str =
_("Do you really want to delete this task?");
const char *erase_warning =
_("This item has a note attached to it. "
"Delete (t)odo or just its (n)ote?");
const char *erase_choice = _("[tn]");
const int nb_erase_choice = 2;
int answer;
struct todo *item = ui_todo_selitem();
if (!item || (conf.confirm_delete &&
(status_ask_bool(del_todo_str) != 1))) {
wins_erase_status_bar();
return;
}
if (item->note)
answer = status_ask_choice(erase_warning, erase_choice,
nb_erase_choice);
else
answer = 1;
switch (answer) {
case 1:
todo_delete(item);
ui_todo_load_items();
io_set_modified();
break;
case 2:
todo_delete_note(item);
io_set_modified();
break;
default:
wins_erase_status_bar();
return;
}
}
/* Edit the description of an already existing todo item. */
void ui_todo_edit(void)
{
struct todo *item = ui_todo_selitem();
const char *mesg = _("Enter the new TODO description:");
if (!item)
return;
status_mesg(mesg, "");
updatestring(win[STA].p, &item->mesg, 0, 1);
todo_resort(item);
ui_todo_load_items();
io_set_modified();
ui_todo_set_selitem(item);
}
/* Pipe a todo item to an external program. */
void ui_todo_pipe(void)
{
char cmd[BUFSIZ] = "";
char const *arg[] = { cmd, NULL };
int pout;
int pid;
FILE *fpout;
struct todo *item = ui_todo_selitem();
if (!item)
return;
status_mesg(_("Pipe item to external command:"), "");
if (getstring(win[STA].p, cmd, BUFSIZ, 0, 1) != GETSTRING_VALID)
return;
wins_prepare_external();
if ((pid = shell_exec(NULL, &pout, NULL, 0, *arg, arg))) {
fpout = fdopen(pout, "w");
todo_write(item, fpout);
fclose(fpout);
child_wait(NULL, &pout, NULL, pid);
press_any_key();
}
wins_unprepare_external();
}
/* Display todo items in the corresponding panel. */
void ui_todo_draw(int n, WINDOW *win, int y, int hilt, void *cb_data)
{
llist_item_t *i = *((llist_item_t **)cb_data);
struct todo *todo = LLIST_TS_GET_DATA(i);
char mark[] = { 0, 0, 0, 0 };
int width = lb_todo.sw.w - 2;
char buf[width * UTF8_MAXLEN];
char *mesg;
int j;
if (ui_todo_view == TODO_HIDE_COMPLETED_VIEW) {
while (i && todo->completed) {
i = i->next;
if (i)
todo = LLIST_TS_GET_DATA(i);
}
}
mark[0] = todo->completed ? 'X' : (todo->id > 0 ? '0' + todo->id : 0);
if (todo->note) {
if (mark[0] == '\0') {
mark[0] = '>';
mark[1] = ' ';
} else {
mark[1] = '>';
mark[2] = ' ';
}
} else if (mark[0] != '\0') {
mark[1] = '.';
mark[2] = ' ';
}
width -= strlen(mark);
hilt = hilt && (wins_slctd() == TOD);
if (hilt)
custom_apply_attr(win, ATTR_HIGHEST);
if (utf8_strwidth(todo->mesg) < width) {
mesg = todo->mesg;
} else {
width -= 3;
for (j = 0; todo->mesg[j] && width > 0; j++) {
if (!UTF8_ISCONT(todo->mesg[j]))
width -= utf8_width(&todo->mesg[j]);
buf[j] = todo->mesg[j];
}
if (j) {
buf[j - 1] = '.';
buf[j] = '.';
buf[j + 1] = '.';
buf[j + 2] = '\0';
} else {
buf[0] = 0;
}
mesg = buf;
}
mvwprintw(win, y, 0, "%s%s", mark, mesg);
if (hilt)
custom_remove_attr(win, ATTR_HIGHEST);
*((llist_item_t **)cb_data) = i->next;
}
enum listbox_row_type ui_todo_row_type(int i, void *cb_data)
{
return LISTBOX_ROW_TEXT;
}
int ui_todo_height(int n, void *cb_data)
{
return 1;
}
void ui_todo_load_items(void)
{
int n = 0;
llist_item_t *i;
/* TODO: Optimize this by keeping the list size in a variable. */
LLIST_FOREACH(&todolist, i) {
struct todo *todo = LLIST_TS_GET_DATA(i);
if (ui_todo_view == TODO_HIDE_COMPLETED_VIEW &&
todo->completed)
continue;
n++;
}
listbox_load_items(&lb_todo, n);
}
void ui_todo_sel_reset(void)
{
listbox_sel_move(&lb_todo, 0);
}
void ui_todo_sel_move(int delta)
{
listbox_sel_move(&lb_todo, delta);
}
/* Updates the TODO panel. */
void ui_todo_update_panel(int hilt)
{
/*
* This is used and modified by ui_todo_draw() to avoid quadratic
* running time.
*/
llist_item_t *p = LLIST_FIRST(&todolist);
listbox_set_cb_data(&lb_todo, &p);
listbox_display(&lb_todo, hilt);
}
/* Change an item priority by pressing '+' or '-' inside TODO panel. */
void ui_todo_chg_priority(int diff)
{
struct todo *item = ui_todo_selitem();
if (!item)
return;
int id = item->id + diff;
struct todo *item_new;
if (id < 0)
id = 0;
else if (id > 9)
id = 9;
item_new = todo_add(item->mesg, id, item->completed, item->note);
todo_delete(item);
io_set_modified();
ui_todo_set_selitem(item_new);
}
void ui_todo_popup_item(void)
{
struct todo *item = ui_todo_selitem();
if (!item)
return;
if (item->note) {
/* Assign a sane default note size that will cleanly
* truncate long notes */
const char *note_heading = _("Note:");
size_t note_size = 3500;
char note[note_size];
char *notepath, *msg;
FILE *fp;
asprintf(¬epath, "%s%s", path_notes, item->note);
fp = fopen(notepath, "r");
note_read_contents(note, note_size, fp);
fclose(fp);
mem_free(notepath);
asprintf(&msg, "%s\n\n%s\n%s", item->mesg, note_heading, note);
item_in_popup(NULL, NULL, msg, _("TODO:"));
mem_free(msg);
} else {
item_in_popup(NULL, NULL, item->mesg, _("TODO:"));
}
}
void ui_todo_flag(void)
{
struct todo *item = ui_todo_selitem();
if (!item)
return;
todo_flag(item);
ui_todo_load_items();
io_set_modified();
ui_todo_set_selitem(item);
}
void ui_todo_view_note(void)
{
struct todo *item = ui_todo_selitem();
if (!item)
return;
todo_view_note(item, conf.pager);
}
void ui_todo_edit_note(void)
{
struct todo *item = ui_todo_selitem();
if (!item)
return;
todo_edit_note(item, conf.editor);
io_set_modified();
}
/* Switch to next todo view. */
void ui_todo_view_next(void)
{
ui_todo_view++;
if (ui_todo_view == TODO_VIEWS)
ui_todo_view = 0;
ui_todo_load_items();
}
/* Switch to previous todo view. */
void ui_todo_view_prev(void)
{
if (ui_todo_view == 0)
ui_todo_view = TODO_VIEWS;
ui_todo_view--;
ui_todo_load_items();
}
void ui_todo_set_view(int view)
{
ui_todo_view = (view < 0 || view >= TODO_VIEWS) ?
TODO_SHOW_COMPLETED_VIEW : view;
}
int ui_todo_get_view(void)
{
return (int)ui_todo_view;
}
|
HanixNicolas/app-mesh
|
src/daemon/Label.h
|
#pragma once
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <cpprest/json.h>
//////////////////////////////////////////////////////////////////////////
/// Label
//////////////////////////////////////////////////////////////////////////
class Label
{
public:
Label();
virtual ~Label();
web::json::value AsJson() const;
static const std::shared_ptr<Label> FromJson(const web::json::value &obj) noexcept(false);
bool operator==(const std::shared_ptr<Label> &label);
void addLabel(const std::string &name, const std::string &value);
void delLabel(const std::string &name);
bool match(const std::shared_ptr<Label> &condition) const;
private:
std::map<std::string, std::string> m_labels;
mutable std::recursive_mutex m_mutex;
};
|
HanixNicolas/app-mesh
|
src/prom_exporter/detail/core_export.h
|
<reponame>HanixNicolas/app-mesh
#ifndef PROMETHEUS_CPP_CORE_EXPORT
#define PROMETHEUS_CPP_CORE_EXPORT
#endif
|
HanixNicolas/app-mesh
|
src/daemon/security/ldapplugin/LdapImpl.h
|
<reponame>HanixNicolas/app-mesh<gh_stars>10-100
#pragma once
#include <cpprest/json.h>
#include <mutex>
#include <string>
#include "../Security.h"
#define NOT_APPLICABLE_THROW \
override \
{ \
throw std::invalid_argument("not applicable for LDAP authentication"); \
}
namespace Ldap
{
class Server;
}
class JsonLdap;
//////////////////////////////////////////////////////////////////////////
/// LdapImpl
//////////////////////////////////////////////////////////////////////////
class LdapImpl : public Security
{
public:
explicit LdapImpl(std::shared_ptr<JsonLdap> ldap);
virtual ~LdapImpl();
virtual bool encryptKey() override { return true; };
virtual web::json::value AsJson() const override;
static std::shared_ptr<LdapImpl> FromJson(const web::json::value &obj) noexcept(false);
static void init();
public:
virtual bool verifyUserKey(const std::string &userName, const std::string &userKey, std::string &outUserGroup) override;
virtual void changeUserPasswd(const std::string &userName, const std::string &newPwd) NOT_APPLICABLE_THROW;
virtual std::shared_ptr<User> getUserInfo(const std::string &userName) const;
virtual std::map<std::string, std::shared_ptr<User>> getUsers() const NOT_APPLICABLE_THROW;
virtual web::json::value getUsersJson() const NOT_APPLICABLE_THROW;
virtual std::shared_ptr<User> addUser(const std::string &userName, const web::json::value &userJson) NOT_APPLICABLE_THROW;
virtual void delUser(const std::string &name) NOT_APPLICABLE_THROW;
virtual web::json::value getRolesJson() const NOT_APPLICABLE_THROW;
virtual void addRole(const web::json::value &obj, std::string name) NOT_APPLICABLE_THROW;
virtual void delRole(const std::string &name) NOT_APPLICABLE_THROW;
virtual std::set<std::string> getAllUserGroups() const override;
virtual std::set<std::string> getUserPermissions(const std::string &userName, const std::string &userGroup) override;
virtual std::set<std::string> getAllPermissions() override;
private:
std::shared_ptr<Ldap::Server> connect();
private:
std::shared_ptr<JsonLdap> m_ldap;
};
|
HanixNicolas/app-mesh
|
src/daemon/application/AppTimer.h
|
#pragma once
#include <chrono>
#include <memory>
#include <string>
#include <tuple>
#include "../../common/croncpp.h"
class DailyLimitation;
//////////////////////////////////////////////////////////////////////////
/// Calculate Application next start time
//////////////////////////////////////////////////////////////////////////
class AppTimer
{
public:
AppTimer(const std::chrono::system_clock::time_point &startTime, const std::chrono::system_clock::time_point &endTime,
std::shared_ptr<DailyLimitation> dailyLimit);
virtual ~AppTimer(){};
virtual std::chrono::system_clock::time_point nextTime(const std::chrono::system_clock::time_point &now = std::chrono::system_clock::now());
bool isInDailyTimeRange(const std::chrono::system_clock::time_point &target);
std::chrono::system_clock::time_point adjustDailyTimeRange(std::chrono::system_clock::time_point target);
protected:
std::chrono::system_clock::time_point checkStartTime(const std::chrono::system_clock::time_point &target);
public:
static std::chrono::system_clock::time_point EPOCH_ZERO_TIME;
protected:
const std::chrono::system_clock::time_point m_startTime;
const std::chrono::system_clock::time_point m_endTime;
std::shared_ptr<DailyLimitation> m_dailyLimit;
};
//////////////////////////////////////////////////////////////////////////
/// Calculate Application next start time for periodic run
//////////////////////////////////////////////////////////////////////////
class AppTimerPeriod : public AppTimer
{
public:
AppTimerPeriod(const std::chrono::system_clock::time_point &startTime, const std::chrono::system_clock::time_point &endTime,
std::shared_ptr<DailyLimitation> dailyLimit, int intervalSeconds);
std::chrono::system_clock::time_point nextTime(const std::chrono::system_clock::time_point &now = std::chrono::system_clock::now()) override;
protected:
const int m_intervalSeconds;
};
//////////////////////////////////////////////////////////////////////////
/// Calculate Application next start time for cron schedule
//////////////////////////////////////////////////////////////////////////
class AppTimerCron : public AppTimerPeriod
{
public:
AppTimerCron(const std::chrono::system_clock::time_point &startTime, const std::chrono::system_clock::time_point &endTime,
std::shared_ptr<DailyLimitation> dailyLimit, const std::string &cronExpr, int intervalSeconds);
std::chrono::system_clock::time_point nextTime(const std::chrono::system_clock::time_point &now = std::chrono::system_clock::now()) override;
protected:
const std::string m_cronExpr;
cron::cronexpr m_cron;
};
|
HanixNicolas/app-mesh
|
src/daemon/DailyLimitation.h
|
<reponame>HanixNicolas/app-mesh
#pragma once
#include <chrono>
#include <memory>
#include <string>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <cpprest/json.h>
//////////////////////////////////////////////////////////////////////////
/// Define the valid time range in one day
//////////////////////////////////////////////////////////////////////////
class DailyLimitation
{
public:
DailyLimitation();
virtual ~DailyLimitation();
bool operator==(const std::shared_ptr<DailyLimitation> &obj) const;
void dump();
web::json::value AsJson() const;
static std::shared_ptr<DailyLimitation> FromJson(const web::json::value &obj, const std::string &posixTimeZone) noexcept(false);
std::string m_startTime;
std::string m_endTime;
boost::posix_time::time_duration m_startTimeValue;
boost::posix_time::time_duration m_endTimeValue;
};
|
HanixNicolas/app-mesh
|
src/daemon/process/LinuxCgroup.h
|
#pragma once
#include <string>
/// </summary>
/// Linux Cgroup operate interface
/// </summary>
class LinuxCgroup
{
public:
explicit LinuxCgroup(long long memLimitBytes, long long memSwapBytes, long long cpuShares);
virtual ~LinuxCgroup();
void setCgroup(const std::string &appName, int pid, int index);
long long readHostMemValue(const std::string &cgroupFileName);
int readHostCpuSet();
bool swapSupport() const;
static bool runningInContainer();
private:
void retrieveCgroupHeirarchy();
void setPhysicalMemory(const std::string &cgroupPath, long long memLimitBytes);
void setSwapMemory(const std::string &cgroupPath, long long memSwapBytes);
void setCpuShares(const std::string &cgroupPath, long long cpuShares);
void writeValue(const std::string &cgroupPath, long long value);
long long readValue(const std::string &cgroupPath);
private:
long long m_memLimitMb;
long long m_memSwapMb;
long long m_cpuShares;
int m_pid;
std::string m_cgroupMemoryPath;
std::string m_cgroupCpuPath;
bool m_cgroupEnabled;
bool m_swapLimitSupport;
static std::string CGROUP_MEMORY_ROOT_DIR;
static std::string CGROUP_CPU_ROOT_DIR;
static std::string CGROUP_CPUSET_ROOT_DIR;
};
|
HanixNicolas/app-mesh
|
src/daemon/PersistManager.h
|
<reponame>HanixNicolas/app-mesh
#pragma once
#include <map>
#include <memory>
#include <string>
#include "cpprest/json.h"
/// <summary>
/// App Process Recover object
/// </summary>
struct AppSnap
{
explicit AppSnap(pid_t pid, int64_t starttime);
bool operator==(const AppSnap &snapshort) const;
pid_t m_pid;
int64_t m_startTime;
};
/// <summary>
/// App Mesh HA snapshot
/// </summary>
struct Snapshot
{
bool operator==(const Snapshot &snapshort) const;
web::json::value AsJson() const;
static std::shared_ptr<Snapshot> FromJson(const web::json::value &obj);
void persist();
std::map<std::string, AppSnap> m_apps;
std::string m_consulSessionId;
};
/// <summary>
/// App Mesh HA manager
/// </summary>
class PersistManager
{
public:
PersistManager();
virtual ~PersistManager();
void persistSnapshot();
static std::unique_ptr<PersistManager> &instance();
private:
std::shared_ptr<Snapshot> captureSnapshot();
private:
std::shared_ptr<Snapshot> m_persistedSnapshot;
};
|
HanixNicolas/app-mesh
|
src/daemon/security/ldapplugin/ldapcpp/cldap_server.h
|
<filename>src/daemon/security/ldapplugin/ldapcpp/cldap_server.h
/***************************************************************************
* Copyright (C) 2012 by <NAME> *
* <EMAIL> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef CLDAP_SERVER_H
#define CLDAP_SERVER_H
#include "cldap_types.h"
namespace Ldap
{
int getVersion(void);
class Info
{
protected:
std::string ldap_uri;
std::string bind_dn;
std::string bind_pw;
public:
Info(const std::string &uri, bool ssl = false) : ldap_uri(CreateURI(uri, ssl)) {}
Info(const std::string &uri, const std::string &dn, const std::string &pw) : ldap_uri(CreateURI(uri, false)), bind_dn(dn), bind_pw(pw) {}
Info() {}
const std::string &URI(void) const { return ldap_uri; }
const std::string &BindDN(void) const { return bind_dn; }
const std::string &BindPW(void) const { return bind_pw; }
static std::string CreateURI(const std::string &uri, bool ssl);
};
class Server : public Info
{
public:
Server();
Server(const Info &);
Server(const std::string &uri, bool ssl = false);
Server(const Server &);
~Server();
Server &operator=(const Server &);
std::string BaseDN(void);
bool Connect(const std::string &uri = "", bool ssl = false);
bool IsConnected(void) const;
void Disconnect(void);
bool Bind(void);
bool Bind(const std::string &bind_dn, const std::string &bind_pw);
bool IsBinded(void) const;
void Unbind(void);
bool Ping(void) const;
ListEntries Search(const std::string &base, const Scope &scope = ScopeBase, const std::string &filter = "");
ListEntries Search(const std::string &base, const Scope &scope, const std::string &filter, const ListAttrs &attrs);
bool Add(const Entry &entry);
bool Modify(const Entry &entry);
bool Compare(const std::string &dn, const std::string &attr, const std::string &val) const;
bool Delete(const std::string &dn);
bool ModDN(const std::string &dn, const std::string &newdn);
int Error(void) const;
const char *Message(void) const;
protected:
LDAP *ldap_object;
int ldap_errno;
bool binded;
bool connected;
};
std::ostream &operator<<(std::ostream &, const ListEntries &);
class Pools : public std::list<Ldap::Server>
{
public:
Pools();
Pools(const Info &, const Info &);
Pools(const std::list<Info> &);
void AddPools(const std::list<Info> &);
void AddServer(const Info &);
ListEntries Search(const std::string &base, const Scope &scope = ScopeBase, const std::string &filter = "");
ListEntries Search(const std::string &base, const Scope &scope, const std::string &filter, const ListAttrs &attrs);
protected:
std::list<Ldap::Server>::iterator current;
};
}
#endif
|
HanixNicolas/app-mesh
|
src/daemon/process/MonitoredProcess.h
|
<gh_stars>10-100
#pragma once
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include "AppProcess.h"
class ACE_Process_Options;
/// <summary>
/// Monitor process and reply http request when finished
/// <summary>
class MonitoredProcess : public AppProcess
{
public:
explicit MonitoredProcess();
virtual ~MonitoredProcess();
// overwrite ACE_Process spawn method
virtual pid_t spawn(ACE_Process_Options &options);
void setAsyncHttpRequest(void *httpRequest) { m_httpRequest = httpRequest; }
protected:
virtual void waitThread(int timerId = 0);
void runPipeReaderThread();
private:
void *m_httpRequest;
std::unique_ptr<std::thread> m_thread;
};
|
HanixNicolas/app-mesh
|
src/daemon/process/AppProcess.h
|
<filename>src/daemon/process/AppProcess.h<gh_stars>10-100
#pragma once
#include <map>
#include <string>
#include <tuple>
#include <ace/Process.h>
#include "../../common/Utility.h"
#include "../TimerHandler.h"
class LinuxCgroup;
class ResourceLimitation;
/// <summary>
/// Process Object, inherit from ACE_Process
/// Support:
/// 1. cgroup
/// 2. pipe
/// 3. auto kill
/// 4. timer kill
/// </summary>
class AppProcess : public ACE_Process, public TimerHandler
{
public:
AppProcess();
virtual ~AppProcess();
/// <summary>
/// Override function
/// </summary>
/// <param name=""></param>
/// <returns></returns>
virtual pid_t getpid(void) const;
/// <summary>
/// Get process exit code
/// </summary>
/// <returns></returns>
virtual int returnValue(void) const { return this->return_value(); };
/// <summary>
/// Process UUID
/// </summary>
/// <returns></returns>
const std::string getuuid() const;
/// <summary>
/// Get Docker container ID
/// </summary>
/// <returns></returns>
virtual std::string containerId() const { return std::string(); };
/// <summary>
/// Set Docker container ID
/// </summary>
/// <param name="containerId"></param>
virtual void containerId(const std::string &containerId){};
/// <summary>
/// get process memory and cpu usage
/// </summary>
/// <returns>
/// tuple
/// - bool: get success or fail
/// - uint64_t: total memory bytes
/// - float: cpu usage
/// </returns>
std::tuple<bool, uint64_t, float> getProcUsage(void *ptree = nullptr);
/// <summary>
/// Attach a existing pid to AppProcess to manage
/// </summary>
/// <param name="pid">process id</param>
void attach(int pid);
/// <summary>
/// avoid de-constructure kill process
/// </summary>
void detach(void);
/// <summary>
/// kill the process group
/// </summary>
/// <param name="timerId"></param>
virtual void killgroup(int timerId = 0);
/// <summary>
/// set resource limitation
/// </summary>
/// <param name="limit"></param>
virtual void setCgroup(std::shared_ptr<ResourceLimitation> &limit);
/// <summary>
/// kill after a time period
/// </summary>
/// <param name="timeoutSec">seconds</param>
/// <param name="from"></param>
void delayKill(std::size_t timeoutSec, const std::string &from);
/// <summary>
/// register check stdout timer
/// </summary>
void regCheckStdout();
/// <summary>
/// check stdout file size
/// </summary>
/// <param name="timerId"></param>
void checkStdout(int timerId);
/// <summary>
/// Start process
/// </summary>
/// <param name="cmd">full command line with arguments</param>
/// <param name="user">Linux user name</param>
/// <param name="workDir">working directory</param>
/// <param name="envMap">environment variables</param>
/// <param name="limit">cgroup limitation</param>
/// <param name="stdoutFile">std out output file</param>
/// <param name="stdinFileContent">std in string content</param>
/// <param name="maxStdoutSize">max stdout log file size, default is 100MB</param>
/// <returns>process id</returns>
virtual int spawnProcess(std::string cmd, std::string user, std::string workDir,
std::map<std::string, std::string> envMap, std::shared_ptr<ResourceLimitation> limit,
const std::string &stdoutFile = "", const web::json::value &stdinFileContent = EMPTY_STR_JSON,
const int maxStdoutSize = APP_STD_OUT_MAX_FILE_SIZE);
/// <summary>
/// get all std out content from stdoutFile with given position
/// </summary>
/// <returns></returns>
virtual const std::string getOutputMsg(long *position = nullptr, int maxSize = APP_STD_OUT_VIEW_DEFAULT_SIZE, bool readLine = false);
/// <summary>
/// save last error
/// </summary>
/// <param name="err">error string</param>
void startError(const std::string &err);
/// <summary>
/// get last error
/// </summary>
/// <returns></returns>
const std::string startError() const;
protected:
/// <summary>
/// Parse command line, get cmdRoot and parameters
/// </summary>
/// <param name="cmd"></param>
/// <returns>tuple: 1 cmdRoot, 2 parameters</returns>
std::tuple<std::string, std::string> extractCommand(const std::string &cmd);
private:
int m_delayKillTimerId;
int m_stdOutSizeTimerId;
off_t m_stdOutMaxSize;
mutable std::recursive_mutex m_processMutex; //checkStdout, delayKill, killgroup
ACE_HANDLE m_stdinHandler;
ACE_HANDLE m_stdoutHandler;
std::string m_stdinFileName;
std::string m_stdoutFileName;
mutable std::recursive_mutex m_outFileMutex;
mutable std::recursive_mutex m_cpuMutex;
uint64_t m_lastProcCpuTime;
uint64_t m_lastSysCpuTime;
std::unique_ptr<LinuxCgroup> m_cgroup;
const std::string m_uuid;
std::string m_startError;
};
|
HanixNicolas/app-mesh
|
src/daemon/ResourceCollection.h
|
<filename>src/daemon/ResourceCollection.h
#pragma once
#include <chrono>
#include <list>
#include <memory>
#include <mutex>
#include <string>
#include <unistd.h>
#include <cpprest/json.h>
struct HostNetInterface
{
std::string name;
bool ipv4;
std::string address;
};
//////////////////////////////////////////////////////////////////////////
/// Host resource attribute
//////////////////////////////////////////////////////////////////////////
struct HostResource
{
HostResource() : m_cores(0), m_sockets(0), m_processors(0), m_total_bytes(0), m_free_bytes(0), m_totalSwap_bytes(0), m_freeSwap_bytes(0) {}
// CPU
std::size_t m_cores;
std::size_t m_sockets;
std::size_t m_processors;
// MEM
uint64_t m_total_bytes;
uint64_t m_free_bytes;
uint64_t m_totalSwap_bytes;
uint64_t m_freeSwap_bytes;
// TODO: disk
// NET
std::list<HostNetInterface> m_ipaddress;
};
//////////////////////////////////////////////////////////////////////////
// Collect host and application resource usage metrics
//////////////////////////////////////////////////////////////////////////
class ResourceCollection
{
public:
ResourceCollection();
virtual ~ResourceCollection();
// Internal Singleton.
static std::unique_ptr<ResourceCollection> &instance();
const std::string getHostName(bool refresh = false);
const HostResource &getHostResource();
pid_t getPid();
void dump();
web::json::value AsJson();
web::json::value getConsulJson();
private:
HostResource m_resources;
std::recursive_mutex m_mutex;
const std::chrono::system_clock::time_point m_appmeshStartTime;
};
|
HanixNicolas/app-mesh
|
src/daemon/HealthCheckTask.h
|
#pragma once
#include <memory>
//////////////////////////////////////////////////////////////////////////
/// Do health check for applications
//////////////////////////////////////////////////////////////////////////
class HealthCheckTask
{
public:
HealthCheckTask();
virtual ~HealthCheckTask();
static std::shared_ptr<HealthCheckTask> &instance();
void doHealthCheck();
};
|
HanixNicolas/app-mesh
|
src/daemon/rest/RestTcpServer.h
|
<gh_stars>10-100
#pragma once
#include <memory>
#include <mutex>
#include <thread>
#include <ace/Message_Block.h>
#include <ace/SOCK_Acceptor.h>
#include <ace/SOCK_Stream.h>
#include <ace/Task.h>
#include "HttpRequest.h"
#include "RestHandler.h"
/// <summary>
/// REST Server, inherit from RestHandler and PrometheusRest
/// Accept REST request from TCP channel and process via RestHandler and PrometheusRest
/// </summary>
class RestTcpServer : public ACE_Task<ACE_MT_SYNCH>, public ACE_SOCK_Acceptor, public RestHandler
{
public:
RestTcpServer();
virtual ~RestTcpServer();
static std::shared_ptr<RestTcpServer> instance();
static void instance(std::shared_ptr<RestTcpServer> tcpServer);
/// <summary>
/// start thread pool and listen port
/// </summary>
void startTcpServer();
/// <summary>
/// Response REST response to client
/// </summary>
/// <param name="uuid"></param>
/// <param name="body"></param>
/// <param name="headers"></param>
/// <param name="status"></param>
/// <param name="bodyType"></param>
void backforwardResponse(const std::string &uuid, const std::string &body, const web::http::http_headers &headers, const http::status_code &status, const std::string &bodyType);
/// <summary>
/// Generate Application json for rest process
/// </summary>
/// <returns></returns>
const web::json::value getRestAppJson() const;
private:
/// <summary>
/// ACE_Task_Base::open()
/// Hook called to initialize a task and prepare it for execution.
/// </summary>
/// <param name=""></param>
/// <returns></returns>
int open(void *);
/// <summary>
/// Thread pool to handle TCP REST request asynchronous
/// </summary>
/// <param name=""></param>
/// <returns></returns>
int svc(void);
/// <summary>
/// Thread to accept and read socket message
/// </summary>
void socketThread();
/// <summary>
/// Process TCP request
/// </summary>
/// <param name="message"></param>
void handleTcpRest(const HttpRequest &message);
private:
mutable std::recursive_mutex m_socketSendLock;
ACE_SOCK_Stream m_socketStream;
static std::shared_ptr<RestTcpServer> m_instance;
std::thread m_socketThread;
};
|
HanixNicolas/app-mesh
|
src/daemon/process/DockerApiProcess.h
|
#pragma once
#include <string>
#include <cpprest/http_msg.h>
#include <cpprest/json.h>
#include "DockerProcess.h"
/// <summary>
/// Docker API Object
/// </summary>
class DockerApiProcess : public DockerProcess
{
public:
/// <summary>
/// Constructor
/// </summary>
/// <param name="dockerImage"></param>
/// <param name="containerName"></param>
DockerApiProcess(const std::string &dockerImage, const std::string &containerName);
virtual ~DockerApiProcess();
/// <summary>
/// override with docker REST behavior
/// </summary>
/// <param name="timerId"></param>
virtual void killgroup(int timerId = 0) override;
/// <summary>
/// override with docker REST request
/// </summary>
/// <param name="cmd"></param>
/// <param name="execUser"></param>
/// <param name="workDir"></param>
/// <param name="envMap"></param>
/// <param name="limit"></param>
/// <param name="stdoutFile"></param>
/// <param name="stdinFileContent"></param>
/// <param name="maxStdoutSize"></param>
/// <returns></returns>
virtual int spawnProcess(std::string cmd, std::string execUser, std::string workDir, std::map<std::string, std::string> envMap, std::shared_ptr<ResourceLimitation> limit, const std::string &stdoutFile = "", const web::json::value &stdinFileContent = EMPTY_STR_JSON, const int maxStdoutSize = 0) override;
/// <summary>
/// get all std out content from stdoutFile with given position
/// </summary>
/// <param name="position"></param>
/// <param name="maxSize"></param>
/// <param name="readLine"></param>
/// <returns></returns>
const std::string getOutputMsg(long *position = nullptr, int maxSize = APP_STD_OUT_VIEW_DEFAULT_SIZE, bool readLine = false) override;
/// <summary>
/// get process exit code
/// </summary>
/// <param name=""></param>
/// <returns></returns>
virtual int returnValue(void) const override;
private:
/// <summary>
/// Request Docker HTTP
/// </summary>
/// <param name="mtd"></param>
/// <param name="path"></param>
/// <param name="query"></param>
/// <param name="header"></param>
/// <param name="body"></param>
/// <returns></returns>
const web::http::http_response requestHttp(const web::http::method &mtd, const std::string &path, std::map<std::string, std::string> query, std::map<std::string, std::string> header, web::json::value *body);
};
|
HanixNicolas/app-mesh
|
src/daemon/consul/Scheduler.h
|
#pragma once
#include <map>
#include <memory>
struct ConsulTopology;
struct ConsulTask;
/// <summary>
/// Leader schedule logic
/// </summary>
class Scheduler
{
public:
static std::map<std::string, std::shared_ptr<ConsulTopology>> scheduleTask(const std::map<std::string, std::shared_ptr<ConsulTask>> &taskMap, const std::map<std::string, std::shared_ptr<ConsulTopology>> &oldTopology);
};
|
HanixNicolas/app-mesh
|
src/common/PerfLog.h
|
<filename>src/common/PerfLog.h
#pragma once
#include <chrono>
#include <string>
/// <summary>
/// Print performance log
/// </summary>
class PerfLog
{
public:
explicit PerfLog(const std::string &logger);
virtual ~PerfLog();
private:
const std::chrono::system_clock::time_point m_start;
const std::string m_logger;
};
|
HanixNicolas/app-mesh
|
src/daemon/application/AppBehavior.h
|
<reponame>HanixNicolas/app-mesh<gh_stars>10-100
#include <map>
#include <string>
#include <cpprest/json.h>
/// <summary>
/// Application error handling
/// </summary>
class AppBehavior
{
public:
/// <summary>
/// Application error handling behavior
/// </summary>
enum Action
{
STANDBY = 0,
RESTART = 1,
KEEPALIVE = 2,
REMOVE = 3
};
public:
AppBehavior();
virtual ~AppBehavior(){};
static std::string action2str(AppBehavior::Action action);
static AppBehavior::Action str2action(const std::string &action2str);
protected:
void behaviorInit(web::json::value config);
web::json::value behaviorAsJson();
// behavior getting
AppBehavior::Action exitAction(int code);
protected:
// action for exit code beside m_exitCodeEvent
AppBehavior::Action m_exitEvent;
// key: exit code, Value: action
std::map<int, AppBehavior::Action> m_exitCodeEvent;
};
|
HanixNicolas/app-mesh
|
src/daemon/security/Security.h
|
#pragma once
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <cpprest/json.h>
#include "User.h"
//////////////////////////////////////////////////////////////////////////
/// Security base implementation based on local JSON file
//////////////////////////////////////////////////////////////////////////
class Security
{
protected:
explicit Security(std::shared_ptr<JsonSecurity> jsonSecurity);
public:
virtual ~Security();
virtual web::json::value AsJson() const;
static std::shared_ptr<Security> FromJson(const web::json::value &obj) noexcept(false);
virtual void save();
virtual bool encryptKey();
static void init();
static std::shared_ptr<Security> instance();
static void instance(std::shared_ptr<Security> instance);
public:
virtual bool verifyUserKey(const std::string &userName, const std::string &userKey, std::string &outUserGroup);
virtual void changeUserPasswd(const std::string &userName, const std::string &newPwd);
virtual std::shared_ptr<User> getUserInfo(const std::string &userName) const;
virtual std::map<std::string, std::shared_ptr<User>> getUsers() const;
virtual web::json::value getUsersJson() const;
virtual std::shared_ptr<User> addUser(const std::string &userName, const web::json::value &userJson);
virtual void delUser(const std::string &name);
virtual web::json::value getRolesJson() const;
virtual void addRole(const web::json::value &obj, std::string name);
virtual void delRole(const std::string &name);
virtual std::set<std::string> getAllUserGroups() const;
virtual std::set<std::string> getUserPermissions(const std::string &userName, const std::string &userGroup);
virtual std::set<std::string> getAllPermissions();
private:
std::shared_ptr<JsonSecurity> m_securityConfig;
static std::shared_ptr<Security> m_instance;
static std::recursive_mutex m_mutex;
};
|
HanixNicolas/app-mesh
|
src/daemon/rest/PrometheusRest.h
|
<gh_stars>10-100
#pragma once
#include <atomic>
#include <memory>
#include <cpprest/http_listener.h> // HTTP server
#include "../../prom_exporter/family.h"
#include "HttpRequest.h"
#include "RestBase.h"
namespace prometheus
{
class Counter;
class Gauge;
class Registry;
}; // namespace prometheus
//////////////////////////////////////////////////////////////////////////
// Registry
// _|_
// CounterFamily-1 CounterFamily-2
// _|_ _|_
// Counter1/Counter2 Counter3/Counter4
//////////////////////////////////////////////////////////////////////////
/// <summary>
/// Metric Wrapper for reg/unreg metric automaticaly
/// </summary>
class CounterMetric
{
public:
explicit CounterMetric(std::shared_ptr<prometheus::Registry> registry,
const std::string &name, const std::string &help,
std::map<std::string, std::string> label);
virtual ~CounterMetric();
prometheus::Counter &metric();
private:
prometheus::Counter *m_metric;
prometheus::Family<prometheus::Counter> *m_family;
std::shared_ptr<prometheus::Registry> m_promRegistry;
const std::string m_name;
const std::string m_help;
const std::map<std::string, std::string> m_label;
};
/// <summary>
/// Metric Wrapper for reg/unreg metric automaticaly
/// </summary>
class GaugeMetric
{
public:
explicit GaugeMetric(std::shared_ptr<prometheus::Registry> registry,
const std::string &name, const std::string &help,
std::map<std::string, std::string> label);
virtual ~GaugeMetric();
prometheus::Gauge &metric();
private:
prometheus::Gauge *m_metric;
prometheus::Family<prometheus::Gauge> *m_family;
std::shared_ptr<prometheus::Registry> m_promRegistry;
const std::string m_name;
const std::string m_help;
const std::map<std::string, std::string> m_label;
};
/// <summary>
/// Prometheus Exporter REST service
/// </summary>
class PrometheusRest : public RestBase
{
public:
explicit PrometheusRest(bool forward2TcpServer);
virtual ~PrometheusRest();
/// <summary>
/// Create a Counter Metric
/// </summary>
/// <param name="metricName"></param>
/// <param name="metricHelp"></param>
/// <param name="labels"></param>
/// <returns>return null if exporter was not enabled</returns>
std::shared_ptr<CounterMetric> createPromCounter(const std::string &metricName, const std::string &metricHelp, const std::map<std::string, std::string> &labels) noexcept(false);
/// <summary>
/// Create a Gauge Metric
/// </summary>
/// <param name="metricName"></param>
/// <param name="metricHelp"></param>
/// <param name="labels"></param>
/// <returns>return null if exporter was not enabled</returns>
std::shared_ptr<GaugeMetric> createPromGauge(const std::string &metricName, const std::string &metricHelp, const std::map<std::string, std::string> &labels) noexcept(false);
/// <summary>
/// Collect all metrics
/// </summary>
/// <returns></returns>
const std::string collectData();
/// <summary>
/// The metrics is collected by Prometheus server or not
/// </summary>
/// <returns></returns>
bool collected();
protected:
/// <summary>
/// open REST listen port
/// </summary>
virtual void open();
/// <summary>
/// override RestBase::handleRest() to set REST related metrics
/// </summary>
/// <param name="message"></param>
/// <param name="restFunctions"></param>
virtual void handleRest(const HttpRequest &message, const std::map<std::string, std::function<void(const HttpRequest &)>> &restFunctions) override;
private:
/// <summary>
/// REST API function
/// </summary>
/// <param name="message"></param>
void apiMetrics(const HttpRequest &message);
/// <summary>
/// Create metrics
/// </summary>
void initMetrics();
private:
bool m_promEnabled;
std::atomic_long m_collectTime = ATOMIC_FLAG_INIT; // std::atomic_flag should be initialized in declare
static std::shared_ptr<PrometheusRest> m_instance;
std::unique_ptr<web::http::experimental::listener::http_listener> m_promListener;
// prometheus registry
std::shared_ptr<prometheus::Registry> m_promRegistry;
// prometheus global metric
std::shared_ptr<CounterMetric> m_scrapeCounter;
std::shared_ptr<GaugeMetric> m_promGauge;
// prometheus rest event counter metric
std::shared_ptr<CounterMetric> m_restGetCounter;
std::shared_ptr<CounterMetric> m_restPutCounter;
std::shared_ptr<CounterMetric> m_restDelCounter;
std::shared_ptr<CounterMetric> m_restPostCounter;
std::shared_ptr<GaugeMetric> m_appmeshFileDesc;
public:
static std::shared_ptr<PrometheusRest> instance() { return m_instance; }
static void instance(std::shared_ptr<PrometheusRest> instance) { m_instance = instance; };
};
#define PROM_COUNTER_INCREASE(counter) \
{ \
if (counter) \
counter->metric().Increment(); \
}
// Prometheus scrap counter
#define PROM_METRIC_NAME_appmesh_prom_scrape_count "appmesh_prom_scrape_count"
#define PROM_METRIC_HELP_appmesh_prom_scrape_count "prometheus scrape count"
// App Mesh alive
#define PROM_METRIC_NAME_appmesh_prom_scrape_up "appmesh_prom_scrape_up"
#define PROM_METRIC_HELP_appmesh_prom_scrape_up "prometheus scrape alive"
// App Mesh file descriptors
#define PROM_METRIC_NAME_appmesh_prom_file_descriptor "appmesh_prom_file_descriptor"
#define PROM_METRIC_HELP_appmesh_prom_file_descriptor "appmesh file descriptors"
// App Mesh HTTP request count
#define PROM_METRIC_NAME_appmesh_http_request_count "appmesh_http_request_count"
#define PROM_METRIC_HELP_appmesh_http_request_count "app mesh http request count"
// Application process start count
#define PROM_METRIC_NAME_appmesh_prom_process_start_count "appmesh_prom_process_start_count"
#define PROM_METRIC_HELP_appmesh_prom_process_start_count "application process spawn count"
// Application process id
#define PROM_METRIC_NAME_appmesh_prom_process_id_gauge "appmesh_prom_process_id_gauge"
#define PROM_METRIC_HELP_appmesh_prom_process_id_gauge "application process id"
// Application process memory usage
#define PROM_METRIC_NAME_appmesh_prom_process_memory_gauge "appmesh_prom_process_memory_gauge"
#define PROM_METRIC_HELP_appmesh_prom_process_memory_gauge "application process memory bytes"
// Application process cpu usage
#define PROM_METRIC_NAME_appmesh_prom_process_cpu_gauge "appmesh_prom_process_cpu_gauge"
#define PROM_METRIC_HELP_appmesh_prom_process_cpu_gauge "application process cpu usage"
// Application process file descriptors
#define PROM_METRIC_NAME_appmesh_prom_process_file_descriptors "appmesh_prom_process_file_descriptors"
#define PROM_METRIC_HELP_appmesh_prom_process_file_descriptors "application process file descriptors"
|
HanixNicolas/app-mesh
|
src/common/DateTime.h
|
<gh_stars>10-100
#pragma once
#include <chrono>
#include <string>
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#define ISO8601FORMAT_IN "%Y-%m-%d %H:%M:%S%F%ZP"
#define ISO8601FORMAT_OUT "%Y-%m-%dT%H:%M:%S%F%Q"
#define RFC3339FORMAT "%Y-%m-%dT%H:%M:%S%FZ"
/// <summary>
/// Boost local time zone
/// https://stackoverflow.com/questions/8746848/boost-get-the-current-local-date-time-with-current-time-zone-from-the-machine
/// </summary>
class machine_time_zone : public boost::local_time::custom_time_zone
{
typedef boost::local_time::custom_time_zone base_type;
typedef base_type::time_duration_type time_duration_type;
public:
machine_time_zone();
// This method is not precise, real offset may be several seconds more or less.
static const boost::posix_time::time_duration &get_utc_offset();
// GMT
static const std::string &get_std_zone_abbrev();
};
/// <summary>
/// Date Time parse and format
/// </summary>
class DateTime
{
public:
/// <summary>
/// Return local host posix zone string
/// </summary>
/// <returns>posix zone: +08:00:00 with format [%H:%M:%S]</returns>
static const std::string getLocalZoneUTCOffset();
/// <summary>
/// Set DateTime output posix zone info to variable: LOCAL_POSIX_ZONE
/// default use LOCAL_POSIX_ZONE without set
/// </summary>
/// <param name="posixZone">posix zone: +08:00:00 with format [%H:%M:%S]</param>
static void setOutputFormatPosixZone(const std::string &posixZone);
/// <summary>
/// Parse ISO8601 date time from string, if the parameter strTime have zone info, will ignore posixTimeZone
/// </summary>
/// <param name="strTime">"2017-09-11 21:52:13+00:00" or "2017-09-11 21:52:13"</param>
/// <param name="posixTimeZone">+07:00, leave empty will use getLocalZoneUTCOffset()</param>
/// <returns></returns>
static std::chrono::system_clock::time_point parseISO8601DateTime(const std::string &strTime, const std::string &posixTimeZone = "");
/// <summary>
/// Format time_point with [%Y-%m-%d %H:%M:%S%F%Q] flags and LOCAL_POSIX_ZONE (set from setOutputFormatPosixZone()) offset
/// </summary>
/// <param name="time">std::chrono::system_clock::time_point</param>
/// <returns>ISO8601 date time string: 2017-09-11 21:52:13+00:00</returns>
static std::string formatISO8601Time(const std::chrono::system_clock::time_point &time);
/// <summary>
/// Format time_point with provided flags and LOCAL_POSIX_ZONE (set from setOutputFormatPosixZone()) offset
/// The format is using boost::local_time::local_date_time, only seconds will be taken.
/// </summary>
/// <param name="time">std::chrono::system_clock::time_point</param>
/// <param name="fmt">The format can be found here: https://www.boost.org/doc/libs/1_69_0/doc/html/date_time/date_time_io.html#date_time.format_flags</param>
/// <returns>Formated date time string</returns>
static std::string formatLocalTime(const std::chrono::system_clock::time_point &time, const char *fmt = ISO8601FORMAT_OUT);
/// <summary>
/// Format time_point (utc) to RFC3339 format
/// </summary>
/// <param name="time">UTC time_point</param>
/// <returns>RFC3339 date time: 2019-01-23T10:18:32.079Z</returns>
static std::string formatRFC3339Time(const std::chrono::system_clock::time_point &time);
/// <summary>
/// Get posix time zone string from date time string
/// </summary>
/// <param name="strTime">ISO8601 time format: 2020-10-11T19:50:00+08:00</param>
/// <returns>posix time zone: +08:00</returns>
static std::string getISO8601TimeZone(const std::string &strTime);
/// <summary>
/// Get day time duration from time_point (time_point is UTC time)
/// </summary>
/// <param name="time">std::chrono::system_clock::time_point</param>
/// <returns>boost::posix_time::time_duration</returns>
static boost::posix_time::time_duration pickDayTimeUtcDuration(const std::chrono::system_clock::time_point &time);
/// <summary>
/// Parse day time string to UTC day time duration
/// </summary>
/// <param name="strTime">string with [%H:%M:%S] format</param>
/// <param name="posixTimezone">posix time zone, +08</param>
/// <returns>boost::posix_time::time_duration</returns>
static boost::posix_time::time_duration parseDayTimeUtcDuration(const std::string &strTime, const std::string &posixTimezone);
/// <summary>
/// Reduce posix zone (+08:00:00 -> +08), remove last ":00"
/// </summary>
/// <param name="timeStr">ISO8601 format date time string</param>
/// <returns>reduced string</returns>
static std::string reducePosixZone(const std::string &timeStr);
};
|
HanixNicolas/app-mesh
|
src/daemon/rest/RestHandler.h
|
#pragma once
#include <functional>
#include <cpprest/http_listener.h> // HTTP server
#include "PrometheusRest.h"
class Application;
/// <summary>
/// REST service handle class, all REST request entrypoint
/// </summary>
class RestHandler : public PrometheusRest
{
public:
explicit RestHandler(bool forward2TcpServer);
virtual ~RestHandler();
protected:
virtual void open() override;
void close();
void checkAppAccessPermission(const HttpRequest &message, const std::string &appName, bool requestWrite);
long getHttpQueryValue(const HttpRequest &message, const std::string &key, long defaultValue, long min, long max) const;
std::string getHttpQueryString(const HttpRequest &message, const std::string &key) const;
std::string regexSearch(const std::string &value, const char *regex);
void apiUserLogin(const HttpRequest &message);
void apiUserAuth(const HttpRequest &message);
void apiAppView(const HttpRequest &message);
void apiAppOutputView(const HttpRequest &message);
void apiAppsView(const HttpRequest &message);
std::shared_ptr<Application> parseAndRegRunApp(const HttpRequest &message);
void apiRunAsync(const HttpRequest &message);
void apiRunSync(const HttpRequest &message);
void apiCloudAppsView(const HttpRequest &message);
void apiCloudAppAdd(const HttpRequest &message);
void apiCloudAppDel(const HttpRequest &message);
void apiCloudHostView(const HttpRequest &message);
void apiResourceView(const HttpRequest &message);
void apiAppAdd(const HttpRequest &message);
void apiAppEnable(const HttpRequest &message);
void apiAppDisable(const HttpRequest &message);
void apiAppDelete(const HttpRequest &message);
void apiFileDownload(const HttpRequest &message);
void apiFileUpload(const HttpRequest &message);
void apiLabelsView(const HttpRequest &message);
void apiLabelAdd(const HttpRequest &message);
void apiLabelDel(const HttpRequest &message);
void apiBasicConfigView(const HttpRequest &message);
void apiBasicConfigSet(const HttpRequest &message);
void apiPermissionsView(const HttpRequest &message);
void apiUserPermissionsView(const HttpRequest &message);
void apiUserChangePwd(const HttpRequest &message);
void apiUserLock(const HttpRequest &message);
void apiUserUnlock(const HttpRequest &message);
void apiUserAdd(const HttpRequest &message);
void apiUserDel(const HttpRequest &message);
void apiUsersView(const HttpRequest &message);
void apiUserGroupsView(const HttpRequest &message);
void apiRolesView(const HttpRequest &message);
void apiRoleUpdate(const HttpRequest &message);
void apiRoleDelete(const HttpRequest &message);
void apiHealth(const HttpRequest &message);
void apiRestMetrics(const HttpRequest &message); // not for Prometheus
protected:
std::unique_ptr<web::http::experimental::listener::http_listener> m_listener;
};
|
HanixNicolas/app-mesh
|
src/daemon/security/ldapplugin/ldapcpp/cldap_mod.h
|
<filename>src/daemon/security/ldapplugin/ldapcpp/cldap_mod.h
/***************************************************************************
* Copyright (C) 2012 by <NAME> *
* <EMAIL> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef CLDAP_MOD_H
#define CLDAP_MOD_H
#include "cldap_types.h"
namespace Ldap
{
class Entry;
class ModBase
{
public:
ModBase(int, const char *);
virtual ~ModBase() {}
virtual void Clear(void) = 0;
virtual bool Append(const char *, size_t) = 0;
void Append(const std::string &str)
{
if (str.size())
Append(str.c_str(), str.size());
}
void Append(const std::vector<char> &v)
{
if (v.size())
Append(&v[0], v.size());
}
bool IsType(const std::string &) const;
bool IsBinary(void) const;
bool IsOperation(int) const;
virtual std::string GetStringValue(void) const = 0;
virtual std::vector<std::string> GetStringValues(void) const = 0;
virtual std::list<std::string> GetStringList(void) const = 0;
virtual std::vector<char> GetBinaryValue(void) const = 0;
virtual std::vector<std::vector<char>> GetBinaryValues(void) const = 0;
virtual std::list<std::vector<char>> GetBinaryList(void) const = 0;
protected:
friend class Entry;
const LDAPMod *toLDAPMod(void) const;
LDAPMod val;
size_t mod_vals_size;
};
class ModStr : public ModBase
{
friend std::ostream &operator<<(std::ostream &, const ModStr &);
public:
ModStr(int op, const std::string &type) : ModBase(op, type.c_str()) {}
~ModStr() { Clear(); }
void Clear(void);
bool Append(const char *, size_t);
void Append(const char *);
std::string GetStringValue(void) const;
std::vector<std::string>
GetStringValues(void) const;
std::list<std::string>
GetStringList(void) const;
std::vector<char>
GetBinaryValue(void) const;
std::vector<std::vector<char>>
GetBinaryValues(void) const;
std::list<std::vector<char>>
GetBinaryList(void) const;
};
class ModBin : public ModBase
{
friend std::ostream &operator<<(std::ostream &, const ModBin &);
public:
ModBin(int op, const std::string &type) : ModBase(op | LDAP_MOD_BVALUES, type.c_str()) {}
~ModBin() { Clear(); }
void Clear(void);
bool Append(const char *, size_t);
std::string GetStringValue(void) const;
std::vector<std::string>
GetStringValues(void) const;
std::list<std::string>
GetStringList(void) const;
std::vector<char>
GetBinaryValue(void) const;
std::vector<std::vector<char>>
GetBinaryValues(void) const;
std::list<std::vector<char>>
GetBinaryList(void) const;
};
std::ostream &operator<<(std::ostream &, const ModStr &);
std::ostream &operator<<(std::ostream &, const ModBin &);
}
#endif
|
HanixNicolas/app-mesh
|
src/daemon/process/DockerProcess.h
|
#pragma once
#include <chrono>
#include <map>
#include <string>
#include "AppProcess.h"
/// <summary>
/// Docker command line process object
/// </summary>
class DockerProcess : public AppProcess
{
public:
/// <summary>
/// constructor
/// </summary>
/// <param name="dockerImage"></param>
/// <param name="containerName"></param>
DockerProcess(const std::string &dockerImage, const std::string &containerName);
virtual ~DockerProcess();
/// <summary>
/// override with docker cli behavior
/// </summary>
/// <param name="timerId"></param>
virtual void killgroup(int timerId = 0) override;
/// <summary>
/// override with docker cli behavior
/// </summary>
/// <param name="cmd"></param>
/// <param name="execUser"></param>
/// <param name="workDir"></param>
/// <param name="envMap"></param>
/// <param name="limit"></param>
/// <param name="stdoutFile"></param>
/// <param name="stdinFileContent"></param>
/// <param name="maxStdoutSize"></param>
/// <returns></returns>
virtual int spawnProcess(std::string cmd, std::string execUser, std::string workDir, std::map<std::string, std::string> envMap, std::shared_ptr<ResourceLimitation> limit, const std::string &stdoutFile = "", const web::json::value &stdinFileContent = EMPTY_STR_JSON, const int maxStdoutSize = 0) override;
/// <summary>
/// override with docker cli behavior
/// 1. return docker pull cli pid
/// 2. return docker container pid get from inspect
/// </summary>
/// <param name=""></param>
/// <returns></returns>
virtual pid_t getpid(void) const override;
/// <summary>
/// get container id
/// </summary>
/// <returns></returns>
virtual std::string containerId() const override;
/// <summary>
/// set container id
/// </summary>
/// <param name="containerId"></param>
virtual void containerId(const std::string &containerId) override;
/// <summary>
/// get process exit code
/// </summary>
/// <param name=""></param>
/// <returns></returns>
virtual int returnValue(void) const override;
/// <summary>
/// get all std out content from stdoutFile with given position
/// </summary>
/// <param name="position"></param>
/// <param name="maxSize"></param>
/// <param name="readLine"></param>
/// <returns></returns>
const std::string getOutputMsg(long *position = nullptr, int maxSize = APP_STD_OUT_VIEW_DEFAULT_SIZE, bool readLine = false) override;
protected:
/// <summary>
/// run docker pull cli
/// </summary>
/// <param name="envMap"></param>
/// <param name="dockerImage"></param>
/// <param name="stdoutFile"></param>
/// <param name="workDir"></param>
/// <returns></returns>
int execPullDockerImage(std::map<std::string, std::string> &envMap, const std::string &dockerImage, const std::string &stdoutFile, const std::string &workDir);
private:
/// <summary>
/// synchronize run docker container start process
/// </summary>
/// <param name="cmd"></param>
/// <param name="execUser"></param>
/// <param name="workDir"></param>
/// <param name="envMap"></param>
/// <param name="limit"></param>
/// <param name="stdoutFile"></param>
/// <returns></returns>
virtual int syncSpawnProcess(std::string cmd, std::string execUser, std::string workDir, std::map<std::string, std::string> envMap, std::shared_ptr<ResourceLimitation> limit, std::string stdoutFile) noexcept(false);
protected:
std::string m_dockerImage;
std::string m_containerId;
std::string m_containerName;
std::shared_ptr<AppProcess> m_imagePullProc;
mutable std::recursive_mutex m_processMutex;
};
|
HanixNicolas/app-mesh
|
src/daemon/security/ldapplugin/ldapcpp/cldap_entry.h
|
<reponame>HanixNicolas/app-mesh
/***************************************************************************
* Copyright (C) 2012 by <NAME> *
* <EMAIL> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef CLDAP_ENTRY_H
#define CLDAP_ENTRY_H
#include <memory>
#include "cldap_mod.h"
namespace Ldap
{
class Server;
class Entry
{
public:
Entry(const std::string &);
~Entry();
void SetDN(const std::string &);
const std::string &DN(void) const;
void Append(int, const std::string &, const std::string &);
void Append(int, const std::string &, const std::vector<std::string> &);
void Append(int, const std::string &, const std::list<std::string> &);
void Append(int, const std::string &, const std::vector<char> &);
void Append(int, const std::string &, const std::vector<std::vector<char>> &);
void Append(int, const std::string &, const std::list<std::vector<char>> &);
std::string GetStringValue(const std::string &) const;
std::vector<std::string>
GetStringValues(const std::string &) const;
std::list<std::string>
GetStringList(const std::string &) const;
std::vector<char> GetBinaryValue(const std::string &) const;
std::vector<std::vector<char>>
GetBinaryValues(const std::string &) const;
std::list<std::vector<char>>
GetBinaryList(const std::string &) const;
int Size(void) const { return values.size(); }
protected:
friend class Server;
friend std::ostream &operator<<(std::ostream &, const Entry &);
typedef std::vector<std::shared_ptr<ModBase>>::iterator iterator;
typedef std::vector<std::shared_ptr<ModBase>>::const_iterator const_iterator;
std::vector<LDAPMod *>
toLDAPMods(void) const;
iterator PushBack(const std::string &type, int op, bool binary);
const_iterator FindType(const std::string &) const;
std::string dn;
std::vector<std::shared_ptr<ModBase>>
values;
};
std::ostream &operator<<(std::ostream &, const Entry &);
}
#endif
|
HanixNicolas/app-mesh
|
src/daemon/rest/RestChildObject.h
|
#pragma once
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <ace/Message_Block.h>
#include <ace/SOCK_Connector.h>
#include <ace/SOCK_Stream.h>
#include "HttpRequest.h"
#include "RestHandler.h"
/// <summary>
/// REST Server Object, forward http REST request to TCP Server side
/// </summary>
class RestChildObject : public ACE_SOCK_Connector, public RestHandler
{
public:
RestChildObject();
virtual ~RestChildObject();
static std::shared_ptr<RestChildObject> instance();
static void instance(std::shared_ptr<RestChildObject> restClientObj);
/// <summary>
/// Connect to TCP REST Server and block read REST response from TCP side.
/// </summary>
/// <param name="port"></param>
void connectAndRun(int port);
/// <summary>
/// Send REST request to TCP Server side and cache HttpRequest for replyResponse()
/// </summary>
/// <param name="message"></param>
void sendRequest2Server(const HttpRequest &message);
/// <summary>
/// Reply REST Response
/// </summary>
/// <param name="msg"></param>
void replyResponse(ACE_Message_Block *response);
/// <summary>
/// Read Message Block from Socket Stream
/// </summary>
/// <param name="socket"></param>
/// <returns></returns>
static ACE_Message_Block *readMessageBlock(const ACE_SOCK_Stream &socket);
private:
ACE_SOCK_Stream m_socketStream;
// key: message uuid; value: message
std::map<std::string, HttpRequest> m_sentMessages;
mutable std::recursive_mutex m_mutex;
static std::shared_ptr<RestChildObject> m_instance;
};
|
HanixNicolas/app-mesh
|
src/daemon/TimerHandler.h
|
#pragma once
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <ace/Event_Handler.h>
#include <ace/Reactor.h>
//////////////////////////////////////////////////////////////////////////
/// Timer Event base class
/// The class which use timer event should implement from this class.
/// Note: enable_shared_from_this does not support stack allocation!
/// http://blog.chinaunix.net/uid-442138-id-2122464.html
//////////////////////////////////////////////////////////////////////////
class TimerHandler : public ACE_Event_Handler, public std::enable_shared_from_this<TimerHandler>
{
private:
/// <summary>
/// One timer event
/// </summary>
struct TimerEvent
{
/// <summary>
/// TimerEvent construction
/// </summary>
/// <param name="timerId">timerId will be deleted in TimerEvent de-construction</param>
/// <param name="handler">timer function</param>
/// <param name="object">timer object</param>
/// <param name="callOnce">only run one-time</param>
explicit TimerEvent(int *timerId, std::function<void(int)> handler, const std::shared_ptr<TimerHandler> object, bool callOnce);
const std::shared_ptr<int> m_timerId;
std::function<void(int)> m_handler;
const std::shared_ptr<TimerHandler> m_timerObject;
const bool m_callOnce;
};
/**
* Timer expire call back function, override from ACE
* Called when timer expires. @a current_time represents the current
* time that the Event_Handler was selected for timeout
* dispatching and @a act is the asynchronous completion token that
* was passed in when <schedule_timer> was invoked.
*/
virtual int handle_timeout(const ACE_Time_Value ¤t_time, const void *act = 0) override final;
public:
TimerHandler();
virtual ~TimerHandler();
/// <summary>
/// Register a timer to this object
/// </summary>
/// <param name="delaySeconds">Timer will start after delay milliseconds [1/1000 second].</param>
/// <param name="intervalSeconds">Interval for the Timer, the value 0 means the timer will only triggered once.</param>
/// <param name="handler">Function point to this object.</param>
/// <return>Timer unique ID.</return>
int registerTimer(long int delayMillisecond, std::size_t intervalSeconds, const std::function<void(int)> &handler, const std::string &from);
/// <summary>
/// Cancel a timer
/// </summary>
/// <param name="timerId">Timer unique ID.</param>
/// <return>Cancel success or not.</return>
bool cancelTimer(int &timerId);
/// <summary>
/// Use ACE_Reactor for timer event, block function, should used in a thread
/// </summary>
static void runReactorEvent(ACE_Reactor *reactor);
/// <summary>
/// End ACE_Reactor
/// </summary>
static int endReactorEvent(ACE_Reactor *reactor);
private:
// key: timer ID point, must unique, value: function point
std::map<const int *, std::shared_ptr<TimerEvent>> m_timers;
protected:
// this reactor can be init as none-default one
ACE_Reactor *m_reactor;
mutable std::recursive_mutex m_timerMutex;
};
|
HanixNicolas/app-mesh
|
src/daemon/security/ldapplugin/ldapcpp/cldap_types.h
|
/***************************************************************************
* Copyright (C) 2012 by <NAME> *
* <EMAIL> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef CLDAP_TYPES_H
#define CLDAP_TYPES_H
#include <iostream>
#include <ldap.h>
#include <list>
#include <string>
#include <vector>
#define CLDAP_VERSION 20180427
namespace Ldap
{
class Entry;
enum Action
{
ActionAdd = LDAP_MOD_ADD,
ActionDelete = LDAP_MOD_DELETE,
ActionReplace = LDAP_MOD_REPLACE
};
enum Scope
{
ScopeBase = LDAP_SCOPE_BASE,
ScopeOne = LDAP_SCOPE_ONELEVEL,
ScopeTree = LDAP_SCOPE_SUBTREE
};
typedef std::list<Entry> ListEntries;
typedef std::list<std::string> ListAttrs;
}
namespace Base64
{
std::vector<char> encode(const char *, size_t);
std::vector<char> decode(const char *, size_t);
std::string StringWrap(const std::string &, const std::string &);
void SetBinaryOnly(bool);
}
#endif
|
HanixNicolas/app-mesh
|
src/prom_exporter/check_names.h
|
#pragma once
#include <string>
#include "detail/core_export.h"
namespace prometheus {
PROMETHEUS_CPP_CORE_EXPORT bool CheckMetricName(const std::string& name);
PROMETHEUS_CPP_CORE_EXPORT bool CheckLabelName(const std::string& name);
} // namespace prometheus
|
HanixNicolas/app-mesh
|
src/daemon/consul/ConsulEntity.h
|
<reponame>HanixNicolas/app-mesh
#pragma once
#include <chrono>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <tuple>
#include <cpprest/json.h>
class Application;
class Label;
struct ConsulTask;
/// <summary>
/// Consul Node definition
/// </summary>
struct ConsulNode
{
ConsulNode();
static std::shared_ptr<ConsulNode> FromJson(const web::json::value &jsonObj, const std::string &hostName);
web::json::value AsJson() const;
void dump();
/// @brief For schedule sort
/// @param app
void assignApp(const std::shared_ptr<ConsulTask> &task);
bool tryAssignApp(const std::shared_ptr<ConsulTask> &task);
bool full();
/// @brief For schedule sort
/// @return
uint64_t getAssignedAppMem() const;
std::shared_ptr<Label> m_label;
// CPU
std::size_t m_cores;
// MEM
uint64_t m_total_bytes;
uint64_t m_occupyMemoryBytes;
std::string m_appmeshProxyUrl;
std::string m_hostName;
bool m_leader;
std::map<std::string, std::shared_ptr<Application>> m_assignedApps;
};
/// <summary>
/// Cluster level application definition with replication and node selector
/// </summary>
struct ConsulTask
{
ConsulTask();
static std::shared_ptr<ConsulTask> FromJson(const web::json::value &jsonObj);
web::json::value AsJson() const;
void dump();
bool operator==(const std::shared_ptr<ConsulTask> &task);
std::size_t m_replication;
std::shared_ptr<Application> m_app;
// schedule parameters
std::shared_ptr<Label> m_condition;
int m_priority;
// consul service port
int m_consulServicePort;
// request memory, MB
uint64_t m_requestMemMega;
// used for schedule fill
std::map<std::string, std::shared_ptr<ConsulNode>> m_matchedHosts;
/// @brief Used for schedule fill, store all index, index start from 1
/// If one task have 4 replica, the set will have 1,2,3,4
std::set<int> m_tasksSet;
};
/// <summary>
/// Topology is leader schedule result
/// </summary>
struct ConsulTopology
{
static std::shared_ptr<ConsulTopology> FromJson(const web::json::value &jsonObj, const std::string &hostName);
web::json::value AsJson() const;
bool operator==(const std::shared_ptr<ConsulTopology> &topology);
void dump();
/// @brief Topology is organized by host for performance consideration
std::string m_hostName;
/// @brief Dispatched tasks on this host
/// key: app name. value: <date time>
std::map<std::string, std::chrono::system_clock::time_point> m_scheduleApps;
};
|
HanixNicolas/app-mesh
|
src/daemon/security/ldapplugin/LdapGroup.h
|
<reponame>HanixNicolas/app-mesh<filename>src/daemon/security/ldapplugin/LdapGroup.h
#pragma once
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <cpprest/json.h>
class Role;
class Roles;
//////////////////////////////////////////////////////////////////////////
/// LDAP Group
//////////////////////////////////////////////////////////////////////////
class LdapGroup
{
public:
explicit LdapGroup(const std::string &name) : m_groupName(name){};
virtual ~LdapGroup(){};
// serialize
web::json::value AsJson() const;
// de-serialize
static std::shared_ptr<LdapGroup> FromJson(const std::string &groupName, const web::json::value &obj, const std::shared_ptr<Roles> roles) noexcept(false);
void updateGroup(std::shared_ptr<LdapGroup> group);
public:
mutable std::recursive_mutex m_mutex;
const std::string m_groupName;
std::string m_bindDN;
std::set<std::shared_ptr<Role>> m_roles;
};
//////////////////////////////////////////////////////////////////////////
/// LDAP Groups
//////////////////////////////////////////////////////////////////////////
class LdapGroups
{
public:
LdapGroups(){};
virtual ~LdapGroups(){};
std::shared_ptr<LdapGroup> getGroup(const std::string &name);
web::json::value AsJson() const;
static const std::shared_ptr<LdapGroups> FromJson(const web::json::value &obj, std::shared_ptr<Roles> roles) noexcept(false);
std::shared_ptr<LdapGroup> addGroup(const web::json::value &obj, std::string name, std::shared_ptr<Roles> roles);
void delGroup(const std::string &name);
std::map<std::string, std::shared_ptr<LdapGroup>> getGroups() const;
private:
std::map<std::string, std::shared_ptr<LdapGroup>> m_groups;
mutable std::recursive_mutex m_mutex;
};
//////////////////////////////////////////////////////////////////////////
/// JsonLdap
//////////////////////////////////////////////////////////////////////////
struct JsonLdap
{
JsonLdap();
static std::shared_ptr<JsonLdap> FromJson(const web::json::value &jsonValue);
web::json::value AsJson() const;
std::string m_ldapUri;
std::shared_ptr<LdapGroups> m_groups;
std::shared_ptr<Roles> m_roles;
};
|
HanixNicolas/app-mesh
|
src/daemon/rest/HttpRequest.h
|
#pragma once
#include <functional>
#include <map>
#include <memory>
#include <ace/CDR_Stream.h>
#include <cpprest/http_client.h>
using namespace web;
using namespace http;
#define CONTENT_TYPE_APPLICATION_JSON "application/json"
/// <summary>
/// HttpRequest is wrapper of <web::http::http_request>,
/// - used for REST server forward request to TCP server and wait TCP result then response REST client
/// - used for TCP server send result to REST server
/// serialize between RestTcpServer & RestChildObject
/// handle across domain reply (headers)
/// </summary>
class HttpRequest : public web::http::http_request
{
private:
/// <summary>
/// Construction for deserialize
/// TCP REST Server receive and decode this, m_forwardResponse2RestServer always set to true
/// </summary>
HttpRequest(const std::string &uuid,
const std::string &method,
const std::string &uri,
const std::string &address,
const std::string &body,
const std::string &headers,
const std::string &query);
public:
HttpRequest(const web::http::http_request &message);
/// <summary>
/// Constructor for RestChildObject::sendRequest2Server() save http_request copy
/// and send the response to REST client after received TCP response
/// </summary>
HttpRequest(const HttpRequest &message);
virtual ~HttpRequest();
/// <summary>
/// Always use this function to get http body
/// http body will always be extract with string (for serialize purpose) and parse to JSON here
/// </summary>
web::json::value extractJson() const;
/// <summary>
/// Asynchronously responses to this HTTP request.
/// </summary>
/// <param name="response">Response to send.</param>
/// <returns>An asynchronous operation that is completed once response is sent.</returns>
void reply(http_response &response) const;
/// <summary>
/// Asynchronously responses to this HTTP request.
/// </summary>
/// <param name="response">Response to send.</param>
/// <returns>An asynchronous operation that is completed once response is sent.</returns>
void reply(http_response &response, const std::string &body_data) const;
/// <summary>
/// Asynchronously responses to this HTTP request.
/// </summary>
/// <param name="status">Response status code.</param>
/// <returns>An asynchronous operation that is completed once response is sent.</returns>
void reply(http::status_code status) const;
/// <summary>
/// Responds to this HTTP request.
/// </summary>
/// <param name="status">Response status code.</param>
/// <param name="body_data">Json value to use in the response body.</param>
/// <returns>An asynchronous operation that is completed once response is sent.</returns>
void reply(http::status_code status, const json::value &body_data) const;
/// Responds to this HTTP request with a string.
/// Assumes the character encoding of the string is UTF-8.
/// </summary>
/// <param name="status">Response status code.</param>
/// <param name="body_data">UTF-8 string containing the text to use in the response body.</param>
/// <param name="content_type">Content type of the body.</param>
/// <returns>An asynchronous operation that is completed once response is sent.</returns>
/// <remarks>
// Callers of this function do NOT need to block waiting for the response to be
/// sent to before the body data is destroyed or goes out of scope.
/// </remarks>
void reply(http::status_code status,
utf8string &&body_data,
const utf8string &content_type = "text/plain; charset=utf-8") const;
/// <summary>
/// Responds to this HTTP request with a string.
/// Assumes the character encoding of the string is UTF-8.
/// </summary>
/// <param name="status">Response status code.</param>
/// <param name="body_data">UTF-8 string containing the text to use in the response body.</param>
/// <param name="content_type">Content type of the body.</param>
/// <returns>An asynchronous operation that is completed once response is sent.</returns>
/// <remarks>
// Callers of this function do NOT need to block waiting for the response to be
/// sent to before the body data is destroyed or goes out of scope.
/// </remarks>
void reply(http::status_code status,
const utf8string &body_data,
const utf8string &content_type = "text/plain; charset=utf-8") const;
/// <summary>
/// Responds to this HTTP request with a string. Assumes the character encoding
/// of the string is UTF-16 will perform conversion to UTF-8.
/// </summary>
/// <param name="status">Response status code.</param>
/// <param name="body_data">UTF-16 string containing the text to use in the response body.</param>
/// <param name="content_type">Content type of the body.</param>
/// <returns>An asynchronous operation that is completed once response is sent.</returns>
/// <remarks>
// Callers of this function do NOT need to block waiting for the response to be
/// sent to before the body data is destroyed or goes out of scope.
/// </remarks>
void reply(http::status_code status,
const utf16string &body_data,
const utf16string &content_type = utility::conversions::to_utf16string("text/plain")) const;
/// <summary>
/// Responds to this HTTP request.
/// </summary>
/// <param name="status">Response status code.</param>
/// <param name="content_type">A string holding the MIME type of the message body.</param>
/// <param name="body">An asynchronous stream representing the body data.</param>
/// <returns>A task that is completed once a response from the request is received.</returns>
void reply(status_code status,
const concurrency::streams::istream &body,
const utility::string_t &content_type = _XPLATSTR("application/octet-stream")) const;
/// <summary>
/// Responds to this HTTP request.
/// </summary>
/// <param name="status">Response status code.</param>
/// <param name="content_length">The size of the data to be sent in the body..</param>
/// <param name="content_type">A string holding the MIME type of the message body.</param>
/// <param name="body">An asynchronous stream representing the body data.</param>
/// <returns>A task that is completed once a response from the request is received.</returns>
void reply(status_code status,
const concurrency::streams::istream &body,
utility::size64_t content_length,
const utility::string_t &content_type = _XPLATSTR("application/octet-stream")) const;
// serialize header
static std::map<std::string, std::string> parseHeaders(const std::string &str);
static std::string serializeHeaders(const std::map<std::string, std::string> &map);
static std::string serializeHeaders(const web::http::http_headers &map);
const std::shared_ptr<ACE_OutputCDR> serialize() const;
static std::shared_ptr<HttpRequest> deserialize(ACE_InputCDR &input);
// serializeable, always use those variables intead of method(), headers()
std::string m_uuid;
web::http::method m_method;
std::string m_relative_uri;
std::string m_remote_address;
std::string m_body;
std::map<std::string, std::string> m_headers;
std::string m_query;
bool m_forwardResponse2RestServer; // not directly reply this endpoint, just forward to child rest side
private:
// hide bellow extract functions, note extract_X function can only be called once, otherwise will hang
pplx::task<utf8string> extract_utf8string(bool ignore_content_type = false)
{
return web::http::http_request::extract_utf8string(ignore_content_type);
};
pplx::task<utility::string_t> extract_string(bool ignore_content_type = false)
{
return web::http::http_request::extract_string(ignore_content_type);
};
pplx::task<utf16string> extract_utf16string(bool ignore_content_type = false)
{
return web::http::http_request::extract_utf16string(ignore_content_type);
};
pplx::task<json::value> extract_json(bool ignore_content_type = false) const
{
return web::http::http_request::extract_json(ignore_content_type);
};
};
/// <summary>
/// HttpTcpResponse is the data of REST response used to transfer to REST process
/// </summary>
class HttpTcpResponse
{
public:
explicit HttpTcpResponse(const std::string &uuid,
const std::string &body,
const std::string &bodyType,
const std::map<std::string, std::string> &headers,
const http::status_code &status);
const std::shared_ptr<ACE_OutputCDR> serialize() const;
static std::shared_ptr<HttpTcpResponse> deserialize(ACE_InputCDR &input);
public:
const std::string m_uuid;
const std::string m_body;
const std::string m_bodyType;
const std::map<std::string, std::string> m_headers;
const http::status_code m_status;
};
/// <summary>
/// IoVector used prepare sendout data to header and body
/// </summary>
struct IoVector
{
public:
explicit IoVector(std::shared_ptr<ACE_OutputCDR> body);
// length is 2, header and body
iovec data[2];
const size_t length() { return data[0].iov_len + data[1].iov_len; };
private:
ACE_OutputCDR m_headerCdr;
std::shared_ptr<ACE_OutputCDR> m_bodyCdr;
};
class Application;
/// <summary>
/// HttpRequest used to remove template Application when finished reply
/// </summary>
class HttpRequestWithAppRef : public HttpRequest
{
public:
HttpRequestWithAppRef(const HttpRequest &message, const std::shared_ptr<Application> &appObj);
virtual ~HttpRequestWithAppRef();
private:
const std::shared_ptr<Application> m_app;
};
|
HanixNicolas/app-mesh
|
src/daemon/security/User.h
|
#pragma once
#include <map>
#include <mutex>
#include <set>
#include <string>
#include <cpprest/json.h>
#include "Role.h"
//////////////////////////////////////////////////////////////////////////
/// User
//////////////////////////////////////////////////////////////////////////
class User
{
public:
explicit User(const std::string &name);
virtual ~User();
// serialize
web::json::value AsJson() const;
static std::shared_ptr<User> FromJson(const std::string &userName, const web::json::value &obj, const std::shared_ptr<Roles> roles) noexcept(false);
// user update
void lock();
void unlock();
void updateUser(std::shared_ptr<User> user);
void updateKey(const std::string &passwd);
// get user info
bool locked() const;
const std::string getKey();
const std::string &getExecUser() const
{
std::lock_guard<std::recursive_mutex> guard(m_mutex);
return m_execUser;
}
const std::string &getGroup() const
{
std::lock_guard<std::recursive_mutex> guard(m_mutex);
return m_group;
}
const std::string &getName() const
{
std::lock_guard<std::recursive_mutex> guard(m_mutex);
return m_name;
}
const std::set<std::shared_ptr<Role>> getRoles();
bool hasPermission(const std::string &permission);
const std::string encrypt(const std::string &msg);
const std::string decrypt(const std::string &msg);
private:
std::string m_key;
bool m_locked;
std::string m_name;
std::string m_group;
std::string m_metadata;
std::string m_execUser;
mutable std::recursive_mutex m_mutex;
std::set<std::shared_ptr<Role>> m_roles;
};
class Users
{
public:
Users();
virtual ~Users();
web::json::value AsJson() const;
static std::shared_ptr<Users> FromJson(const web::json::value &obj, std::shared_ptr<Roles> roles) noexcept(false);
// find user
std::map<std::string, std::shared_ptr<User>> getUsers();
std::shared_ptr<User> getUser(std::string name) const;
std::set<std::string> getGroups() const;
// manage users
void addUsers(const web::json::value &obj, std::shared_ptr<Roles> roles);
std::shared_ptr<User> addUser(const std::string &userName, const web::json::value &userJson, std::shared_ptr<Roles> roles);
void delUser(const std::string &name);
private:
std::map<std::string, std::shared_ptr<User>> m_users;
mutable std::recursive_mutex m_mutex;
};
struct JsonSecurity
{
JsonSecurity();
static std::shared_ptr<JsonSecurity> FromJson(const web::json::value &jsonObj);
web::json::value AsJson();
bool m_encryptKey;
std::string m_jwtSalt;
std::shared_ptr<Users> m_users;
std::shared_ptr<Roles> m_roles;
};
|
henryly94/pocketbook
|
src/entity.h
|
<filename>src/entity.h
#ifndef ENTITY_H_
#define ENTITY_H_
#include <string>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/time/time.h"
namespace yypocketbook {
struct Transaction {
enum Type {
CREDIT,
DEBIT,
};
Type type;
double amount;
absl::Time timestamp;
std::string detail;
};
class Entity {
public:
enum Type {
ASSET = 0,
EXPENSE,
LIABILITY,
EQUITY,
REVENUE,
};
static const std::vector<std::string> type_string_;
static const absl::flat_hash_map<std::string, Type> string_to_type_;
Entity() {}
explicit Entity(std::string name, Type type, double amount = 0.0,
std::vector<Transaction> transaction_history = {})
: name(name), type(type), amount(amount),
transaction_history(std::move(transaction_history)) {}
Entity(const Entity &entity)
: name(entity.name), type(entity.type), amount(entity.amount),
transaction_history(entity.transaction_history) {}
Entity &operator=(const Entity &entity) {
name = entity.name;
type = entity.type;
amount = entity.amount;
transaction_history = entity.transaction_history;
return *this;
}
Type GetType() const { return type; }
double GetAmount() const { return amount; }
std::string GetName() const { return name; }
const std::vector<Transaction> &GetHistory() const {
return transaction_history;
}
void AddTransaction(const Transaction &transaction);
absl::flat_hash_set<Type> &LeftsideType() const;
void Print() const;
~Entity() {}
private:
Type type;
double amount;
std::string name;
std::vector<Transaction> transaction_history;
};
} // namespace yypocketbook
#endif // ENTITY_H_
|
henryly94/pocketbook
|
src/util.h
|
#ifndef UTIL_H_
#define UTIL_H_
#include "absl/container/flat_hash_map.h"
#include "book.h"
#include "messages.pb.h"
namespace yypocketbook {
class Util {
public:
static protobuf::Book MakeProtobufBook(const Book &book);
static protobuf::Entity MakeProtobufEntity(const Entity &entity);
static protobuf::Transaction
MakeProtobufTransaction(const Transaction &transaction);
static Book MakeBook(const protobuf::Book &proto_book);
static Entity MakeEntity(const protobuf::Entity &proto_entity);
static Transaction
MakeTransaction(const protobuf::Transaction &proto_transaction);
private:
const static protobuf::Entity_Type get_protobuf_entity_type_[];
const static protobuf::Transaction_Type get_protobuf_transaction_type_[];
const static absl::flat_hash_map<protobuf::Entity_Type, Entity::Type>
get_entity_type_;
const static absl::flat_hash_map<protobuf::Transaction_Type,
Transaction::Type>
get_transaction_type_;
};
} // namespace yypocketbook
#endif // UTIL_H_
|
henryly94/pocketbook
|
src/book.h
|
<reponame>henryly94/pocketbook
#ifndef BOOK_H_
#define BOOK_H_
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "entity.h"
namespace yypocketbook {
using EntityFeature = std::pair<Entity::Type, std::string>;
using EntityFilter = std::function<bool(const Entity &)>;
class Book {
public:
explicit Book() {}
explicit Book(const std::vector<EntityFeature> &entity_features);
// TODO: Add a function to add complete entity (with
// transactions, converted from protobuf).
void AddEntity(Entity::Type entity_type, const std::string &entity_name,
double amount = 0);
void AddTransaction(double amount, absl::string_view from_account_name,
const std::string &to_account_name,
absl::string_view detail, absl::Time timestamp);
void LoadTSVConfig(absl::string_view file_path);
void DumpToDisk(absl::string_view file_path);
void LoadFromDisk(absl::string_view file_path);
void Print() const;
void PrintWithFilter(EntityFilter filter) const;
const absl::flat_hash_map<std::string, Entity> &GetEntityMap() const {
return entity_map_;
}
private:
absl::flat_hash_map<std::string, Entity> entity_map_;
};
} // namespace yypocketbook
#endif // BOOK_H_
|
Colbeyyy/eden
|
src/gui.h
|
#pragma once
#include <ch_stl/string.h>
#include <ch_stl/math.h>
struct Vertical_Layout {
f32 row_height;
f32 top_x;
f32 left_y;
f32 width;
f32 at_x;
f32 at_y;
Vertical_Layout(f32 _top_x, f32 _left_y, f32 _row_height) : top_x(_top_x), left_y(_left_y), row_height(_row_height), at_x(_top_x), at_y(_left_y) {}
void row();
void row(f32 height);
};
struct UI_ID {
u32 ptr = 0;
u32 index = 0;
UI_ID() = default;
UI_ID(const void* in_ptr) : ptr((u32)in_ptr), index(0) {}
UI_ID(const void* in_ptr, usize in_index) : ptr((u32)in_ptr), index(in_index) {}
bool operator==(UI_ID other) const {
return ptr == other.ptr && index == other.index;
}
bool operator!=(UI_ID other) const {
return !(*this == other);
}
operator bool() const { return ptr || index; }
};
CH_FORCEINLINE bool is_point_in_rect(ch::Vector2 p, f32 x0, f32 y0, f32 x1, f32 y1) {
return p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1;
}
void gui_label(const ch::String& s, const ch::Color& color, f32 x, f32 y);
CH_FORCEINLINE void gui_label(UI_ID id, const char* s, const ch::Color& color, f32 x, f32 y) {
ch::String real;
real.data = (char*)s;
real.count = ch::strlen(s);
gui_label(real, color, x, y);
}
bool gui_button(UI_ID id, f32 x0, f32 y0, f32 x1, f32 y1);
bool gui_button_label(UI_ID id, const ch::String& s, f32 x0, f32 y0, f32 x1, f32 y1);
CH_FORCEINLINE bool gui_button_label(UI_ID id, const char* s, f32 x0, f32 y0, f32 x1, f32 y1) {
ch::String real;
real.data = (char*)s;
real.count = ch::strlen(s);
return gui_button_label(id, real, x0, y0, x1, y1);
}
void tick_gui();
|
Colbeyyy/eden
|
src/editor.h
|
#pragma once
#include <ch_stl/window.h>
extern ch::Window the_window;
extern struct Font the_font;
|
Colbeyyy/eden
|
src/buffer.h
|
#pragma once
#include <ch_stl/filesystem.h>
#include <ch_stl/gap_buffer.h>
#include <ch_stl/hash.h>
#include "draw.h"
#include "parsing.h"
using Buffer_ID = usize;
const usize invalid_buffer_id = 0;
CH_FORCEINLINE u64 hash(Buffer_ID id) {
return ch::fnv1_hash(&id, sizeof(Buffer_ID));
}
/**
* Gets the column size of char
*
* @TODO: Move to somewhere else
*/
u32 get_char_column_size(u32 c);
enum Line_Ending {
LE_NIX, // \n
LE_CRLF // \r\n
};
CH_FORCEINLINE const char* get_line_ending_display(Line_Ending ending) {
switch (ending) {
case LE_NIX:
return "unix";
case LE_CRLF:
return "crlf";
}
return nullptr;
}
/** Encoding of the loaded buffer. Default for buffers will be user defined. As more encodings are added this needs to be updated. */
enum Buffer_Encoding {
BE_ANSI,
BE_UTF8
};
CH_FORCEINLINE const char* get_buffer_encoding_display(Buffer_Encoding encoding) {
switch (encoding) {
case BE_ANSI:
return "ansi";
case BE_UTF8:
return "utf-8";
}
return nullptr;
}
enum Buffer_Flags {
BF_File = 1,
BF_Scratch = 1 << 1,
BF_ReadOnly = 1 << 2,
};
/**
* Wrapper around gap buffer that keeps cached data about the contents of the gap buffer
*
* @see ch:Gap_Buffer
*/
struct Buffer {
Buffer_ID id = invalid_buffer_id;
/** Gap Buffer used to reduce moving bytes with every char press. */
ch::Gap_Buffer<u8> gap_buffer;
/** Absolute path to the file this buffer will save to. */
ch::Path absolute_path;
/** Name used for powerline display and buffer lookup. */
ch::String name;
/**
* Linear table where index is line index and value is the size of the line with eol characters in bytes
* Used for moving up and down lines in a fast manner
*
* @see refresh_eol_table
*/
ch::Array<u32> eol_table;
/**
* Linear table where index is line index and value is the size of line with eol characters in col count
* Used for rendering
*
* @see refresh_line_column_table
*/
ch::Array<u32> line_column_table;
/**
* Current line endings used in this buffer.
*
* @see load_file_into_buffer for how we determine what line_ending to use
*/
Line_Ending line_ending = LE_NIX;
/**
* Encoding of the current buffer. Default is defined by user but is also dtermined if file is loaded
*
* @see load_file_into_buffer
*/
Buffer_Encoding encoding = BE_UTF8;
/**
* Attributes to give details about what type of buffer this is.
*
* @see Buffer_Flags
*/
u8 flags = 0;
/**
* Keeps track if file is dirty
*
* @temp until we have undo/redo
*/
bool is_dirty = false;
bool disable_parse = false;
bool syntax_dirty = true;
ch::Array<parsing::Lexeme> lexemes;
f64 lex_time = 0;
f64 parse_time = 0;
u64 lex_parse_count = 0;
Buffer() = default;
Buffer(Buffer_ID _id);
/**
* Loads a file into this buffer. Will also determine what line endings to use and what encoding the file is.
*
* @param path is the path to the file. Can be relative or absolute.
* @returns true if the file was loaded
*/
bool load_file_into_buffer(const ch::Path& path);
/**
* Saves to a file at the listed path.
*
* @returns true if save was successful
*/
bool save_file_to_path();
/** Empties the gap buffer and resets all cached state. */
void empty();
/** Frees all dynamic memory. */
void free();
void add_char(u32 c, usize index);
void remove_char(usize index);
void print_to(const char* fmt, ...);
/**
* Clears cached data and runs through entire buffer to rebuild it.
*
* @speed this is O(n) but requires decoding
* @note this will probably be deprecated. Just using now due to laziness
*/
void refresh_line_tables();
/**
* Finds the next codepoint based on file encoding
* Returns gap_buffer.count() for end of buffer
*
* @param index is the location to start searching at
* @return is the found "next" index
*/
usize find_next_char(usize index);
/**
* Finds prev codepoint based on file encoding
* Returns 0 for beginning of buffer
*
* @param index is the location to start searching at
* @return is the found "prev" index
*/
usize find_prev_char(usize index);
/**
* Decodes character at codepoint index
*
* @param index is the char codepoint
* @returns decoded char based on file encoding
*/
u32 get_char(usize index);
u64 get_index_from_line(u64 line) const;
u64 get_line_from_index(u64 index) const;
u64 get_wrapped_line_from_index(u64 index, u64 max_line_width) const;
/** @temp */
void mark_file_dirty();
};
/** Creates a new buffer and @returns the new buffer's id. */
Buffer_ID create_buffer();
/**
* Finds the buffer via Buffer_ID.
*
* @param id is the buffer's id we're trying to find.
* @returns a pointer to the actual buffer.
*/
Buffer* find_buffer(Buffer_ID id);
/**
* Removes the buffer with the id given.
*
* @param id is the buffer's id we're trying to remove.
* @returns true if the buffer was removed.
*/
bool remove_buffer(Buffer_ID id);
|
Colbeyyy/eden
|
src/parsing.h
|
#pragma once
#include <ch_stl/types.h>
struct Buffer;
// C++ lexing/parsing tools.
namespace parsing {
// This is the actual DFA state machine. It's not perfect,
// but I (phillip) can get it to run at 13mloc/s on a 3.6 GHz machine
// with 1600 MHz DDR3 RAM and, as of writing, YEET's UTF-8 gap buffer.
// It does as little as it can; it tries not to *parse* C++, only lex it.
// This means it just scans comments and string/number literals (mostly).
// It doesn't even recognize keywords, it just treats all identifiers alike.
// The tradeoff is that this puts an increased burden of code processing
// onto the parser. There is no nesting of any kind.
// I don't yet know the optimal ordering here for cache-efficiency, if there is
// one; I will have to write some sort of randomizer/permutation-checker.
enum Lex_Dfa : u8 {
DFA_BLOCK_COMMENT,
DFA_BLOCK_COMMENT_STAR,
DFA_LINE_COMMENT,
DFA_WHITE,
DFA_WHITE_BS,
DFA_NEWLINE,
DFA_STRINGLIT,
DFA_STRINGLIT_BS,
DFA_CHARLIT,
DFA_CHARLIT_BS,
DFA_SLASH,
DFA_IDENT,
DFA_OP,
DFA_OP2,
DFA_NUMLIT,
DFA_NUM_STATES,
DFA_PREPROC,
DFA_MACRO,
DFA_TYPE,
DFA_KEYWORD,
DFA_FUNCTION,
DFA_PARAM,
DFA_LABEL,
};
// This is an enum for categorizing C++ source code characters.
// Since the lexer uses a table-based DFA, all of its relevant
// char types need to be numerically adjacent, so that they can
// index a contiguous cache-friendly table.
// Strictly speaking, a real lexer would also process digraphs,
// but digraphs are rarely used. Trigraphs are never used.
enum Char_Type : u8 {
WHITE ,
NEWLINE , // '\r' '\n'
IDENT , // '$' '@'-'Z' '_'-'z'
DOUBLEQUOTE, // '"'
SINGLEQUOTE, // '\''
DIGIT , // '0'-'9'
SLASH , // '/'
STAR , // '*'
BS , // '\\'
OP ,
NUM_CHAR_TYPES,
};
struct Lexeme {
const u8* i;
u8 dfa;
u8 cached_first;
CH_FORCEINLINE u8 c() const { return cached_first; }
};
bool is_keyword(const Lexeme* l);
void parse_cpp(Buffer* b);
} // namespace parsing
|
Colbeyyy/eden
|
src/parsing_cpp_keywords.h
|
#if 1
#define CPP_KEYWORDS_2(X) \
X(do) \
X(if) \
X(or) \
#define CPP_KEYWORDS_3(X) \
X(and) \
X(asm) \
X(for) \
X(int) \
X(new) \
X(not) \
X(try) \
X(xor) \
#define CPP_KEYWORDS_4(X) \
X(auto) \
X(bool) \
X(case) \
X(char) \
X(else) \
X(enum) \
X(goto) \
X(long) \
X(this) \
X(true) \
X(void) \
#define CPP_KEYWORDS_5(X) \
X(bitor) \
X(break) \
X(catch) \
X(class) \
X(compl) \
X(const) \
X(false) \
X(float) \
X(or_eq) \
X(short) \
X(throw) \
X(union) \
X(using) \
X(while) \
#define CPP_KEYWORDS_6(X) \
X(and_eq) \
X(bitand) \
X(delete) \
X(double) \
X(export) \
X(extern) \
X(friend) \
X(inline) \
X(not_eq) \
X(public) \
X(return) \
X(signed) \
X(sizeof) \
X(static) \
X(struct) \
X(switch) \
X(typeid) \
X(xor_eq) \
#define CPP_KEYWORDS_7(X) \
X(alignas) \
X(alignof) \
X(char8_t) \
X(concept) \
X(default) \
X(mutable) \
X(nullptr) \
X(private) \
X(typedef) \
X(virtual) \
X(wchar_t) \
#define CPP_KEYWORDS_8(X) \
X(char16_t) \
X(char32_t) \
X(continue) \
X(co_await) \
X(co_yield) \
X(decltype) \
X(explicit) \
X(noexcept) \
X(operator) \
X(reflexpr) \
X(register) \
X(requires) \
X(template) \
X(typename) \
X(unsigned) \
X(volatile) \
#define CPP_KEYWORDS_9(X) \
X(consteval) \
X(constexpr) \
X(constinit) \
X(co_return) \
X(namespace) \
X(protected) \
#define CPP_KEYWORDS_10(X) \
X(const_cast) \
#define CPP_KEYWORDS_11(X) \
X(static_cast) \
#define CPP_KEYWORDS_12(X) \
X(dynamic_cast) \
X(synchronized) \
X(thread_local) \
#define CPP_KEYWORDS_13(X) \
/*X(atomic_cancel)*/ \
/*X(atomic_commit)*/ \
X(static_assert) \
#define CPP_KEYWORDS_15(X) \
X(atomic_noexcept) \
#define CPP_KEYWORDS_17(X) \
X(reinterpret_cast) \
#else
#define CPP_KEYWORDS(X)
X(alignas ) \
X(alignof ) \
X(and ) \
X(and_eq ) \
X(asm ) \
X(atomic_cancel ) \
X(atomic_commit ) \
X(atomic_noexcept ) \
X(auto ) \
X(bitand ) \
X(bitor ) \
X(bool ) \
X(break ) \
X(case ) \
X(catch ) \
X(char ) \
X(char8_t ) \
X(char16_t ) \
X(char32_t ) \
X(class ) \
X(compl ) \
X(concept ) \
X(const ) \
X(consteval ) \
X(constexpr ) \
X(constinit ) \
X(const_cast ) \
X(continue ) \
X(co_await ) \
X(co_return ) \
X(co_yield ) \
X(decltype ) \
X(default ) \
X(delete ) \
X(do ) \
X(double ) \
X(dynamic_cast ) \
X(else ) \
X(enum ) \
X(explicit ) \
X(export ) \
X(extern ) \
X(false ) \
X(float ) \
X(for ) \
X(friend ) \
X(goto ) \
X(if ) \
X(inline ) \
X(int ) \
X(long ) \
X(mutable ) \
X(namespace ) \
X(new ) \
X(noexcept ) \
X(not ) \
X(not_eq ) \
X(nullptr ) \
X(operator ) \
X(or ) \
X(or_eq ) \
X(private ) \
X(protected ) \
X(public ) \
X(reflexpr ) \
X(register ) \
X(reinterpret_cast) \
X(requires ) \
X(return ) \
X(short ) \
X(signed ) \
X(sizeof ) \
X(static ) \
X(static_assert ) \
X(static_cast ) \
X(struct ) \
X(switch ) \
X(synchronized ) \
X(template ) \
X(this ) \
X(thread_local ) \
X(throw ) \
X(true ) \
X(try ) \
X(typedef ) \
X(typeid ) \
X(typename ) \
X(union ) \
X(unsigned ) \
X(using ) \
X(virtual ) \
X(void ) \
X(volatile ) \
X(wchar_t ) \
X(while ) \
X(xor ) \
X(xor_eq ) \
#endif
|
Colbeyyy/eden
|
src/buffer_view.h
|
<reponame>Colbeyyy/eden
#pragma once
#include "buffer.h"
const f32 min_width_ratio = 0.2f;
struct Buffer_View {
Buffer_ID the_buffer = 0;
f32 width_ratio = 0.5f;
usize cursor = 0;
usize selection = 0;
u64 desired_column = 0;
u64 current_column = 0;
u64 current_line = 0;
f32 current_scroll_y = 0.f;
f32 target_scroll_y = 0.f;
bool show_cursor = true;
f32 cursor_blink_time = 0.f;
CH_FORCEINLINE bool has_selection() const { return cursor != selection; }
CH_FORCEINLINE void reset_cursor_timer() {
show_cursor = true;
cursor_blink_time = 0.f;
}
void remove_selection();
/**
* Updates column and line data
*
* @param update_desired_col if true sets desired_column to current_column
*/
void update_column_info(bool update_desired_col = false);
void ensure_cursor_in_view();
void on_char_entered(u32 c);
};
void tick_views(f32 dt);
Buffer_View* get_focused_view();
usize push_view(Buffer_ID the_buffer);
usize insert_view(Buffer_ID the_buffer, usize index);
bool remove_view(usize view_index);
Buffer_View* get_view(usize index);
|
Colbeyyy/eden
|
src/config.h
|
<gh_stars>10-100
#pragma once
#include <ch_stl/math.h>
#define CONFIG_VAR(macro) \
macro(u16, font_size, 24) \
macro(ch::Color, background_color, 0x052329FF) \
macro(ch::Color, foreground_color, 0xD6B58DFF) \
macro(ch::Color, cursor_color, 0x81E38EFF) \
macro(ch::Color, selection_color, 0x000EFFFF) \
macro(ch::Color, selected_text_color, ch::white) \
macro(bool, show_line_numbers, true) \
macro(ch::Color, line_number_background_color, 0x041E24FF) \
macro(ch::Color, line_number_text_color, 0x083945FF) \
macro(f32, scroll_speed, 50.f) \
macro(u16, tab_width, 4) \
macro(u32, last_window_width, 1920) \
macro(u32, last_window_height, 1080) \
macro(bool, was_maximized, false)
#define PUSH_VARS(t, n, v) t n = v;
struct Config {
CONFIG_VAR(PUSH_VARS);
};
extern Config default_config;
const Config& get_config();
void init_config();
void try_refresh_config();
void shutdown_config();
// @NOTE(Chall): this kind of sucks
void on_window_resize_config();
void on_window_maximized_config();
|
Colbeyyy/eden
|
src/input.h
|
<gh_stars>10-100
#pragma once
#include <ch_stl/input.h>
#include <ch_stl/math.h>
#include <ch_stl/array.h>
#include <ch_stl/hash.h>
extern ch::Vector2 last_mouse_position;
extern ch::Vector2 current_mouse_position;
extern f32 current_mouse_scroll_y;
enum Key_Bind_Modifier {
KBM_None = 0,
KBM_Shift = 1,
KBM_Ctrl = 1 << 1,
KBM_Alt = 1 << 2
};
struct Key_Bind {
u8 modifier_flags;
u32 key;
Key_Bind() : modifier_flags(0), key(0) {}
Key_Bind(u8 _modifier_flags, u32 _key) : modifier_flags(_modifier_flags), key(_key) {}
CH_FORCEINLINE bool operator==(const Key_Bind bind) const {
return modifier_flags == bind.modifier_flags && key == bind.key;
}
};
CH_FORCEINLINE u64 hash(const Key_Bind bind) {
return ch::fnv1_hash(&bind, sizeof(Key_Bind));
}
using Action_Func = void (*)();
/**
* Binds a function to a Key_Bind
*
* @see unbind_action
*
* @param binding used as a key to find the action
* @param action called when binding has been called
* @returns true if the binding was overridden
*/
bool bind_action(const Key_Bind binding, Action_Func action);
/**
* Removes an action binding from all bindings
*
* @see bind_action
*
* @param binding is used to find the action and remove it
* @returns true if the binding was found and removed
*/
bool unbind_action(const Key_Bind binding);
/**
* Checks if a binding is currently bound
*
* @returns true if the binding is currently bound
*/
bool has_action_binding(const Key_Bind binding);
/**
* Removes all bindings
*
* @returns true if a binding was removed.
*/
bool remove_all_bindings();
/** Inits the input system. */
void init_input();
/** Binds all the default bindings. */
void setup_default_bindings();
/** Polls input from the window and executes actions in the action table. */
void process_input();
/** @returns true if exit button on window was pressed. */
bool is_exit_requested();
/** @returns true if a mouse button is down. */
bool is_mouse_button_down(u8 mb);
/** @returns true if a mouse button was pressed this frame. */
bool was_mouse_button_pressed(u8 mb);
/** @returns true if a mouse button was released this frame. */
bool was_mouse_button_released(u8 mb);
|
Colbeyyy/eden
|
src/actions.h
|
<filename>src/actions.h
#pragma once
/** adds a newline to the current buffer. */
void newline();
/** removes the char at the cursor in the current buffer. */
void backspace();
void move_cursor_right(bool move_selection);
void move_cursor_left(bool move_selection);
void move_cursor_up(bool move_selection);
void move_cursor_down(bool move_selection);
void seek_cursor_left(bool move_selection);
void seek_cursor_right(bool move_selection);
void save_buffer();
void open_dialog();
|
Colbeyyy/eden
|
src/draw.h
|
#pragma once
#include <ch_stl/opengl.h>
#include <ch_stl/math.h>
#include <stb/stb_truetype.h>
struct Font_Glyph {
f32 width, height;
f32 bearing_x, bearing_y;
f32 advance;
u32 x0, y0, x1, y1;
};
struct Font_Atlas {
u32 w;
u32 h;
Font_Glyph* glyphs;
};
struct Font {
stbtt_fontinfo info;
u16 size;
f64 atlas_area;
f32 ascent;
f32 descent;
f32 line_gap;
static const usize num_atlases = 129;
Font_Atlas atlases[num_atlases];
GLuint atlas_ids[num_atlases];
s32* codepoints;
u32 num_glyphs;
CH_FORCEINLINE void free() {
ch_delete codepoints;
}
const Font_Glyph* operator[](u32 c) const;
void pack_atlas();
void bind() const;
};
bool load_font_from_path(const ch::Path& path, Font* out_font);
void init_draw();
void refresh_shader_transform();
void render_right_handed();
void frame_begin();
void frame_end();
void imm_begin();
void imm_flush();
void imm_vertex(f32 x, f32 y, const ch::Color& color, ch::Vector2 uv = 0.f, f32 z_index = 9.f);
void imm_quad(f32 x0, f32 y0, f32 x1, f32 y1, const ch::Color& color, f32 z_index = 9.f);
CH_FORCEINLINE void draw_quad(f32 x0, f32 y0, f32 x1, f32 y1, const ch::Color& color, f32 z_index = 9.f) {
imm_begin();
imm_quad(x0, y0, x1, y1, color, z_index);
imm_flush();
}
void imm_glyph(const Font_Glyph* glyph, const Font& font, f32 x, f32 y, const ch::Color& color, f32 z_index = 9.f);
CH_FORCEINLINE void draw_glyph(const Font_Glyph* glyph, const Font& font, f32 x, f32 y, const ch::Color& color, f32 z_index = 9.f) {
imm_begin();
imm_glyph(glyph, font, x, y, color, z_index);
imm_flush();
}
const Font_Glyph* imm_char(const u32 c, const Font& font, f32 x, f32 y, const ch::Color& color, f32 z_index = 9.f);
CH_FORCEINLINE void draw_char(const u32 c, const Font& font, f32 x, f32 y, const ch::Color& color, f32 z_index = 9.f) {
imm_begin();
imm_char(c, font, x, y, color, z_index);
imm_flush();
}
ch::Vector2 imm_string(const ch::String& s, const Font& font, f32 x, f32 y, const ch::Color& color, f32 z_index = 9.f);
CH_FORCEINLINE ch::Vector2 draw_string(const ch::String& s, const Font& font, f32 x, f32 y, const ch::Color& color, f32 z_index = 9.f) {
font.bind();
imm_begin();
const ch::Vector2 result = imm_string(s, font, x, y, color, z_index);
imm_flush();
return result;
}
CH_FORCEINLINE ch::Vector2 imm_string(const char* s, const Font& font, f32 x, f32 y, const ch::Color& color, f32 z_index = 9.f) {
return imm_string(ch::make_stack_string(s), font, x, y, color, z_index);
}
CH_FORCEINLINE ch::Vector2 draw_string(const char* s, const Font& font, f32 x, f32 y, const ch::Color& color, f32 z_index = 9.f) {
font.bind();
imm_begin();
const ch::Vector2 result = imm_string(s, font, x, y, color, z_index);
imm_flush();
return result;
}
ch::Vector2 get_string_draw_size(const ch::String& s, const Font& font);
CH_FORCEINLINE ch::Vector2 get_string_draw_size(const char* s, const Font& font) {
return get_string_draw_size(ch::make_stack_string(s), font);
}
void imm_border_quad(f32 x0, f32 y0, f32 x1, f32 y1, f32 thickness, const ch::Color& color, f32 z_index = 9.f);
CH_FORCEINLINE void draw_border_quad(f32 x0, f32 y0, f32 x1, f32 y1, f32 thickness, const ch::Color& color, f32 z_index = 9.f) {
imm_begin();
imm_border_quad(x0, y0, x1, y1, thickness, color, z_index);
imm_flush();
}
|
CFAthens/lyricsify-mac
|
Pods/Target Support Files/Pods-LyricsifyUITests/Pods-LyricsifyUITests-umbrella.h
|
#ifdef __OBJC__
#import <Cocoa/Cocoa.h>
#endif
FOUNDATION_EXPORT double Pods_LyricsifyUITestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_LyricsifyUITestsVersionString[];
|
CFAthens/lyricsify-mac
|
Pods/Target Support Files/Pods-Lyricsify/Pods-Lyricsify-umbrella.h
|
#ifdef __OBJC__
#import <Cocoa/Cocoa.h>
#endif
FOUNDATION_EXPORT double Pods_LyricsifyVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_LyricsifyVersionString[];
|
CFAthens/lyricsify-mac
|
Pods/Target Support Files/Pods-LyricsifyTests/Pods-LyricsifyTests-umbrella.h
|
<filename>Pods/Target Support Files/Pods-LyricsifyTests/Pods-LyricsifyTests-umbrella.h
#ifdef __OBJC__
#import <Cocoa/Cocoa.h>
#endif
FOUNDATION_EXPORT double Pods_LyricsifyTestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_LyricsifyTestsVersionString[];
|
zfields/mcp23s17-wiring
|
tests/MOCK_wiring.h
|
<filename>tests/MOCK_wiring.h<gh_stars>0
/* Created and copyrighted by <NAME>. Offered as open source under the MIT License (MIT). */
#if defined(TESTING)
#ifndef MOCK_WIRING
#define MOCK_WIRING
#include <cstdint>
#include <functional>
enum BitOrder : uint8_t {
LSBFIRST = 0,
MSBFIRST,
};
enum ClockDivider : uint8_t {
SPI_CLOCK_DIV4 = 0,
SPI_CLOCK_DIV16,
SPI_CLOCK_DIV64,
SPI_CLOCK_DIV128,
SPI_CLOCK_DIV2,
SPI_CLOCK_DIV8,
SPI_CLOCK_DIV32,
};
enum DataMode : uint8_t {
SPI_MODE0 = 0,
SPI_MODE1 = 4,
SPI_MODE2 = 8,
SPI_MODE3 = 12,
};
enum PinMode : uint8_t {
INPUT = 0,
OUTPUT,
INPUT_PULLUP,
};
enum PinValue : uint8_t {
LOW = 0,
HIGH,
};
enum SPIPinAlias : uint8_t {
SS = 10,
MOSI,
MISO,
SCK,
};
struct MOCK_spi {
static bool _has_begun;
static std::function<void(void)> _begin;
static std::function<void(void)> _end;
static std::function<void(uint8_t)> _setBitOrder;
static std::function<void(uint8_t)> _setClockDivider;
static std::function<void(uint8_t)> _setDataMode;
static std::function<uint8_t(uint8_t)> _transfer;
static
void
begin (
void
);
static
void
end (
void
);
static
void
setBitOrder (
uint8_t bit_order_
);
static
void
setClockDivider (
uint8_t clock_divider_
);
static
void
setDataMode (
uint8_t data_mode_
);
static
uint8_t
transfer (
uint8_t data_
);
};
void
digitalWrite (
const uint8_t pin_,
const uint8_t latch_value_
);
namespace MOCK {
enum class PinTransition : uint8_t {
NO_TRANSITION = static_cast<uint8_t>(-1),
HIGH_TO_LOW = 0,
LOW_TO_HIGH,
};
void
initMockState (
void
);
uint8_t
getPinLatchValue (
const uint8_t pin_
);
PinTransition *
getPinTransition (
const uint8_t pin_
);
void
resetPinTransitions (
void
);
} // namespace MOCK
#endif
extern MOCK_spi SPI;
#endif
/* Created and copyrighted by <NAME>. Offered as open source under the MIT License (MIT). */
|
zfields/mcp23s17-wiring
|
src/mcp23s17.h
|
/* Created and copyrighted by <NAME>. Offered as open source under the MIT License (MIT). */
#ifndef MCP23S17_H
#define MCP23S17_H
#include <cstdint>
class mcp23s17 {
public:
// Definition(s)
typedef void(*isr_t)(void);
/// \brief Control Registers
/// \note IOCONA is equivalent to IOCONB
/// \note As addressed when IOCON.BANK = 0
enum class ControlRegister : uint8_t {
IODIRA = 0,
IODIRB,
IPOLA,
IPOLB,
GPINTENA,
GPINTENB,
DEFVALA,
DEFVALB,
INTCONA,
INTCONB,
IOCONA,
IOCONB,
GPPUA,
GPPUB,
INTFA,
INTFB,
INTCAPA,
INTCAPB,
GPIOA_,
GPIOB_,
OLATA,
OLATB,
REGISTER_COUNT,
};
/// \brief The hardware address of the chip
/// \detail The chip has three pins A0, A1 and A2 dedicated
/// to supplying an individual address to a chip, which
/// allows up to eight devices on the bus.
enum class HardwareAddress : uint8_t {
HW_ADDR_0 = 0,
HW_ADDR_1,
HW_ADDR_2,
HW_ADDR_3,
HW_ADDR_4,
HW_ADDR_5,
HW_ADDR_6,
HW_ADDR_7,
};
/// \brief Interrupt Mode
enum class InterruptMode {
LOW = 0,
HIGH = 1,
CHANGE,
FALLING,
RISING,
};
/// \brief I/O Control Register
/// \n Unimplemented (bit 0) - Read as ‘0’.
/// \n INTPOL (bit 1) - This bit sets the polarity of the INT output pin.
/// \n - 0 = Active-low.
/// \n - 1 = Active-high.
/// \n ODR (bit 2) - This bit configures the INT pin as an open-drain output.
/// \n - 0 = Active driver output (INTPOL bit sets the polarity).
/// \n - 1 = Open-drain output (overrides the INTPOL bit).
/// \n HAEN (bit 3) - Hardware Address Enable bit (MCP23S17 only, address pins are always enabled on MCP23017).
/// \n - 0 = Disables the MCP23S17 address pins.
/// \n - 1 = Enables the MCP23S17 address pins.
/// \n DISSLW (bit 4) - Slew Rate control bit for SDA output.
/// \n - 0 = Slew rate enabled.
/// \n - 1 = Slew rate disabled.
/// \n SEQOP (bit 5) - Sequential Operation mode bit.
/// \n - 0 = Sequential operation enabled, address pointer increments.
/// \n - 1 = Sequential operation disabled, address pointer does not increment.
/// \n MIRROR (bit 6) - INT Pins Mirror bit
/// \n - 0 = The INT pins are not connected. INTA is associated with PortA and INTB is associated with PortB
/// \n - 1 = The INT pins are internally connected
/// \n BANK (bit 7) - Controls how the registers are addressed
/// \n - 0 = The registers are in the same bank (addresses are sequential)
/// \n - 1 = The registers associated with each port are separated into different banks
enum class IOConfigurationRegister : uint8_t {
UNIMPLEMENTED = 0x01,
INTPOL = 0x02,
ODR = 0x04,
HAEN = 0x08,
DISSLW = 0x10,
SEQOP = 0x20,
MIRROR = 0x40,
BANK = 0x80,
};
/// \brief Pin Latch Value
/// \note HIGH => Vcc
/// \n LOW => GND
enum class PinLatchValue {
LOW = 0,
HIGH,
};
/// \brief Pin Modes
/// \note INPUT_PULLUP uses an internal 100kΩ resistor
/// \note The pull-up resistor will provide 40-115uA of current
enum class PinMode {
OUTPUT = 0,
INPUT,
INPUT_PULLUP,
};
/// \brief Register Transaction Flag
enum class RegisterTransaction : uint8_t {
WRITE = 0,
READ,
};
// Constructor and destructor method(s)
/// \brief Object Constructor
/// \param [in] hw_addr_ The hardware address of the device
mcp23s17 (
const HardwareAddress hw_addr_
);
// Accessor method(s)
/// \brief Hardware address of device
/// \return Hardware address of the device
inline
uint8_t
getSpiBusAddress (
void
) const {
return _SPI_BUS_ADDRESS;
}
// Public instance variable(s)
static const uint8_t PIN_COUNT = 16;
static const uint8_t SPI_BASE_ADDRESS = 0x40;
// Public method(s)
/// \brief Attach interrupt to specified pin
/// \param [in] pin_ The number associated with the pin
/// \param [in] interrupt_service_routine_ The callback to be fired when the interrupt occurs
/// \param [in] mode_ The mode of the interrupt
/// \n - CHANGE - Signal when pin state changes from previous state
/// \n - FALLING - Signal when pin transistions from HIGH to LOW
/// \n - HIGH - Signal when pin state is HIGH
/// \n - LOW - Signal when pin state is LOW
/// \n - RISING - Signal when pin transistions from LOW to HIGH
void
attachInterrupt (
const uint8_t pin_,
const isr_t interrupt_service_routine_,
const InterruptMode mode_
);
/// \brief Read from GPIO pins
/// \param [in] pin_ The number associated with the pin
/// \return HIGH or LOW based on the voltage level on the pin
PinLatchValue
digitalRead (
const uint8_t pin_
) const;
/// \brief Write HIGH or LOW on pins
/// \param [in] pin_ The number associated with the pin
/// \param [in] value_ The value set to the latch
/// \n - HIGH => Vcc
/// \n - LOW => GND
void
digitalWrite (
const uint8_t pin_,
const PinLatchValue value_
);
/// \brief Set pin mode
/// \param [in] pin_ The number associated with the pin
/// \param [in] mode_ The direction to set the GPIO pins
/// \n - INPUT => Prepares the chip to read from the GPIO pins
/// \n - INPUT_PULLUP => Prepares the chip to read from the GPIO pins,
/// and supplies a 100kΩ resistor to pull the line HIGH while idle.
/// \n - OUTPUT => Prepares the chip to write from the GPIO pins
void
pinMode (
const uint8_t pin_,
const PinMode mode_
);
protected:
// Protected instance variable(s)
// Protected method(s)
inline
uint8_t const *
getControlRegister (
void
) const {
return _control_register;
}
inline
uint8_t const *
getControlRegisterAddresses (
void
) const {
return _control_register_address;
}
inline
isr_t const *
getInterruptServiceRoutines (
void
) const {
return _interrupt_service_routines;
}
private:
// Private instance variable(s)
const uint8_t _SPI_BUS_ADDRESS;
uint8_t _control_register[static_cast<uint8_t>(ControlRegister::REGISTER_COUNT)];
uint8_t _control_register_address[static_cast<uint8_t>(ControlRegister::REGISTER_COUNT)];
isr_t _interrupt_service_routines[PIN_COUNT];
// Private method(s)
};
#endif
/* Created and copyrighted by <NAME>. Offered as open source under the MIT License (MIT). */
|
Dynamo13D/ubicoin
|
src/chainparamsseeds.h
|
#ifndef UBICOIN_CHAINPARAMSSEEDS_H
#define UBICOIN_CHAINPARAMSSEEDS_H
/**
* List of fixed seed nodes for the ubicoin network
* AUTOGENERATED by contrib/seeds/generate-seeds.py
*
* Each line contains a 16-byte IPv6 address and a port.
* IPv4 as well as onion addresses are wrapped inside an IPv6 address accordingly.
*/
static SeedSpec6 pnSeed6_main[] = {
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x9b,0x8a,0x8f,0x89}, 9777},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x24,0x54,0x3f,0xc7}, 9777},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x9b,0x8a,0x8f,0x89}, 9777},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x24,0x54,0x3f,0xc7}, 9777},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x42,0x2a,0x34,0x38}, 9777},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x2d,0x4c,0x64,0x96}, 9777},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x45,0x55,0x55,0x14}, 9777},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x45,0x55,0x55,0x02}, 9777}
};
static SeedSpec6 pnSeed6_test[] = {
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x45,0x55,0x54,0xaf}, 19225}
};
#endif // UBICOIN_CHAINPARAMSSEEDS_H
|
AstroProfundis/monitoring-tools
|
collectd/collectd_tsl2561.c
|
<reponame>AstroProfundis/monitoring-tools<gh_stars>1-10
/*
* A simple collectd exec plugin that reads data from TSL2561
* and similiar sensors.
*
* To use it, first `cd` into 'tsl2561/src' and `make`, then compile
* this plugin with:
* gcc -Wall tsl2561/src/tsl2561.o collectd_tsl2561.c -o collectd_tsl2561
*
* Remember to add following configs to your types.db:
* tsl_lux value:GAUGE:0:U
* */
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "tsl2561/src/tsl2561.h"
#define TSL_I2C_DEV "/dev/i2c-0"
#define TSL_I2C_PIN 0x39
void read_tsl_data(char *hostname, int interval){
char *i2c_device = TSL_I2C_DEV;
int address = TSL_I2C_PIN;
void *tsl = tsl2561_init(address, i2c_device);
tsl2561_enable_autogain(tsl);
tsl2561_set_integration_time(tsl, TSL2561_INTEGRATION_TIME_13MS);
/* Flush stdout buffer:
* This needs to be done before *anything* is written to STDOUT! */
int status = setvbuf (stdout,
/* buf = */ NULL,
/* mode = */ _IONBF, /* unbuffered */
/* size = */ 0);
if (status != 0){
perror ("Error in setvbuf(): fail to flush stdout buffer.");
exit (1);
}
if(tsl != NULL){
long lux = tsl2561_lux(tsl);
if (lux < 800){ // force hight gain in dark
tsl2561_disable_autogain(tsl);
tsl2561_set_timing(tsl, TSL2561_INTEGRATION_TIME_402MS, TSL2561_GAIN_16X);
lux = tsl2561_lux(tsl);
}
printf("PUTVAL \"%s/exec-tsl/gauge-tsl_lux\" interval=%d N:%ld\n", hostname, interval, lux);
tsl2561_close(tsl);
i2c_device = NULL;
}
}
int main(int argc, char *argv[]){
char *hostname = getenv("COLLECTD_HOSTNAME");
int interval = atoi(getenv("COLLECTD_INTERVAL"));
while (1){
read_tsl_data(hostname, interval);
sleep(interval); /* interval is in seconds, wait before next read */
}
return 0;
}
|
AstroProfundis/monitoring-tools
|
collectd/collectd_max44009.c
|
// Distributed with a free-will license.
// Use it any way you want, profit or free, provided it fits in the licenses of its associated works.
// MAX44009
// This code is designed to work with the MAX44009_I2CS I2C Mini Module available from ControlEverything.com.
// https://www.controleverything.com/products
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <math.h>
float get_lux(void){
// Create I2C bus
int file;
char *bus = "/dev/i2c-1";
if ((file = open(bus, O_RDWR)) < 0){
printf("Failed to open the bus. \n");
exit(1);
}
// Get I2C device, MAX44009 I2C address is 0x4A(74)
ioctl(file, I2C_SLAVE, 0x4A);
// Select configuration register(0x02)
char config[2] = {0};
config[0] = 0x02;
// Manual mode, Integration time = 800 ms(0x40)
//config[1] = 0x40;
// Automatic mode
config[1] = 0x00;
write(file, config, 2);
// Read 2 bytes of data from register(0x03)
// luminance MSB, luminance LSB
char reg[1] = {0x03} ;
write(file, reg, 1);
char data[2] = {0};
float luminance;
if(read(file, data, 2) != 2){
printf("Erorr : Input/output Erorr \n");
luminance = 0;
} else {
// Convert the data to lux
int exponent = (data[0] & 0xF0) >> 4;
int mantissa = ((data[0] & 0x0F) << 4) | (data[1] & 0x0F);
//printf("%d, %d\n", exponent, mantissa);
luminance = pow(2, exponent) * mantissa * 0.045;
}
return luminance;
}
int main(void){
char *hostname = getenv("COLLECTD_HOSTNAME");
int interval = atoi(getenv("COLLECTD_INTERVAL"));
while (1){
float lux = get_lux();
/* Flush stdout buffer:
* This needs to be done before *anything* is written to STDOUT! */
int status = setvbuf (stdout,
/* buf = */ NULL,
/* mode = */ _IONBF, /* unbuffered */
/* size = */ 0);
if (status != 0){
perror ("Error in setvbuf(): fail to flush stdout buffer.");
exit (1);
}
printf("PUTVAL \"%s/exec-max44009/gauge-max44009_lux\" interval=%d N:%.2f\n", hostname, interval, lux);
sleep(interval);
}
return 0;
}
|
AstroProfundis/monitoring-tools
|
collectd/collectd_dht.c
|
<filename>collectd/collectd_dht.c
/*
* A simple collectd exec plugin that reads data from DHT11/DHT22
* and similiar sensors.
* Modified base on example code from:
* https://www.piprojects.xyz/temperature-humidity-sensor-orange-pi/
*
* Remember to add following configs to your types.db:
* dht_humi value:GAUGE:0:U
* dht_temp value:GAUGE:U:U
* dht_dewp value:GAUGE:U:U
* dht_error value:GAUGE:0:U
* */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <wiringPi.h>
#define MAX_TIMINGS 85
#define DHT_PIN 7
#define MAX_RETRY 5
#define RETRY_DELAY 200
int data[5] = { 0, 0, 0, 0, 0 };
float cal_dewpoint(float temp, float humi){
/* fomula and constants from https://en.wikipedia.org/wiki/Dew_point */
float b = 17.67;
float c = 243.5; // C
float gamma = logf(humi / 100) + b * temp / (c + temp);
float tdewp = c * gamma / (b - gamma);
return tdewp;
}
void read_dht_data(char *hostname, int interval, double retries){
uint8_t laststate = HIGH;
uint8_t counter = 0;
uint8_t j = 0, i;
data[0] = data[1] = data[2] = data[3] = data[4] = 0;
/* pull pin down for 18 milliseconds */
pinMode( DHT_PIN, OUTPUT );
digitalWrite( DHT_PIN, LOW );
delay( 18 );
/* prepare to read the pin */
pinMode( DHT_PIN, INPUT );
/* detect change and read data */
for ( i = 0; i < MAX_TIMINGS; i++ ){
counter = 0;
while ( digitalRead( DHT_PIN ) == laststate ){
counter++;
delayMicroseconds( 1 );
if ( counter == 255 ){
break;
}
}
laststate = digitalRead( DHT_PIN );
if ( counter == 255 )
break;
/* ignore first 3 transitions */
if ( (i >= 4) && (i % 2 == 0) ){
/* shove each bit into the storage bytes */
data[j / 8] <<= 1;
if ( counter > 16 )
data[j / 8] |= 1;
j++;
}
}
/* Flush stdout buffer:
* This needs to be done before *anything* is written to STDOUT! */
int status = setvbuf (stdout,
/* buf = */ NULL,
/* mode = */ _IONBF, /* unbuffered */
/* size = */ 0);
if (status != 0){
perror ("Error in setvbuf(): fail to flush stdout buffer.");
exit (1);
}
/*
* check we read 40 bits (8bit x 5 ) + verify checksum in the last byte
* print it out if data is good
*/
if ( (j >= 40) &&
(data[4] == ( (data[0] + data[1] + data[2] + data[3]) & 0xFF) ) ){
float h = (float)((data[0] << 8) + data[1]) / 10;
if ( h > 100 ){
h = data[0]; // for DHT11
}
float c = (float)(((data[2] & 0x7F) << 8) + data[3]) / 10;
if ( c > 125 ){
c = data[2]; // for DHT11
}
if ( data[2] & 0x80 ){
c = -c;
}
float dewp = cal_dewpoint(c, h);
printf("PUTVAL \"%s/exec-dht/gauge-dht_humi\" interval=%d N:%.2f\n", hostname, interval, h);
printf("PUTVAL \"%s/exec-dht/gauge-dht_temp\" interval=%d N:%.2f\n", hostname, interval, c);
printf("PUTVAL \"%s/exec-dht/gauge-dht_dewp\" interval=%d N:%.2f\n", hostname, interval, dewp);
printf("PUTVAL \"%s/exec-dht/gauge-dht_error\" interval=%d N:%.2f\n", hostname, interval, retries / MAX_RETRY);
} else if (retries < MAX_RETRY) {
/* On reading errors, wait for some time and try again */
delay(RETRY_DELAY);
read_dht_data(hostname, interval, ++retries);
} else {
printf("PUTVAL \"%s/exec-dht/gauge-dht_error\" interval=%d N:1.00\n", hostname, interval);
}
}
int main( void ){
char *hostname = getenv("COLLECTD_HOSTNAME");
int interval = atoi(getenv("COLLECTD_INTERVAL"));
if ( wiringPiSetup() == -1 )
exit( 1 );
while ( 1 ){
read_dht_data(hostname, interval, 0.0);
delay(interval * 1000); /* interval is in seconds, wait before next read */
}
return(0);
}
|
AstroProfundis/monitoring-tools
|
collectd/collectd_bmp180.c
|
/*
* A simple collectd exec plugin that reads data from BMP180
* and similiar sensors.
*
* To use it, first `cd` into 'bmp180/src' and `make`, then compile
* this plugin with:
* gcc -Wall bmp180/src/bmp180.o collectd_bmp180.c -o collectd_bmp180 -lm
*
* Remember to add following configs to your types.db:
* bmp_temp value:GAUGE:U:U
* bmp_pres value:GAUGE:0:U
* bmp_alti value:GAUGE:U:U
* */
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "bmp180/src/bmp180.h"
#define BMP_I2C_DEV "/dev/i2c-1"
#define BMP_I2C_PIN 0x77
void read_bmp_data(char *hostname, int interval){
char *i2c_device = BMP_I2C_DEV;
int address = BMP_I2C_PIN;
void *bmp = bmp180_init(address, i2c_device);
bmp180_eprom_t eprom;
bmp180_dump_eprom(bmp, &eprom);
bmp180_set_oss(bmp, 1);
/* Flush stdout buffer:
* This needs to be done before *anything* is written to STDOUT! */
int status = setvbuf (stdout,
/* buf = */ NULL,
/* mode = */ _IONBF, /* unbuffered */
/* size = */ 0);
if (status != 0){
perror ("Error in setvbuf(): fail to flush stdout buffer.");
exit (1);
}
if(bmp != NULL){
float t = bmp180_temperature(bmp);
long p = bmp180_pressure(bmp);
float alt = bmp180_altitude(bmp);
printf("PUTVAL \"%s/exec-bmp/gauge-bmp_temp\" interval=%d N:%.4f\n", hostname, interval, t);
printf("PUTVAL \"%s/exec-bmp/gauge-bmp_pres\" interval=%d N:%lu\n", hostname, interval, p);
printf("PUTVAL \"%s/exec-bmp/gauge-bmp_alti\" interval=%d N:%.4f\n", hostname, interval, alt);
bmp180_close(bmp);
}
}
int main(int argc, char *argv[]){
char *hostname = getenv("COLLECTD_HOSTNAME");
int interval = atoi(getenv("COLLECTD_INTERVAL"));
while (1){
read_bmp_data(hostname, interval);
sleep(interval); /* interval is in seconds, wait before next read */
}
return 0;
}
|
bravegnu/mzero
|
src/debug.h
|
<filename>src/debug.h<gh_stars>10-100
#ifndef DEBUG_H
#define DEBUG_H
#include <cstdint>
#include <string>
#include "sysbus.h"
class Debug {
private:
uint32_t *m_regs;
bool *m_c;
bool *m_v;
bool *m_n;
bool *m_z;
SystemBus *m_sysbus;
uint32_t *parse_reg(std::string reg_name);
public:
static const char *REG_NAMES[16];
static const char FLAGS[4];
Debug(uint32_t *regs, bool *c, bool *v, bool *n, bool *z, SystemBus *sysbus);
void set_reg(std::string reg_name, uint32_t value);
uint32_t get_reg(std::string reg_name);
bool get_flag(char ch);
void set_flag(char ch, bool val);
void set_mem32(uint32_t addr, uint32_t value);
uint32_t get_mem32(uint32_t addr);
};
#endif
|
bravegnu/mzero
|
src/decoder.h
|
<filename>src/decoder.h
#ifndef DECODER_H
#define DECODER_H
#include <cstdint>
enum Cond {
COND_EQ,
COND_NE,
COND_CS,
COND_CC,
COND_MI,
COND_PL,
COND_VS,
COND_VC,
COND_HI,
COND_LS,
COND_GE,
COND_LT,
COND_GT,
COND_LE,
COND_AL,
COND_UNDEF,
};
enum Op {
/* Data Processing */
LSLI, LSRI, ASRI, ADD, SUB, ADDI, SUBI, MOV, MOVI, CMPI,
AND, EOR, LSL, LSR, ASR, ADC, SBC, ROR, TST, RSBI, CMP, CMN,
ORR, MUL, BIC, MVN,
/* Relative Addressing */
ADR,
/* Branching */
BX, BLX, BCOND, SVC,
/* Load Store */
STR, STRH, STRB, LDRSB, LDR, LDRH, LDRB, LDRSH, STRI, LDRI, STRBI,
LDRBI, STRHI, LDRHI, LDM, STM, LDRL,
/* Misc. */
SXTH, SXTB, UXTH, UXTB, PUSH, CPS, REV, REV16, REVSH, POP, BKPT,
/* Hint */
NOP, YIELD, WFE, WFI, SEV,
/* Branch and Control */
MSR, MRS, BL, DSB, DMB, ISB,
/* Undefined */
UDF,
OP_MAX
};
#define DECODE_TAB_SIZE 77
#define DECODE32_TAB_SIZE 7
struct DecodedInst {
uint8_t op;
uint8_t rd;
uint8_t rn;
uint8_t rm;
int32_t imm;
uint16_t specific;
bool setflags;
};
class Decoder;
struct DecoderTab {
uint16_t mask;
uint16_t match;
void (Decoder::*decode)();
};
struct Decoder32Tab {
uint32_t mask;
uint32_t match;
void (Decoder::*decode)();
};
class Decoder {
private:
uint32_t m_inst;
bool m_is32;
DecodedInst m_di;
static const DecoderTab m_decode_table[DECODE_TAB_SIZE];
static const Decoder32Tab m_decode32_table[DECODE32_TAB_SIZE];
void decode_lsli();
void decode_lsri();
void decode_asri();
void decode_add_t1();
void decode_sub();
void decode_addi_t1();
void decode_subi_t1();
void decode_movi();
void decode_cmpi();
void decode_addi_t2();
void decode_subi_t2();
void decode_dproc();
void decode_and();
void decode_eor();
void decode_lsl();
void decode_lsr();
void decode_asr();
void decode_adc();
void decode_sbc();
void decode_ror();
void decode_tst();
void decode_rsbi();
void decode_cmp();
void decode_cmn();
void decode_orr();
void decode_mul();
void decode_bic();
void decode_mvn();
void decode_add_t2();
void decode_cmp_t1();
void decode_cmp_t2();
void decode_mov_t1();
void decode_mov_t2();
void decode_bx();
void decode_blx();
void decode_ldrl();
void decode_load_store();
void decode_str();
void decode_ldr();
void decode_strh();
void decode_strb();
void decode_ldrsb();
void decode_ldrh();
void decode_ldrb();
void decode_ldrsh();
void decode_load_store_imm();
void decode_ldri_t2();
void decode_stri_t2();
void decode_ldrbi();
void decode_strbi();
void decode_ldrhi();
void decode_strhi();
void decode_ldri_t1();
void decode_stri_t1();
void decode_adr();
void decode_add_sp_t1();
void decode_add_sp_t2();
void decode_addi_sp_t1();
void decode_addi_sp_t2();
void decode_subi_sp();
void decode_sxth();
void decode_sxtb();
void decode_uxth();
void decode_uxtb();
void decode_push();
void decode_cps();
void decode_rev();
void decode_rev16();
void decode_revsh();
void decode_pop();
void decode_bkpt();
void decode_nop();
void decode_yield();
void decode_wfe();
void decode_wfi();
void decode_sev();
void decode_stm();
void decode_ldm();
void decode_udf();
void decode_b_t1();
void decode_b_t2();
void decode_svc();
void decode_inst();
void decode_bl();
void decode_msr();
void decode_dsb();
void decode_dmb();
void decode_isb();
void decode_mrs();
void decode_udf32();
void decode_inst32();
uint8_t REG(unsigned offset)
{
return (m_inst >> offset) & 0x7;
}
uint8_t REG4(unsigned offset)
{
return (m_inst >> offset) & 0xF;
}
uint8_t REG4M()
{
return (m_inst >> 3) & 0xF;
}
uint8_t REG4N()
{
return ((m_inst >> 4) & 0x8) | ((m_inst >> 0) & 0x7);
}
uint32_t IMM3()
{
return (m_inst >> 6) & 0x7;
}
uint32_t IMM5()
{
return (m_inst >> 6) & 0x1F;
}
uint32_t IMM7()
{
return (m_inst >> 0) & 0x7F;
}
uint32_t IMM8()
{
return (m_inst >> 0) & 0xFF;
}
uint32_t SIMM8()
{
return (int32_t (IMM8() << 24)) >> 24;
}
uint32_t SIMM11()
{
return (int32_t ((m_inst & 0x7FF) << 21)) >> 21;
}
uint16_t HI16()
{
return (m_inst >> 16) & 0xFF;
}
uint16_t LO16()
{
return (m_inst & 0xFF);
}
public:
Decoder();
DecodedInst decode(uint32_t inst, bool is32);
};
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.