/* Thread */ void *janus_pfunix_thread(void *data) { JANUS_LOG(LOG_INFO, "Unix Sockets thread started\n"); int fds = 0; struct pollfd poll_fds[1024]; /* FIXME Should we allow for more clients? */ char buffer[BUFFER_SIZE]; struct iovec iov[1]; struct msghdr msg; memset(&msg, 0, sizeof(msg)); memset(iov, 0, sizeof(iov)); iov[0].iov_base = buffer; iov[0].iov_len = sizeof(buffer); msg.msg_iov = iov; msg.msg_iovlen = 1; while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) { /* Prepare poll list of file descriptors */ fds = 0; /* Writeable monitor */ poll_fds[fds].fd = write_fd[0]; poll_fds[fds].events = POLLIN; fds++; if(pfd > -1) { /* Janus API */ poll_fds[fds].fd = pfd; poll_fds[fds].events = POLLIN; fds++; } if(admin_pfd > -1) { /* Admin API */ poll_fds[fds].fd = admin_pfd; poll_fds[fds].events = POLLIN; fds++; } /* Iterate on available clients, to see if we need to POLLIN or POLLOUT too */ janus_mutex_lock(&clients_mutex); GHashTableIter iter; gpointer value; g_hash_table_iter_init(&iter, clients_by_fd); while(g_hash_table_iter_next(&iter, NULL, &value)) { janus_pfunix_client *client = value; if(client->fd > -1) { poll_fds[fds].fd = client->fd; poll_fds[fds].events = g_async_queue_length(client->messages) > 0 ? POLLIN | POLLOUT : POLLIN; fds++; } } janus_mutex_unlock(&clients_mutex); /* Start polling */ int res = poll(poll_fds, fds, -1); if(res == 0) continue; if(res < 0) { JANUS_LOG(LOG_ERR, "poll() failed\n"); break; } int i = 0; for(i=0; i<fds; i++) { if(poll_fds[i].revents & (POLLERR | POLLHUP)) { /* Socket error? Shall we do something? */ if(poll_fds[i].fd == write_fd[0]) { /* Error in the wake-up socketpair, that sucks: try recreating it */ JANUS_LOG(LOG_WARN, "Error polling wake-up socketpair: %s...\n", poll_fds[i].revents & POLLERR ? "POLLERR" : "POLLHUP"); close(write_fd[0]); write_fd[0] = -1; close(write_fd[1]); write_fd[1] = -1; if(socketpair(PF_LOCAL, SOCK_STREAM, 0, write_fd) < 0) { JANUS_LOG(LOG_FATAL, "Error creating socket pair for writeable events: %d, %s\n", errno, strerror(errno)); continue; } } else if(poll_fds[i].fd == pfd) { /* Error in the Janus API socket */ JANUS_LOG(LOG_WARN, "Error polling Unix Sockets Janus API interface (%s), disabling it\n", poll_fds[i].revents & POLLERR ? "POLLERR" : "POLLHUP"); close(pfd); pfd = -1; continue; } else if(poll_fds[i].fd == admin_pfd) { /* Error in the Admin API socket */ JANUS_LOG(LOG_WARN, "Error polling Unix Sockets Admin API interface (%s), disabling it\n", poll_fds[i].revents & POLLERR ? "POLLERR" : "POLLHUP"); close(admin_pfd); admin_pfd = -1; continue; } else { /* Error in a client socket, find and remove it */ janus_mutex_lock(&clients_mutex); janus_pfunix_client *client = g_hash_table_lookup(clients_by_fd, GINT_TO_POINTER(poll_fds[i].fd)); if(client == NULL) { /* We're not handling this, ignore */ continue; } JANUS_LOG(LOG_INFO, "Unix Sockets client disconnected (%d)\n", poll_fds[i].fd); /* Notify core */ gateway->transport_gone(&janus_pfunix_transport, client); /* Notify handlers about this transport being gone */ if(notify_events && gateway->events_is_enabled()) { json_t *info = json_object(); json_object_set_new(info, "event", json_string("disconnected")); gateway->notify_event(&janus_pfunix_transport, client, info); } /* Close socket */ shutdown(SHUT_RDWR, poll_fds[i].fd); close(poll_fds[i].fd); client->fd = -1; /* Destroy the client */ g_hash_table_remove(clients_by_fd, GINT_TO_POINTER(poll_fds[i].fd)); g_hash_table_remove(clients, client); if(client->messages != NULL) { char *response = NULL; while((response = g_async_queue_try_pop(client->messages)) != NULL) { g_free(response); } g_async_queue_unref(client->messages); } g_free(client); janus_mutex_unlock(&clients_mutex); continue; } continue; } if(poll_fds[i].revents & POLLOUT) { /* Find the client from its file descriptor */ janus_mutex_lock(&clients_mutex); janus_pfunix_client *client = g_hash_table_lookup(clients_by_fd, GINT_TO_POINTER(poll_fds[i].fd)); if(client != NULL) { char *payload = NULL; while((payload = g_async_queue_try_pop(client->messages)) != NULL) { int res = 0; do { res = write(client->fd, payload, strlen(payload)); } while(res == -1 && errno == EINTR); /* FIXME Should we check if sent everything? */ JANUS_LOG(LOG_HUGE, "Written %d/%zu bytes on %d\n", res, strlen(payload), client->fd); g_free(payload); } } janus_mutex_unlock(&clients_mutex); } if(poll_fds[i].revents & POLLIN) { if(poll_fds[i].fd == write_fd[0]) { /* Read and ignore: we use this to unlock the poll if there's data to write */ res = read(poll_fds[i].fd, buffer, BUFFER_SIZE); } else if(poll_fds[i].fd == pfd || poll_fds[i].fd == admin_pfd) { /* Janus/Admin API: accept the new client (SOCK_SEQPACKET) or receive data (SOCK_DGRAM) */ struct sockaddr_un address; socklen_t addrlen = sizeof(address); if((poll_fds[i].fd == pfd && !dgram) || (poll_fds[i].fd == admin_pfd && !admin_dgram)) { /* SOCK_SEQPACKET */ int cfd = accept(poll_fds[i].fd, (struct sockaddr *) &address, &addrlen); if(cfd > -1) { JANUS_LOG(LOG_INFO, "Got new Unix Sockets %s API client: %d\n", poll_fds[i].fd == pfd ? "Janus" : "Admin", cfd); /* Allocate new client */ janus_pfunix_client *client = g_malloc0(sizeof(janus_pfunix_client)); client->fd = cfd; client->admin = (poll_fds[i].fd == admin_pfd); /* API client type */ client->messages = g_async_queue_new(); client->session_timeout = FALSE; /* Take note of this new client */ janus_mutex_lock(&clients_mutex); g_hash_table_insert(clients_by_fd, GINT_TO_POINTER(cfd), client); g_hash_table_insert(clients, client, client); janus_mutex_unlock(&clients_mutex); /* Notify handlers about this new transport */ if(notify_events && gateway->events_is_enabled()) { json_t *info = json_object(); json_object_set_new(info, "event", json_string("connected")); json_object_set_new(info, "admin_api", client->admin ? json_true() : json_false()); json_object_set_new(info, "fd", json_integer(client->fd)); gateway->notify_event(&janus_pfunix_transport, client, info); } } } else { /* SOCK_DGRAM */ struct sockaddr_storage address; res = recvfrom(poll_fds[i].fd, buffer, sizeof(buffer), 0, (struct sockaddr *)&address, &addrlen); if(res < 0) { if(errno != EAGAIN && errno != EWOULDBLOCK) { JANUS_LOG(LOG_ERR, "Error reading from client (%s API)...\n", poll_fds[i].fd == pfd ? "Janus" : "Admin"); } continue; } buffer[res] = '\0'; /* Is this a new client, or one we knew about already? */ struct sockaddr_un *uaddr = (struct sockaddr_un *)&address; if(strlen(uaddr->sun_path) == 0) { /* No path provided, drop the packet */ JANUS_LOG(LOG_WARN, "Dropping packet from unknown source (no path provided)\n"); continue; } janus_mutex_lock(&clients_mutex); janus_pfunix_client *client = g_hash_table_lookup(clients_by_path, uaddr->sun_path); if(client == NULL) { JANUS_LOG(LOG_INFO, "Got new Unix Sockets %s API client: %s\n", poll_fds[i].fd == pfd ? "Janus" : "Admin", uaddr->sun_path); /* Allocate new client */ client = g_malloc0(sizeof(janus_pfunix_client)); client->fd = -1; memcpy(&client->addr, uaddr, sizeof(struct sockaddr_un)); client->admin = (poll_fds[i].fd == admin_pfd); /* API client type */ client->messages = g_async_queue_new(); client->session_timeout = FALSE; /* Take note of this new client */ g_hash_table_insert(clients_by_path, uaddr->sun_path, client); g_hash_table_insert(clients, client, client); /* Notify handlers about this new transport */ if(notify_events && gateway->events_is_enabled()) { json_t *info = json_object(); json_object_set_new(info, "event", json_string("connected")); json_object_set_new(info, "admin_api", client->admin ? json_true() : json_false()); json_object_set_new(info, "fd", json_integer(client->fd)); json_object_set_new(info, "type", json_string("SOCK_DGRAM")); gateway->notify_event(&janus_pfunix_transport, client, info); } } janus_mutex_unlock(&clients_mutex); JANUS_LOG(LOG_VERB, "Message from client %s (%d bytes)\n", uaddr->sun_path, res); JANUS_LOG(LOG_HUGE, "%s\n", buffer); /* Parse the JSON payload */ json_error_t error; json_t *root = json_loads(buffer, 0, &error); /* Notify the core, passing both the object and, since it may be needed, the error */ gateway->incoming_request(&janus_pfunix_transport, client, NULL, client->admin, root, &error); } } else { /* Client data: receive message */ iov[0].iov_len = sizeof(buffer); res = recvmsg(poll_fds[i].fd, &msg, MSG_WAITALL); if(res < 0) { if(errno != EAGAIN && errno != EWOULDBLOCK) { JANUS_LOG(LOG_ERR, "Error reading from client %d...\n", poll_fds[i].fd); } continue; } if(msg.msg_flags & MSG_TRUNC) { /* Apparently our buffer is not large enough? */ JANUS_LOG(LOG_WARN, "Incoming message from client %d truncated (%d bytes), dropping it...\n", poll_fds[i].fd, res); continue; } /* Find the client from its file descriptor */ janus_mutex_lock(&clients_mutex); janus_pfunix_client *client = g_hash_table_lookup(clients_by_fd, GINT_TO_POINTER(poll_fds[i].fd)); if(client == NULL) { janus_mutex_unlock(&clients_mutex); JANUS_LOG(LOG_WARN, "Got data from unknown Unix Sockets client %d, closing connection...\n", poll_fds[i].fd); /* Close socket */ shutdown(SHUT_RDWR, poll_fds[i].fd); close(poll_fds[i].fd); continue; } if(res == 0) { JANUS_LOG(LOG_INFO, "Unix Sockets client disconnected (%d)\n", poll_fds[i].fd); /* Notify core */ gateway->transport_gone(&janus_pfunix_transport, client); /* Notify handlers about this transport being gone */ if(notify_events && gateway->events_is_enabled()) { json_t *info = json_object(); json_object_set_new(info, "event", json_string("disconnected")); gateway->notify_event(&janus_pfunix_transport, client, info); } /* Close socket */ shutdown(SHUT_RDWR, poll_fds[i].fd); close(poll_fds[i].fd); client->fd = -1; /* Destroy the client */ g_hash_table_remove(clients_by_fd, GINT_TO_POINTER(poll_fds[i].fd)); g_hash_table_remove(clients, client); if(client->messages != NULL) { char *response = NULL; while((response = g_async_queue_try_pop(client->messages)) != NULL) { g_free(response); } g_async_queue_unref(client->messages); } g_free(client); janus_mutex_unlock(&clients_mutex); continue; } janus_mutex_unlock(&clients_mutex); /* If we got here, there's data to handle */ buffer[res] = '\0'; JANUS_LOG(LOG_VERB, "Message from client %d (%d bytes)\n", poll_fds[i].fd, res); JANUS_LOG(LOG_HUGE, "%s\n", buffer); /* Parse the JSON payload */ json_error_t error; json_t *root = json_loads(buffer, 0, &error); /* Notify the core, passing both the object and, since it may be needed, the error */ gateway->incoming_request(&janus_pfunix_transport, client, NULL, client->admin, root, &error); } } } } socklen_t addrlen = sizeof(struct sockaddr_un); void *addr = g_malloc0(addrlen+1); if(pfd > -1) { /* Unlink the path name first */ if(getsockname(pfd, (struct sockaddr *)addr, &addrlen) != -1) { JANUS_LOG(LOG_INFO, "Unlinking %s\n", ((struct sockaddr_un *)addr)->sun_path); unlink(((struct sockaddr_un *)addr)->sun_path); } /* Close the socket */ close(pfd); } pfd = -1; if(admin_pfd > -1) { /* Unlink the path name first */ if(getsockname(admin_pfd, (struct sockaddr *)addr, &addrlen) != -1) { JANUS_LOG(LOG_INFO, "Unlinking %s\n", ((struct sockaddr_un *)addr)->sun_path); unlink(((struct sockaddr_un *)addr)->sun_path); } /* Close the socket */ close(admin_pfd); } admin_pfd = -1; g_free(addr); g_hash_table_destroy(clients_by_path); g_hash_table_destroy(clients_by_fd); g_hash_table_destroy(clients); /* Done */ JANUS_LOG(LOG_INFO, "Unix Sockets thread ended\n"); return NULL; }
/** * \internal * \brief Write meta data on a single line json record */ static void FileWriteJsonRecord(JsonFileLogThread *aft, const Packet *p, const File *ff) { MemBuffer *buffer = (MemBuffer *)aft->buffer; json_t *js = CreateJSONHeader((Packet *)p, 0, "file"); //TODO const if (unlikely(js == NULL)) return; /* reset */ MemBufferReset(buffer); json_t *hjs = json_object(); if (unlikely(hjs == NULL)) { json_decref(js); return; } json_object_set_new(hjs, "url", LogFileMetaGetUri(p, ff)); json_object_set_new(hjs, "hostname", LogFileMetaGetHost(p, ff)); json_object_set_new(hjs, "http_refer", LogFileMetaGetReferer(p, ff)); json_object_set_new(hjs, "http_user_agent", LogFileMetaGetUserAgent(p, ff)); json_object_set_new(js, "http", hjs); json_t *fjs = json_object(); if (unlikely(fjs == NULL)) { json_decref(hjs); json_decref(js); return; } char *s = BytesToString(ff->name, ff->name_len); json_object_set_new(fjs, "filename", json_string(s)); if (s != NULL) SCFree(s); if (ff->magic) json_object_set_new(fjs, "magic", json_string((char *)ff->magic)); else json_object_set_new(fjs, "magic", json_string("unknown")); switch (ff->state) { case FILE_STATE_CLOSED: json_object_set_new(fjs, "state", json_string("CLOSED")); #ifdef HAVE_NSS if (ff->flags & FILE_MD5) { size_t x; int i; char *s = SCMalloc(256); if (likely(s != NULL)) { for (i = 0, x = 0; x < sizeof(ff->md5); x++) { i += snprintf(&s[i], 255-i, "%02x", ff->md5[x]); } json_object_set_new(fjs, "md5", json_string(s)); SCFree(s); } } #endif break; case FILE_STATE_TRUNCATED: json_object_set_new(fjs, "state", json_string("TRUNCATED")); break; case FILE_STATE_ERROR: json_object_set_new(fjs, "state", json_string("ERROR")); break; default: json_object_set_new(fjs, "state", json_string("UNKNOWN")); break; } json_object_set_new(fjs, "stored", (ff->flags & FILE_STORED) ? json_true() : json_false()); json_object_set_new(fjs, "size", json_integer(ff->size)); json_object_set_new(js, "file", fjs); OutputJSONBuffer(js, aft->filelog_ctx->file_ctx, buffer); json_object_del(js, "file"); json_object_del(js, "http"); json_object_clear(js); json_decref(js); }
static json_t *parse_object(lex_t *lex, size_t flags, json_error_t *error) { json_t *object = json_object(); if(!object) return NULL; lex_scan(lex, error); if(lex->token == '}') return object; while(1) { char *key; json_t *value; if(lex->token != TOKEN_STRING) { error_set(error, lex, "string or '}' expected"); goto error; } key = lex_steal_string(lex); if(!key) return NULL; if(flags & JSON_REJECT_DUPLICATES) { if(json_object_get(object, key)) { jsonp_free(key); error_set(error, lex, "duplicate object key"); goto error; } } lex_scan(lex, error); if(lex->token != ':') { jsonp_free(key); error_set(error, lex, "':' expected"); goto error; } lex_scan(lex, error); value = parse_value(lex, flags, error); if(!value) { jsonp_free(key); goto error; } if(json_object_set_nocheck(object, key, value)) { jsonp_free(key); json_decref(value); goto error; } json_decref(value); jsonp_free(key); lex_scan(lex, error); if(lex->token != ',') break; lex_scan(lex, error); } if(lex->token != '}') { error_set(error, lex, "'}' expected"); goto error; } return object; error: json_decref(object); return NULL; }
char* parse_response(void* conn, const char* request, int length) { json_t* root = NULL; json_t* obj = NULL; json_error_t err; char* response = NULL; std::string resaction = "errorResponse"; try { memset(&err, 0, sizeof(json_error_t)); root = json_loadb(request, length, JSON_DECODE_ANY, &err); if(!root) { throw std::runtime_error("Request is not a valid JSON object"); } const char* action; json_object_get_string(root, obj, "action", action); if(!action) { throw std::runtime_error("Request type is unknown"); } else if(strcmp(action, "loginType1") == 0) { int ret; const char* challenge; resaction = "loginType1Response"; ret = lmice::token_get_challenge(conn, &challenge); if(ret != 0) throw std::runtime_error("Client connection is invalid"); json_t* rep = json_object(); json_object_set_string(rep, "action", resaction.c_str()); json_object_set_bool(rep, "status", true); json_object_set_string(rep, "challenge", challenge); json_object_set_string(rep, "error", "OK"); response = json_dumps(rep, JSON_INDENT(4)); json_decref(rep); } else if(strcmp(action, "loginType2") == 0) { int id; int ret; const char* name; const char* pass; const char* challenge; const char* email; const char* password; const char* display_name; resaction = "loginType2Response"; json_object_get_string( root, obj, "name", name); json_object_get_string( root, obj, "password", pass); json_object_get_string( root, obj, "challenge", challenge); ret = lmice::token_compare_challenge(conn, challenge); if(ret != 0) throw std::runtime_error("Client status is incorrect"); ret = lmice::user_find_name(name, &id, &display_name, &email, &password); if(ret != 0) throw std::runtime_error("User name is invalid"); ret = lmice::user_compare_password(id, challenge, pass); if( ret != 0) throw std::runtime_error("Password is incorrect"); lmice::token_update_user(conn, id); json_t* rep = json_object(); json_object_set_string(rep, "action", resaction.c_str()); json_object_set_bool(rep, "status", true); json_object_set_string(rep, "token", "123"); json_object_set_string(rep, "displayName", display_name); json_object_set_string(rep, "email", email); json_object_set_string(rep, "error", "OK"); response = json_dumps(rep, JSON_INDENT(4)); json_decref(rep); } else if(strcmp(action, "logout") == 0) { // Logout const char* token; json_object_get_string(root, obj, "token", token); lmice::token_reset(conn); if(!token) { throw std::runtime_error("Client status is incorrect"); } json_t* rep = json_object(); json_object_set_string(rep, "action", "logoutResponse"); json_object_set_bool(rep, "status", true); json_object_set_string(rep, "error", "OK"); response = json_dumps(rep, JSON_INDENT(4)); json_decref(rep); } else if(strcmp(action, "register") == 0) { // Register const char* name; const char* display_name; const char* password; const char* email; int ret; int id; resaction = "registerResponse"; json_object_get_string( root, obj, "name", name); json_object_get_string( root, obj, "password", password); json_object_get_string( root, obj, "display_name", display_name); json_object_get_string( root, obj, "email", email); if(!name) throw std::runtime_error("Name is null"); if(!password) throw std::runtime_error("Password is null"); if(!display_name) display_name = name; if(!email) throw std::runtime_error("Email is null"); ret = lmice::user_add_new( name, display_name, email, password, &id); switch(ret) { case lmice::EUSER_ID_EXIST: throw std::runtime_error("Create new user failed(ID)"); case lmice::EUSER_NAME_EXIST: throw std::runtime_error("Create new user failed(Name)"); case lmice::EUSER_EMAIL_EXIST: throw std::runtime_error("Create new user failed(Email)"); } json_t* rep = json_object(); json_object_set_string(rep, "action", "registerResponse"); json_object_set_bool(rep, "status", true); json_object_set_string(rep, "error", "OK"); response = json_dumps(rep, JSON_INDENT(4)); json_decref(rep); } } catch(const std::exception& e) { json_t* rep = json_object(); json_object_set_string(rep, "action", resaction.c_str()); json_object_set_bool(rep, "status", false); json_object_set_string(rep, "error", e.what()); response = json_dumps(rep, JSON_INDENT(4)); json_decref(rep); } json_decref(root); return response; }
int janus_websockets_send_message(void *transport, void *request_id, gboolean admin, json_t *message) { if(message == NULL) return -1; if(transport == NULL) { json_decref(message); return -1; } /* Make sure this is not related to a closed /freed WebSocket session */ janus_mutex_lock(&old_wss_mutex); janus_websockets_client *client = (janus_websockets_client *)transport; #ifdef HAVE_LIBWEBSOCKETS_NEWAPI if(g_list_find(old_wss, client) != NULL || !client->wsi) { #else if(g_list_find(old_wss, client) != NULL || !client->context || !client->wsi) { #endif json_decref(message); message = NULL; transport = NULL; janus_mutex_unlock(&old_wss_mutex); return -1; } janus_mutex_lock(&client->mutex); /* Convert to string and enqueue */ char *payload = json_dumps(message, json_format); g_async_queue_push(client->messages, payload); #ifdef HAVE_LIBWEBSOCKETS_NEWAPI lws_callback_on_writable(client->wsi); #else libwebsocket_callback_on_writable(client->context, client->wsi); #endif janus_mutex_unlock(&client->mutex); janus_mutex_unlock(&old_wss_mutex); json_decref(message); return 0; } void janus_websockets_session_created(void *transport, guint64 session_id) { /* We don't care */ } void janus_websockets_session_over(void *transport, guint64 session_id, gboolean timeout) { if(transport == NULL || !timeout) return; /* We only care if it's a timeout: if so, close the connection */ janus_websockets_client *client = (janus_websockets_client *)transport; /* Make sure this is not related to a closed WebSocket session */ janus_mutex_lock(&old_wss_mutex); #ifdef HAVE_LIBWEBSOCKETS_NEWAPI if(g_list_find(old_wss, client) == NULL && client->wsi){ #else if(g_list_find(old_wss, client) == NULL && client->context && client->wsi){ #endif janus_mutex_lock(&client->mutex); client->session_timeout = 1; #ifdef HAVE_LIBWEBSOCKETS_NEWAPI lws_callback_on_writable(client->wsi); #else libwebsocket_callback_on_writable(client->context, client->wsi); #endif janus_mutex_unlock(&client->mutex); } janus_mutex_unlock(&old_wss_mutex); } /* Thread */ void *janus_websockets_thread(void *data) { #ifdef HAVE_LIBWEBSOCKETS_NEWAPI struct lws_context *service = (struct lws_context *)data; #else struct libwebsocket_context *service = (struct libwebsocket_context *)data; #endif if(service == NULL) { JANUS_LOG(LOG_ERR, "Invalid service\n"); return NULL; } const char *type = NULL; if(service == wss) type = "WebSocket (Janus API)"; else if(service == swss) type = "Secure WebSocket (Janus API)"; else if(service == admin_wss) type = "WebSocket (Admin API)"; else if(service == admin_swss) type = "Secure WebSocket (Admin API)"; JANUS_LOG(LOG_INFO, "%s thread started\n", type); while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) { /* libwebsockets is single thread, we cycle through events here */ #ifdef HAVE_LIBWEBSOCKETS_NEWAPI lws_service(service, 50); #else libwebsocket_service(service, 50); #endif } /* Get rid of the WebSockets server */ #ifdef HAVE_LIBWEBSOCKETS_NEWAPI lws_cancel_service(service); #else libwebsocket_cancel_service(service); #endif /* Done */ JANUS_LOG(LOG_INFO, "%s thread ended\n", type); return NULL; } /* WebSockets */ static int janus_websockets_callback_http( #ifdef HAVE_LIBWEBSOCKETS_NEWAPI struct lws *wsi, enum lws_callback_reasons reason, #else struct libwebsocket_context *this, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, #endif void *user, void *in, size_t len) { /* This endpoint cannot be used for HTTP */ switch(reason) { case LWS_CALLBACK_HTTP: JANUS_LOG(LOG_VERB, "Rejecting incoming HTTP request on WebSockets endpoint\n"); #ifdef HAVE_LIBWEBSOCKETS_NEWAPI lws_return_http_status(wsi, 403, NULL); #else libwebsockets_return_http_status(this, wsi, 403, NULL); #endif /* Close and free connection */ return -1; case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: if (!in) { JANUS_LOG(LOG_VERB, "Rejecting incoming HTTP request on WebSockets endpoint: no sub-protocol specified\n"); return -1; } break; default: break; } return 0; } static int janus_websockets_callback_https( #ifdef HAVE_LIBWEBSOCKETS_NEWAPI struct lws *wsi, enum lws_callback_reasons reason, #else struct libwebsocket_context *this, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, #endif void *user, void *in, size_t len) { /* We just forward the event to the HTTP handler */ #ifdef HAVE_LIBWEBSOCKETS_NEWAPI return janus_websockets_callback_http(wsi, reason, user, in, len); #else return janus_websockets_callback_http(this, wsi, reason, user, in, len); #endif } /* This callback handles Janus API requests */ static int janus_websockets_common_callback( #ifdef HAVE_LIBWEBSOCKETS_NEWAPI struct lws *wsi, enum lws_callback_reasons reason, #else struct libwebsocket_context *this, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, #endif void *user, void *in, size_t len, gboolean admin) { const char *log_prefix = admin ? "AdminWSS" : "WSS"; janus_websockets_client *ws_client = (janus_websockets_client *)user; switch(reason) { case LWS_CALLBACK_ESTABLISHED: { /* Is there any filtering we should apply? */ char name[256], ip[256]; #ifdef HAVE_LIBWEBSOCKETS_NEWAPI lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name, 256, ip, 256); #else libwebsockets_get_peer_addresses(this, wsi, libwebsocket_get_socket_fd(wsi), name, 256, ip, 256); #endif JANUS_LOG(LOG_VERB, "[%s-%p] WebSocket connection opened from %s by %s\n", log_prefix, wsi, ip, name); if(!janus_websockets_is_allowed(ip, admin)) { JANUS_LOG(LOG_ERR, "[%s-%p] IP %s is unauthorized to connect to the WebSockets %s API interface\n", log_prefix, wsi, ip, admin ? "Admin" : "Janus"); /* Close the connection */ #ifdef HAVE_LIBWEBSOCKETS_NEWAPI lws_callback_on_writable(wsi); #else libwebsocket_callback_on_writable(this, wsi); #endif return -1; } JANUS_LOG(LOG_VERB, "[%s-%p] WebSocket connection accepted\n", log_prefix, wsi); if(ws_client == NULL) { JANUS_LOG(LOG_ERR, "[%s-%p] Invalid WebSocket client instance...\n", log_prefix, wsi); return -1; } /* Clean the old sessions list, in case this pointer was used before */ janus_mutex_lock(&old_wss_mutex); if(g_list_find(old_wss, ws_client) != NULL) old_wss = g_list_remove(old_wss, ws_client); janus_mutex_unlock(&old_wss_mutex); /* Prepare the session */ #ifndef HAVE_LIBWEBSOCKETS_NEWAPI ws_client->context = this; #endif ws_client->wsi = wsi; ws_client->messages = g_async_queue_new(); ws_client->buffer = NULL; ws_client->buflen = 0; ws_client->bufpending = 0; ws_client->bufoffset = 0; ws_client->session_timeout = 0; ws_client->destroy = 0; janus_mutex_init(&ws_client->mutex); /* Let us know when the WebSocket channel becomes writeable */ #ifdef HAVE_LIBWEBSOCKETS_NEWAPI lws_callback_on_writable(wsi); #else libwebsocket_callback_on_writable(this, wsi); #endif JANUS_LOG(LOG_VERB, "[%s-%p] -- Ready to be used!\n", log_prefix, wsi); /* Notify handlers about this new transport */ if(notify_events && gateway->events_is_enabled()) { json_t *info = json_object(); json_object_set_new(info, "event", json_string("connected")); json_object_set_new(info, "admin_api", admin ? json_true() : json_false()); json_object_set_new(info, "ip", json_string(ip)); gateway->notify_event(&janus_websockets_transport, ws_client, info); } return 0; } case LWS_CALLBACK_RECEIVE: { JANUS_LOG(LOG_HUGE, "[%s-%p] Got %zu bytes:\n", log_prefix, wsi, len); #ifdef HAVE_LIBWEBSOCKETS_NEWAPI if(ws_client == NULL || ws_client->wsi == NULL) { #else if(ws_client == NULL || ws_client->context == NULL || ws_client->wsi == NULL) { #endif JANUS_LOG(LOG_ERR, "[%s-%p] Invalid WebSocket client instance...\n", log_prefix, wsi); return -1; } /* Is this a new message, or part of a fragmented one? */ #ifdef HAVE_LIBWEBSOCKETS_NEWAPI const size_t remaining = lws_remaining_packet_payload(wsi); #else const size_t remaining = libwebsockets_remaining_packet_payload(wsi); #endif if(ws_client->incoming == NULL) { JANUS_LOG(LOG_HUGE, "[%s-%p] First fragment: %zu bytes, %zu remaining\n", log_prefix, wsi, len, remaining); ws_client->incoming = g_malloc0(len+1); memcpy(ws_client->incoming, in, len); ws_client->incoming[len] = '\0'; JANUS_LOG(LOG_HUGE, "%s\n", ws_client->incoming); } else { size_t offset = strlen(ws_client->incoming); JANUS_LOG(LOG_HUGE, "[%s-%p] Appending fragment: offset %zu, %zu bytes, %zu remaining\n", log_prefix, wsi, offset, len, remaining); ws_client->incoming = g_realloc(ws_client->incoming, offset+len+1); memcpy(ws_client->incoming+offset, in, len); ws_client->incoming[offset+len] = '\0'; JANUS_LOG(LOG_HUGE, "%s\n", ws_client->incoming+offset); } #ifdef HAVE_LIBWEBSOCKETS_NEWAPI if(remaining > 0 || !lws_is_final_fragment(wsi)) { #else if(remaining > 0 || !libwebsocket_is_final_fragment(wsi)) { #endif /* Still waiting for some more fragments */ JANUS_LOG(LOG_HUGE, "[%s-%p] Waiting for more fragments\n", log_prefix, wsi); return 0; } JANUS_LOG(LOG_HUGE, "[%s-%p] Done, parsing message: %zu bytes\n", log_prefix, wsi, strlen(ws_client->incoming)); /* If we got here, the message is complete: parse the JSON payload */ json_error_t error; json_t *root = json_loads(ws_client->incoming, 0, &error); g_free(ws_client->incoming); ws_client->incoming = NULL; /* Notify the core, passing both the object and, since it may be needed, the error */ gateway->incoming_request(&janus_websockets_transport, ws_client, NULL, admin, root, &error); return 0; } case LWS_CALLBACK_SERVER_WRITEABLE: { #ifdef HAVE_LIBWEBSOCKETS_NEWAPI if(ws_client == NULL || ws_client->wsi == NULL) { #else if(ws_client == NULL || ws_client->context == NULL || ws_client->wsi == NULL) { #endif JANUS_LOG(LOG_ERR, "[%s-%p] Invalid WebSocket client instance...\n", log_prefix, wsi); return -1; } if(!ws_client->destroy && !g_atomic_int_get(&stopping)) { janus_mutex_lock(&ws_client->mutex); /* Check if we have a pending/partial write to complete first */ if(ws_client->buffer && ws_client->bufpending > 0 && ws_client->bufoffset > 0 && !ws_client->destroy && !g_atomic_int_get(&stopping)) { JANUS_LOG(LOG_HUGE, "[%s-%p] Completing pending WebSocket write (still need to write last %d bytes)...\n", log_prefix, wsi, ws_client->bufpending); #ifdef HAVE_LIBWEBSOCKETS_NEWAPI int sent = lws_write(wsi, ws_client->buffer + ws_client->bufoffset, ws_client->bufpending, LWS_WRITE_TEXT); #else int sent = libwebsocket_write(wsi, ws_client->buffer + ws_client->bufoffset, ws_client->bufpending, LWS_WRITE_TEXT); #endif JANUS_LOG(LOG_HUGE, "[%s-%p] -- Sent %d/%d bytes\n", log_prefix, wsi, sent, ws_client->bufpending); if(sent > -1 && sent < ws_client->bufpending) { /* We still couldn't send everything that was left, we'll try and complete this in the next round */ ws_client->bufpending -= sent; ws_client->bufoffset += sent; } else { /* Clear the pending/partial write queue */ ws_client->bufpending = 0; ws_client->bufoffset = 0; } /* Done for this round, check the next response/notification later */ #ifdef HAVE_LIBWEBSOCKETS_NEWAPI lws_callback_on_writable(wsi); #else libwebsocket_callback_on_writable(this, wsi); #endif janus_mutex_unlock(&ws_client->mutex); return 0; } /* Shoot all the pending messages */ char *response = g_async_queue_try_pop(ws_client->messages); if(response && !ws_client->destroy && !g_atomic_int_get(&stopping)) { /* Gotcha! */ int buflen = LWS_SEND_BUFFER_PRE_PADDING + strlen(response) + LWS_SEND_BUFFER_POST_PADDING; if(ws_client->buffer == NULL) { /* Let's allocate a shared buffer */ JANUS_LOG(LOG_HUGE, "[%s-%p] Allocating %d bytes (response is %zu bytes)\n", log_prefix, wsi, buflen, strlen(response)); ws_client->buflen = buflen; ws_client->buffer = g_malloc0(buflen); } else if(buflen > ws_client->buflen) { /* We need a larger shared buffer */ JANUS_LOG(LOG_HUGE, "[%s-%p] Re-allocating to %d bytes (was %d, response is %zu bytes)\n", log_prefix, wsi, buflen, ws_client->buflen, strlen(response)); ws_client->buflen = buflen; ws_client->buffer = g_realloc(ws_client->buffer, buflen); } memcpy(ws_client->buffer + LWS_SEND_BUFFER_PRE_PADDING, response, strlen(response)); JANUS_LOG(LOG_HUGE, "[%s-%p] Sending WebSocket message (%zu bytes)...\n", log_prefix, wsi, strlen(response)); #ifdef HAVE_LIBWEBSOCKETS_NEWAPI int sent = lws_write(wsi, ws_client->buffer + LWS_SEND_BUFFER_PRE_PADDING, strlen(response), LWS_WRITE_TEXT); #else int sent = libwebsocket_write(wsi, ws_client->buffer + LWS_SEND_BUFFER_PRE_PADDING, strlen(response), LWS_WRITE_TEXT); #endif JANUS_LOG(LOG_HUGE, "[%s-%p] -- Sent %d/%zu bytes\n", log_prefix, wsi, sent, strlen(response)); if(sent > -1 && sent < (int)strlen(response)) { /* We couldn't send everything in a single write, we'll complete this in the next round */ ws_client->bufpending = strlen(response) - sent; ws_client->bufoffset = LWS_SEND_BUFFER_PRE_PADDING + sent; JANUS_LOG(LOG_HUGE, "[%s-%p] -- Couldn't write all bytes (%d missing), setting offset %d\n", log_prefix, wsi, ws_client->bufpending, ws_client->bufoffset); } /* We can get rid of the message */ free(response); /* Done for this round, check the next response/notification later */ #ifdef HAVE_LIBWEBSOCKETS_NEWAPI lws_callback_on_writable(wsi); #else libwebsocket_callback_on_writable(this, wsi); #endif janus_mutex_unlock(&ws_client->mutex); return 0; } janus_mutex_unlock(&ws_client->mutex); } return 0; } case LWS_CALLBACK_CLOSED: { JANUS_LOG(LOG_VERB, "[%s-%p] WS connection down, closing\n", log_prefix, wsi); janus_websockets_destroy_client(ws_client, wsi, log_prefix); JANUS_LOG(LOG_VERB, "[%s-%p] -- closed\n", log_prefix, wsi); return 0; } case LWS_CALLBACK_WSI_DESTROY: { JANUS_LOG(LOG_VERB, "[%s-%p] WS connection down, destroying\n", log_prefix, wsi); janus_websockets_destroy_client(ws_client, wsi, log_prefix); JANUS_LOG(LOG_VERB, "[%s-%p] -- destroyed\n", log_prefix, wsi); return 0; } default: if(wsi != NULL) { JANUS_LOG(LOG_HUGE, "[%s-%p] %d (%s)\n", log_prefix, wsi, reason, janus_websockets_reason_string(reason)); } else { JANUS_LOG(LOG_HUGE, "[%s] %d (%s)\n", log_prefix, reason, janus_websockets_reason_string(reason)); } break; } return 0; } /* This callback handles Janus API requests */ static int janus_websockets_callback( #ifdef HAVE_LIBWEBSOCKETS_NEWAPI struct lws *wsi, enum lws_callback_reasons reason, #else struct libwebsocket_context *this, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, #endif void *user, void *in, size_t len) { #ifdef HAVE_LIBWEBSOCKETS_NEWAPI return janus_websockets_common_callback(wsi, reason, user, in, len, FALSE); #else return janus_websockets_common_callback(this, wsi, reason, user, in, len, FALSE); #endif } static int janus_websockets_callback_secure( #ifdef HAVE_LIBWEBSOCKETS_NEWAPI struct lws *wsi, enum lws_callback_reasons reason, #else struct libwebsocket_context *this, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, #endif void *user, void *in, size_t len) { /* We just forward the event to the Janus API handler */ #ifdef HAVE_LIBWEBSOCKETS_NEWAPI return janus_websockets_callback(wsi, reason, user, in, len); #else return janus_websockets_callback(this, wsi, reason, user, in, len); #endif } /* This callback handles Admin API requests */ static int janus_websockets_admin_callback( #ifdef HAVE_LIBWEBSOCKETS_NEWAPI struct lws *wsi, enum lws_callback_reasons reason, #else struct libwebsocket_context *this, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, #endif void *user, void *in, size_t len) { #ifdef HAVE_LIBWEBSOCKETS_NEWAPI return janus_websockets_common_callback(wsi, reason, user, in, len, TRUE); #else return janus_websockets_common_callback(this, wsi, reason, user, in, len, TRUE); #endif } static int janus_websockets_admin_callback_secure( #ifdef HAVE_LIBWEBSOCKETS_NEWAPI struct lws *wsi, enum lws_callback_reasons reason, #else struct libwebsocket_context *this, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, #endif void *user, void *in, size_t len) { /* We just forward the event to the Admin API handler */ #ifdef HAVE_LIBWEBSOCKETS_NEWAPI return janus_websockets_admin_callback(wsi, reason, user, in, len); #else return janus_websockets_admin_callback(this, wsi, reason, user, in, len); #endif }
// arguments: [ttl <int>] [name <string>] [target <string>] // (in any order) // if we change record's name (subDomain), we need to update records cache static command_status_t record_update(COMMAND_ARGS) { domain_t *d; record_t *r; bool success; domain_record_argument_t *args; USED(mainopts); args = (domain_record_argument_t *) arg; assert(NULL != args->domain); assert(NULL != args->record); if ((success = (COMMAND_SUCCESS == get_domain_records(args->domain, &d, FALSE, error)))) { json_document_t *reqdoc; size_t matches; matches = find_record(d->records, args->record, &r); switch (matches) { case 1: // NOP : OK break; case 0: error_set(error, WARN, "Abort, no record match '%s'", args->record); return COMMAND_FAILURE; default: error_set(error, WARN, "Abort, more than one record match '%s'", args->record); return COMMAND_FAILURE; } // data { json_value_t root; reqdoc = json_document_new(); root = json_object(); if (NULL != args->value) { json_object_set_property(root, "target", json_string(args->value)); } if (NULL != args->name) { json_object_set_property(root, "subDomain", json_string(args->name)); } json_object_set_property(root, "ttl", json_integer(args->ttl)); json_document_set_root(reqdoc, root); } // request { request_t *req; req = request_new(REQUEST_FLAG_SIGN | REQUEST_FLAG_JSON, HTTP_PUT, reqdoc, error, API_BASE_URL "/domain/zone/%s/record/%" PRIu32, args->domain, r->id); success = request_execute(req, RESPONSE_IGNORE, NULL, error); request_destroy(req); json_document_destroy(reqdoc); } if (success) { if (NULL != args->value) { FREE(r, target); r->target = strdup(args->value); } if (NULL != args->name) { FREE(r, name); r->name = strdup(args->name); } r->ttl = args->ttl; ask_for_refresh(RELAY_COMMAND_ARGS); } } // debug("request update of %s.%s to %s.%s with TTL = %" PRIu32 " and value = '%s'", args->record, args->domain, args->name, args->domain, args->ttl, args->value); return COMMAND_SUCCESS; }
int main(int argc,char **argv) { int opt; int i; int fflag = 0; int r, code = 0; int do_report = 1; char *alt_config = NULL, *domain = NULL; if ((geteuid()) == 0 && (become_cyrus(/*is_master*/0) != 0)) { fatal("must run as the Cyrus user", EC_USAGE); } while ((opt = getopt(argc, argv, "C:d:fqJZ")) != EOF) { switch (opt) { case 'C': /* alt config file */ alt_config = optarg; break; case 'q': do_report = 0; break; case 'd': domain = optarg; break; case 'f': fflag = 1; break; case 'J': jsonout = json_object(); break; /* deliberately undocumented option for testing */ case 'Z': test_sync_mode = 1; break; default: usage(); } } /* always report if not fixing, otherwise we do nothing */ if (!fflag) do_report = 1; cyrus_init(alt_config, "quota", 0, CONFIG_NEED_PARTITION_DATA); /* Set namespace -- force standard (internal) */ if ((r = mboxname_init_namespace("a_namespace, 1)) != 0) { syslog(LOG_ERR, "%s", error_message(r)); fatal(error_message(r), EC_CONFIG); } if (config_getswitch(IMAPOPT_IMPROVED_MBOXLIST_SORT)) compar = bsearch_compare_mbox; else compar = strcmp; /* * Lock mailbox list to prevent mailbox creation/deletion * during work */ mboxlist_init(0); mboxlist_open(NULL); quotadb_init(0); quotadb_open(NULL); quota_changelock(); if (!r) r = buildquotalist(domain, argv+optind, argc-optind); if (!r && fflag) r = fixquotas(domain, argv+optind, argc-optind); quota_changelockrelease(); if (r) code = convert_code(r); else if (do_report) reportquota(); quotadb_close(); quotadb_done(); mboxlist_close(); mboxlist_done(); /* just for neatness */ for (i = 0; i < quota_num; i++) free(quotaroots[i].name); free(quotaroots); if (jsonout) json_decref(jsonout); cyrus_done(); return code; }
void TeamCard::onButtonClick(cocos2d::Ref *pSender) { Button* btn=(Button*) pSender; int tag=btn->getTag(); log("tag:%d,index:%d",btn->getTag(),tabBar->getIndex()); switch (tag) { case 1000: //gohome { Manager::getInstance()->switchScence(HomeScene::createScene()); break; } case 1001: //返回 { Team2* team=dynamic_cast<Team2*>(this->preUI); json_object_set(data, "cards", this->cards); json_array_set(team->teamsJson, this->index, this->data); team->resetUI(); this->clear(true); break; } case 1002: //tab0 黑白红绿蓝黄 case 1003: //tab1 case 1004: //tab2 case 1005: //tab4 case 1006: //tab5 case 1007: //tab6 { this->tabBar->setIndex(tag-1002); this->filterCard(tag-1002); break; } case 1008: //上场 { this->aoYiPanel->setVisible(true); this->cardPanel->setVisible(false); json_object_set(this->card->data, "isUsed", json_boolean(true)); json_array_append(this->cards, this->card->data); this->card->setUse(true); this->initAoYi(); this->initCard(); break; } case 1009: //下场 { this->aoYiPanel->setVisible(true); this->cardPanel->setVisible(false); for (int i=0; i<json_array_size(cards); i++) { json_t* json=json_array_get(cards, i); int xid=json_integer_value(json_object_get(json, "xid")); int cid=json_integer_value(json_object_get(this->card->data, "xid")); if(xid==cid){ json_array_remove(cards, i); break; } } json_array_set(cards, 0, json_object()); this->card->setUse(false); this->initCard(); this->initAoYi(); break; } } }
json_t *AddExternalServerOperationsToJSON (ServersManager *manager_p, LinkedList *internal_services_p, Operation op) { /* build the request that we will send to each external server */ json_error_t error; json_t *op_p = json_pack ("{s:{s:i}}", SERVER_OPERATIONS_S, OPERATION_ID_S, op); json_t *ops_array_p = NULL; if (op_p) { LinkedList *servers_p = GetAllExternalServersFromServersManager (manager_p, DeserialiseExternalServerFromJSON); if (servers_p && (servers_p -> ll_size > 0)) { ExternalServerNode *node_p = (ExternalServerNode *) servers_p -> ll_head_p; while (node_p) { ExternalServer *external_server_p = node_p -> esn_server_p; const char *response_s = MakeRemoteJsonCallViaConnection (external_server_p -> es_connection_p, op_p); if (response_s) { json_t *server_response_p = json_loads (response_s, 0, &error); /* * If the external server has paired services, try and pair them */ if (server_response_p) { json_t *default_external_provider_p = json_object_get (server_response_p, SERVER_PROVIDER_S); #if SERVERS_POOL_DEBUG >= STM_LEVEL_FINE PrintJSONToLog (ops_array_p, "local server json:\n", STM_LEVEL_FINE, __FILE__, __LINE__); PrintJSONToLog (default_external_provider_p, "default_external_provider_p:\n", STM_LEVEL_FINE, __FILE__, __LINE__); #endif /* * The elements to get are dependent on the api call */ switch (op) { case OP_LIST_ALL_SERVICES: case OP_LIST_INTERESTED_SERVICES: case OP_GET_NAMED_SERVICES: { json_t *src_services_p = json_object_get (server_response_p, SERVICES_NAME_S); if (src_services_p) { json_t *src_ops_p = json_object_get (src_services_p, SERVER_OPERATIONS_S); if (src_ops_p) { #if SERVERS_POOL_DEBUG >= STM_LEVEL_FINE PrintJSONToLog (src_ops_p, "src_ops:\n", STM_LEVEL_FINE, __FILE__, __LINE__); #endif if (json_is_array (src_ops_p)) { json_t *dest_p = json_object (); if (dest_p) { /* * If the op doesn't have an explicit provider, add * the default one */ bool success_flag = true; json_t *provider_p = json_object_get (server_response_p, SERVER_PROVIDER_S); if (!provider_p) { provider_p = default_external_provider_p; } if (provider_p) { if (json_object_set (dest_p, SERVER_PROVIDER_S, provider_p) != 0) { success_flag = false; } } if (success_flag) { success_flag = false; if (json_object_set (dest_p, SERVER_OPERATIONS_S, src_ops_p) == 0) { if (json_array_append_new (ops_array_p, dest_p) == 0) { success_flag = true; } } } /* if (success_flag) */ if (!success_flag) { WipeJSON (dest_p); } } /* if (dest_p) */ } /* if (json_is_array (src_ops_p)) */ } /* if (src_ops_p) */ } /* if (src_services_p) */ } break; case OP_RUN_KEYWORD_SERVICES: case OP_GET_SERVICE_RESULTS: // element_name_s = SERVICE_RESULTS_S; break; case OP_IRODS_MODIFIED_DATA: break; case OP_CHECK_SERVICE_STATUS: break; case OP_CLEAN_UP_JOBS: break; default: break; } WipeJSON (server_response_p); } /* if (server_response_p) */ else { } } /* if (response_s) */ else { } node_p = (ExternalServerNode *) node_p -> esn_node.ln_next_p; } /* while (node_p) */ FreeLinkedList (servers_p); } /* if (servers_p) */ WipeJSON (op_p); } /* if (op_p) */ else { } #if SERVERS_POOL_DEBUG >= STM_LEVEL_FINE PrintJSONToLog (ops_array_p, "final ops p:\n", STM_LEVEL_FINE, __FILE__, __LINE__); #endif return ops_array_p; }
// Translate from the legacy array into the new style, then // delegate to the main parser. // We build a big anyof expression w_query *w_query_parse_legacy(w_root_t *root, json_t *args, char **errmsg, int start, uint32_t *next_arg, const char *clockspec, json_t **expr_p) { bool include = true; bool negated = false; uint32_t i; const char *term_name = "match"; json_t *query_array; json_t *included = NULL, *excluded = NULL; json_t *term; json_t *container; json_t *query_obj = json_object(); w_query *query; if (!json_is_array(args)) { *errmsg = strdup("Expected an array"); json_decref(query_obj); return NULL; } for (i = start; i < json_array_size(args); i++) { const char *arg = json_string_value(json_array_get(args, i)); if (!arg) { /* not a string value! */ ignore_result(asprintf(errmsg, "rule @ position %d is not a string value", i)); json_decref(query_obj); return NULL; } } for (i = start; i < json_array_size(args); i++) { const char *arg = json_string_value(json_array_get(args, i)); if (!strcmp(arg, "--")) { i++; break; } if (!strcmp(arg, "-X")) { include = false; continue; } if (!strcmp(arg, "-I")) { include = true; continue; } if (!strcmp(arg, "!")) { negated = true; continue; } if (!strcmp(arg, "-P")) { term_name = "ipcre"; continue; } if (!strcmp(arg, "-p")) { term_name = "pcre"; continue; } // Which group are we going to file it into if (include) { if (!included) { included = json_pack("[s]", "anyof"); } container = included; } else { if (!excluded) { excluded = json_pack("[s]", "anyof"); } container = excluded; } term = json_pack("[sss]", term_name, arg, "wholename"); if (negated) { term = json_pack("[so]", "not", term); } json_array_append_new(container, term); // Reset negated flag negated = false; term_name = "match"; } if (excluded) { term = json_pack("[so]", "not", excluded); excluded = term; } if (included && excluded) { query_array = json_pack("[soo]", "allof", excluded, included); } else if (included) { query_array = included; } else { query_array = excluded; } // query_array may be NULL, which means find me all files. // Otherwise, it is the expression we want to use. if (query_array) { json_object_set_new_nocheck(query_obj, "expression", query_array); } // For trigger if (next_arg) { *next_arg = i; } if (clockspec) { json_object_set_new_nocheck(query_obj, "since", json_string_nocheck(clockspec)); } /* compose the query with the field list */ query = w_query_parse(root, query_obj, errmsg); if (expr_p) { *expr_p = query_obj; } else { json_decref(query_obj); } return query; }
int main(int argc, char *argv[]) { int const EVENT_SIZE = 35; int const OBJ_NAME_SIZE = 16; int const ISO_DATETIME_LEN = 25; // READ FROM SERIAL PORT puts("Reading Serial Interface..."); char *portname = "/dev/ttyUSB0"; int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC); if (fd < 0) { printf("error %d opening %s: %s", errno, portname, strerror (errno)); return -1; } set_interface_attribs (fd, B57600, 0); // set speed to 57,600 bps, 8n1 (no pari set_blocking (fd, 0); // set no blocking unsigned int eventIndex = 0; unsigned int year = 0; char month = 0; char day = 0; char hour = 0; char minute = 0; char objStatus = 0; char objId = 0; char objType = 0; char unknownVal0 = 0; char objName[OBJ_NAME_SIZE + 1]; while (1==1) { unsigned char eofBuf [2]; while (eofBuf[1] != 0xE0 || eofBuf[0] != 0xFF){ eofBuf[1] = eofBuf[0]; read (fd, eofBuf, 1); //if (eofBuf[0] != 0) printf("%i;",eofBuf[0]); } eofBuf[0] = eofBuf[1] = 0; int totalRead = 0; unsigned char eventBuf [EVENT_SIZE]; while (totalRead < EVENT_SIZE) { unsigned char readBuf [EVENT_SIZE - totalRead]; int n = read (fd, readBuf, sizeof readBuf); // read remaining b memcpy(&eventBuf[totalRead],&readBuf[0],n); totalRead+=n; //printf_ByteArray(readBuf, sizeof readBuf); } totalRead = 0; eventIndex = 0x00 | (eventBuf[0] << 8) | (eventBuf[1]); year = (eventBuf[2] * 100) + eventBuf[3]; month = eventBuf[4]; day = eventBuf[5]; hour = eventBuf[6]; minute = eventBuf[7]; objStatus = eventBuf[8]; objId = eventBuf[10]; objType = eventBuf[16]; unknownVal0 = eventBuf[34]; strncpy(&objName[0],&eventBuf[17],OBJ_NAME_SIZE); objName[OBJ_NAME_SIZE] = '\0'; time_t now; time(&now); char isoTime[ISO_DATETIME_LEN + 1]; strftime(isoTime, sizeof isoTime, "%FT%T%z", localtime(&now)); memmove(isoTime + 23, isoTime + 22, 3); isoTime[22] = ':'; json_t *customData = json_object(); json_object_set_new(customData, "evtIndex", json_integer(eventIndex)); json_object_set_new(customData, "objType", json_integer(objType)); json_object_set_new(customData, "objName", json_string(objName)); json_object_set_new(customData, "unkVal0", json_integer(unknownVal0)); char *dateStrBuf; dateStrBuf = (char *)my_malloc(ISO_DATETIME_LEN + 1); snprintf(dateStrBuf, ISO_DATETIME_LEN + 1,"%02d-%02d-%02dT%02d:%02d:%02d", 0); strncpy(&dateStrBuf[19], &isoTime[19], 6); json_object_set_new(customData, "rptdTime", json_string(dateStrBuf)); json_t *readingData = json_object(); json_object_set_new(readingData, "sensorId", json_integer(objId)); json_object_set_new(readingData, "reading", json_integer(objStatus)); json_object_set_new(readingData, "dateTime", json_string(isoTime)); json_object_set(readingData, "customData", customData); char *jsonResult = json_dumps(readingData, JSON_COMPACT); printf("%s\n\n", jsonResult); free(jsonResult); free(customData); free(readingData); } return 0; }
json_t* make_interface_file() { json_t *interfaces_json = json_object(); json_t *ifTable_json = json_object(); json_t *ifEntry_array = json_array(); struct rtnl_handle rth = { .fd = -1 }; if (rtnl_open(&rth, 0) < 0) { exit(1); } if (rtnl_wilddump_request(&rth, AF_PACKET, RTM_GETLINK) < 0) { perror("Cannot send dump request"); exit(1); } struct nlmsg_list *linfo = NULL; if (rtnl_dump_filter(&rth, store_nlmsg, &linfo, NULL, NULL) < 0) { fprintf(stderr, "Dump terminated\n"); exit(1); } struct nlmsg_list *l, *n; for (l = linfo; l; l = n) { n = l->next; struct nlmsghdr *nlhdr = &(l->h); struct ifinfomsg *ifimsg = NLMSG_DATA(nlhdr); // Process Data of Netlink Message as ifinfomsg if (ifimsg->ifi_family != AF_UNSPEC && ifimsg->ifi_family != AF_INET6) { printf("error family: %d\n", ifimsg->ifi_family); continue; } // Add Each Parameter to json file json_t *interface_json = json_object(); json_t *linux_json = json_object(); json_object_set_new(interface_json, "ifIndex", json_integer(ifimsg->ifi_index)); json_object_set_new(linux_json, "ifi_type", json_integer(ifimsg->ifi_type)); json_object_set_new(linux_json, "ifi_flags", json_integer(ifimsg->ifi_flags)); // Analyze rtattr Message int len = nlhdr->nlmsg_len - NLMSG_LENGTH(sizeof(*ifimsg));; struct rtattr *tb[IFLA_MAX+1]; parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifimsg), len); if (tb[IFLA_IFNAME]) { // printf("\n%s\n", (char *)RTA_DATA(tb[IFLA_IFNAME])); json_object_set_new(interface_json, "ifDscr", json_string((char *)RTA_DATA(tb[IFLA_IFNAME]))); } if (tb[IFLA_MTU]) { // printf("%d\n", *(int *)RTA_DATA(tb[IFLA_MTU])); json_object_set_new(interface_json, "ifMtu", json_integer(*(int *)RTA_DATA(tb[IFLA_MTU]))); } static const char *oper_states[] = { "UNKNOWN", "NOTPRESENT", "DOWN", "LOWERLAYERDOWN", "TESTING", "DORMANT", "UP" }; if (tb[IFLA_OPERSTATE]) { __u8 state = *(__u8 *)RTA_DATA(tb[IFLA_OPERSTATE]); if (state >= sizeof(oper_states)/sizeof(oper_states[0])){ fprintf(stderr, "state %#x ", state); } else{ // printf("state %s ", oper_states[state]); json_object_set_new(interface_json, "ifOperStatus", json_string(oper_states[state])); } } if (tb[IFLA_ADDRESS]) { char abuf[64]; json_object_set_new(interface_json, "ifPhysAddress", json_string(ll_addr_n2a(RTA_DATA(tb[IFLA_ADDRESS]), RTA_PAYLOAD(tb[IFLA_ADDRESS]), ifimsg->ifi_type, abuf, sizeof(abuf)))); } json_object_set_new(interface_json, "linux", linux_json); json_array_append(ifEntry_array, interface_json); } json_object_set_new(ifTable_json, "ifEntry", ifEntry_array); json_object_set_new(interfaces_json, "ifTable", ifTable_json); free(l); rtnl_close(&rth); return interfaces_json; }
static int AlertJsonDecoderEvent(ThreadVars *tv, JsonAlertLogThread *aft, const Packet *p) { MemBuffer *buffer = (MemBuffer *)aft->json_buffer; int i; char timebuf[64]; json_t *js; if (p->alerts.cnt == 0) return TM_ECODE_OK; CreateIsoTimeString(&p->ts, timebuf, sizeof(timebuf)); for (i = 0; i < p->alerts.cnt; i++) { MemBufferReset(buffer); const PacketAlert *pa = &p->alerts.alerts[i]; if (unlikely(pa->s == NULL)) { continue; } char *action = "allowed"; if (pa->action & (ACTION_REJECT|ACTION_REJECT_DST|ACTION_REJECT_BOTH)) { action = "blocked"; } else if ((pa->action & ACTION_DROP) && EngineModeIsIPS()) { action = "blocked"; } char buf[(32 * 3) + 1]; PrintRawLineHexBuf(buf, sizeof(buf), GET_PKT_DATA(p), GET_PKT_LEN(p) < 32 ? GET_PKT_LEN(p) : 32); js = json_object(); if (js == NULL) return TM_ECODE_OK; json_t *ajs = json_object(); if (ajs == NULL) { json_decref(js); return TM_ECODE_OK; } /* time & tx */ json_object_set_new(js, "timestamp", json_string(timebuf)); /* tuple */ //json_object_set_new(js, "srcip", json_string(srcip)); //json_object_set_new(js, "sp", json_integer(p->sp)); //json_object_set_new(js, "dstip", json_string(dstip)); //json_object_set_new(js, "dp", json_integer(p->dp)); //json_object_set_new(js, "proto", json_integer(proto)); json_object_set_new(ajs, "action", json_string(action)); json_object_set_new(ajs, "gid", json_integer(pa->s->gid)); json_object_set_new(ajs, "signature_id", json_integer(pa->s->id)); json_object_set_new(ajs, "rev", json_integer(pa->s->rev)); json_object_set_new(ajs, "signature", json_string((pa->s->msg) ? pa->s->msg : "")); json_object_set_new(ajs, "category", json_string((pa->s->class_msg) ? pa->s->class_msg : "")); json_object_set_new(ajs, "severity", json_integer(pa->s->prio)); /* alert */ json_object_set_new(js, "alert", ajs); OutputJSONBuffer(js, aft->file_ctx, buffer); json_object_clear(js); json_decref(js); } return TM_ECODE_OK; }
void w_perf_add_meta(w_perf_t *perf, const char *key, json_t *val) { if (!perf->meta_data) { perf->meta_data = json_object(); } set_prop(perf->meta_data, key, val); }
json_t* Channel::saveChannel() { const time_t now = time(nullptr); json_t* ret = json_object(); json_object_set_new_nocheck(ret, "name", json_string_nocheck(name.c_str()) ); json_object_set_new_nocheck(ret, "description", json_string_nocheck(description.c_str()) ); json_object_set_new_nocheck(ret, "mode", json_string_nocheck(modeToString().c_str()) ); json_object_set_new_nocheck(ret, "owner", json_string_nocheck(owner.c_str()) ); json_object_set_new_nocheck(ret, "users", json_integer(participants.size()) ); json_object_set_new_nocheck(ret, "title", json_string_nocheck(title.c_str()) ); json_object_set_new_nocheck(ret, "top", json_integer(topUsers) ); json_object_set_new_nocheck(ret, "type", json_string_nocheck(typeToString().c_str()) ); { json_t* bansnode = json_array(); for (chbanmap_t::const_iterator i = bans.begin(); i != bans.end(); ++i) { BanRecord br = (*i).second; if(br.timeout != 0 && br.timeout < now) continue; json_t* ban = json_object(); json_object_set_new_nocheck(ban, "name", json_string_nocheck((*i).first.c_str()) ); json_object_set_new_nocheck(ban, "banner", json_string_nocheck(br.banner.c_str()) ); json_object_set_new_nocheck(ban, "timeout", json_integer(br.timeout) ); json_object_set_new_nocheck(ban, "time", json_integer(br.time) ); json_array_append_new(bansnode, ban); } json_object_set_new_nocheck(ret, "banlist", bansnode); } { json_t* mods = json_array(); for (chmodmap_t::const_iterator i = moderators.begin(); i != moderators.end(); ++i) { json_t* mod = json_object(); ModRecord mr = (*i).second; json_object_set_new_nocheck(mod, "name", json_string_nocheck((*i).first.c_str()) ); json_object_set_new_nocheck(mod, "modder", json_string_nocheck(mr.modder.c_str()) ); json_object_set_new_nocheck(mod, "time", json_integer(mr.time) ); json_array_append_new(mods, mod); } json_object_set_new_nocheck(ret, "modlist", mods); } return ret; }
char *cjose_jwk_to_json(const cjose_jwk_t *jwk, bool priv, cjose_err *err) { char *result = NULL; if (!jwk) { CJOSE_ERROR(err, CJOSE_ERR_INVALID_ARG); return NULL; } json_t *json = json_object(), *field = NULL; if (!json) { CJOSE_ERROR(err, CJOSE_ERR_NO_MEMORY); goto to_json_cleanup; } // set kty const char *kty = cjose_jwk_name_for_kty(jwk->kty, err); field = json_string(kty); if (!field) { CJOSE_ERROR(err, CJOSE_ERR_NO_MEMORY); goto to_json_cleanup; } json_object_set(json, "kty", field); json_decref(field); field = NULL; // set kid if (NULL != jwk->kid) { field = json_string(jwk->kid); if (!field) { CJOSE_ERROR(err, CJOSE_ERR_NO_MEMORY); goto to_json_cleanup; } json_object_set(json, CJOSE_JWK_KID_STR, field); json_decref(field); field = NULL; } // set public fields if (jwk->fns->public_json && !jwk->fns->public_json(jwk, json, err)) { goto to_json_cleanup; } // set private fields if (priv && jwk->fns->private_json && !jwk->fns->private_json(jwk, json, err)) { goto to_json_cleanup; } // generate the string ... char *str_jwk = json_dumps( json, JSON_ENCODE_ANY | JSON_COMPACT | JSON_PRESERVE_ORDER); if (!str_jwk) { CJOSE_ERROR(err, CJOSE_ERR_NO_MEMORY); goto to_json_cleanup; } result = strdup(str_jwk); cjose_get_dealloc()(str_jwk); to_json_cleanup: if (json) { json_decref(json); json = NULL; } if (field) { json_decref(field); field = NULL; } return result; }
/** \brief turn StatsTable into a json object * \param flags JSON_STATS_* flags for controlling output */ json_t *StatsToJSON(const StatsTable *st, uint8_t flags) { const char delta_suffix[] = "_delta"; struct timeval tval; gettimeofday(&tval, NULL); json_t *js_stats = json_object(); if (unlikely(js_stats == NULL)) { return NULL; } /* Uptime, in seconds. */ json_object_set_new(js_stats, "uptime", json_integer((int)difftime(tval.tv_sec, st->start_time))); uint32_t u = 0; if (flags & JSON_STATS_TOTALS) { for (u = 0; u < st->nstats; u++) { if (st->stats[u].name == NULL) continue; const char *name = st->stats[u].name; const char *shortname = name; if (rindex(name, '.') != NULL) { shortname = &name[rindex(name, '.') - name + 1]; } json_t *js_type = OutputStats2Json(js_stats, name); if (js_type != NULL) { json_object_set_new(js_type, shortname, json_integer(st->stats[u].value)); if (flags & JSON_STATS_DELTAS) { char deltaname[strlen(shortname) + strlen(delta_suffix) + 1]; snprintf(deltaname, sizeof(deltaname), "%s%s", shortname, delta_suffix); json_object_set_new(js_type, deltaname, json_integer(st->stats[u].value - st->stats[u].pvalue)); } } } } /* per thread stats - stored in a "threads" object. */ if (st->tstats != NULL && (flags & JSON_STATS_THREADS)) { /* for each thread (store) */ json_t *threads = json_object(); if (unlikely(threads == NULL)) { json_decref(js_stats); return NULL; } uint32_t x; for (x = 0; x < st->ntstats; x++) { uint32_t offset = x * st->nstats; /* for each counter */ for (u = offset; u < (offset + st->nstats); u++) { if (st->tstats[u].name == NULL) continue; char str[256]; snprintf(str, sizeof(str), "%s.%s", st->tstats[u].tm_name, st->tstats[u].name); char *shortname = &str[rindex(str, '.') - str + 1]; json_t *js_type = OutputStats2Json(threads, str); if (js_type != NULL) { json_object_set_new(js_type, shortname, json_integer(st->tstats[u].value)); if (flags & JSON_STATS_DELTAS) { char deltaname[strlen(shortname) + strlen(delta_suffix) + 1]; snprintf(deltaname, sizeof(deltaname), "%s%s", shortname, delta_suffix); json_object_set_new(js_type, deltaname, json_integer(st->tstats[u].value - st->tstats[u].pvalue)); } } } } json_object_set_new(js_stats, "threads", threads); } return js_stats; }
void MapFormat::saveToFile(String filename) { FILE* file = fopen(filename.c_str(), "w"); if (file) { json_t* rootObject = json_object(); json_t* nameJson = json_string(name); json_t* descriptionJson = json_string(description); json_t* firstRespawnJson = json_integer(firstRespawnOffset); // json_t* sizeXjson = json_integer(Math::ICeil(size.x)); // json_t* sizeXjson = json_integer(Math::ICeil(size.y)); // json_t* sizeXjson = json_integer(Math::ICeil(size.z)); int blockSize = blocks.size(); json_t* blocksJson = json_array(); json_object_set(rootObject, "name", nameJson); json_object_set(rootObject, "description", descriptionJson); json_object_set(rootObject, "first-respawn", firstRespawnJson); // // fwrite(name, sizeof(char), sizeof(name), file); // fwrite(description, sizeof(char), sizeof(description), file); //// fwrite(&respawnTime, sizeof(respawnTime), 1, file); // fwrite(&firstRespawnOffset, sizeof(firstRespawnOffset), 1, file); // fwrite(&size, sizeof(size), 1, file); // int a; // fwrite(&a, sizeof(a), 1, file); // // int blockSize = blocks.size(); // fwrite(&(blockSize), sizeof(blockSize), 1, file); for (int i = 0; i < blocks.size(); i++) { Block* block = blocks[i]; json_t* indBlock = json_object(); json_object_set(indBlock, "extra-args", json_integer(block->extraArgsBit)); json_object_set(indBlock, "origin-x", json_integer(Math::ICeil(block->origin.x))); json_object_set(indBlock, "origin-y", json_integer(Math::ICeil(block->origin.y))); json_object_set(indBlock, "origin-z", json_integer(Math::ICeil(block->origin.z))); json_object_set(indBlock, "material-index", json_integer(block->materialIndex)); if (block->isPoint) { json_object_set(indBlock, "is-point", json_boolean(block->isPoint)); } else if (block->isRespawn) { json_object_set(indBlock, "is-respawn", json_boolean(block->isRespawn)); } if (Math::IFloor(block->rotation.valueDegrees()) != 0) { json_object_set(indBlock, "rotation", json_integer(Math::IFloor(block->rotation.valueDegrees()))); } if ((block->linearSpeed && Math::IFloor(block->linearLocation.length()) > 0)|| block->rotationSpeed) { json_t* movableArgs = json_object(); if (block->linearSpeed > 0 && Math::IFloor(block->linearLocation.length()) > 0) { json_object_set(movableArgs, "linear-speed", json_integer(block->linearSpeed)); json_object_set(movableArgs, "linear-location-x", json_integer(Math::ICeil(block->linearLocation.x))); json_object_set(movableArgs, "linear-location-y", json_integer(Math::ICeil(block->linearLocation.y))); json_object_set(movableArgs, "linear-location-z", json_integer(Math::ICeil(block->linearLocation.z))); if (block->isRotationMovement) { json_object_set(movableArgs, "rotation-movement", json_integer(1)); json_object_set(movableArgs, "is-rotation-right", json_integer(block->isRightRotationMovement ? 1 : 0)); } } if (block->rotationSpeed) { json_object_set(movableArgs, "rotation-speed", json_integer(Math::ICeil(block->rotationSpeed))); } json_object_set(indBlock, "movable-args", movableArgs); } if (block->specialBlockId != -1) { json_object_set(indBlock, "special-block", json_integer(block->specialBlockId)); } json_array_append(blocksJson, indBlock); } json_object_set(rootObject, "blocks", blocksJson); json_dumpf(rootObject, file, JSON_INDENT(4)); json_delete(rootObject); fclose(file); } }
json_t *CreateJSONHeader(Packet *p, int direction_sensitive, char *event_type) { char timebuf[64]; char srcip[46], dstip[46]; Port sp, dp; json_t *js = json_object(); if (unlikely(js == NULL)) return NULL; CreateIsoTimeString(&p->ts, timebuf, sizeof(timebuf)); srcip[0] = '\0'; dstip[0] = '\0'; if (direction_sensitive) { if ((PKT_IS_TOSERVER(p))) { if (PKT_IS_IPV4(p)) { PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), srcip, sizeof(srcip)); PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), dstip, sizeof(dstip)); } else if (PKT_IS_IPV6(p)) { PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), srcip, sizeof(srcip)); PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), dstip, sizeof(dstip)); } sp = p->sp; dp = p->dp; } else { if (PKT_IS_IPV4(p)) { PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), srcip, sizeof(srcip)); PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), dstip, sizeof(dstip)); } else if (PKT_IS_IPV6(p)) { PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), srcip, sizeof(srcip)); PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), dstip, sizeof(dstip)); } sp = p->dp; dp = p->sp; } } else { if (PKT_IS_IPV4(p)) { PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), srcip, sizeof(srcip)); PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), dstip, sizeof(dstip)); } else if (PKT_IS_IPV6(p)) { PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), srcip, sizeof(srcip)); PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), dstip, sizeof(dstip)); } sp = p->sp; dp = p->dp; } char proto[16]; if (SCProtoNameValid(IP_GET_IPPROTO(p)) == TRUE) { strlcpy(proto, known_proto[IP_GET_IPPROTO(p)], sizeof(proto)); } else { snprintf(proto, sizeof(proto), "%03" PRIu32, IP_GET_IPPROTO(p)); } /* time & tx */ json_object_set_new(js, "timestamp", json_string(timebuf)); /* sensor id */ if (sensor_id >= 0) json_object_set_new(js, "sensor_id", json_integer(sensor_id)); /* pcap_cnt */ if (p->pcap_cnt != 0) { json_object_set_new(js, "pcap_cnt", json_integer(p->pcap_cnt)); } if (event_type) { json_object_set_new(js, "event_type", json_string(event_type)); } /* vlan */ if (p->vlan_idx > 0) { json_t *js_vlan; switch (p->vlan_idx) { case 1: json_object_set_new(js, "vlan", json_integer(VLAN_GET_ID1(p))); break; case 2: js_vlan = json_array(); if (unlikely(js != NULL)) { json_array_append_new(js_vlan, json_integer(VLAN_GET_ID1(p))); json_array_append_new(js_vlan, json_integer(VLAN_GET_ID2(p))); json_object_set_new(js, "vlan", js_vlan); } break; default: /* shouldn't get here */ break; } } /* tuple */ json_object_set_new(js, "src_ip", json_string(srcip)); switch(p->proto) { case IPPROTO_ICMP: break; case IPPROTO_UDP: case IPPROTO_TCP: case IPPROTO_SCTP: json_object_set_new(js, "src_port", json_integer(sp)); break; } json_object_set_new(js, "dest_ip", json_string(dstip)); switch(p->proto) { case IPPROTO_ICMP: break; case IPPROTO_UDP: case IPPROTO_TCP: case IPPROTO_SCTP: json_object_set_new(js, "dest_port", json_integer(dp)); break; } json_object_set_new(js, "proto", json_string(proto)); switch (p->proto) { case IPPROTO_ICMP: if (p->icmpv4h) { json_object_set_new(js, "icmp_type", json_integer(p->icmpv4h->type)); json_object_set_new(js, "icmp_code", json_integer(p->icmpv4h->code)); } break; case IPPROTO_ICMPV6: if (p->icmpv6h) { json_object_set_new(js, "icmp_type", json_integer(p->icmpv6h->type)); json_object_set_new(js, "icmp_code", json_integer(p->icmpv6h->code)); } break; } return js; }
/* * Construct the proper JSON object for an iCalendar value. */ static json_t *icalvalue_as_json_object(const icalvalue *value) { const char *str = NULL; json_t *obj; switch (icalvalue_isa(value)) { case ICAL_BOOLEAN_VALUE: return json_boolean(icalvalue_get_integer(value)); case ICAL_DATE_VALUE: str = icaltime_as_iso_string(icalvalue_get_date(value)); break; case ICAL_DATETIME_VALUE: str = icaltime_as_iso_string(icalvalue_get_datetime(value)); break; case ICAL_DATETIMEPERIOD_VALUE: { struct icaldatetimeperiodtype dtp = icalvalue_get_datetimeperiod(value); if (!icaltime_is_null_time(dtp.time)) str = icaltime_as_iso_string(dtp.time); else str = icalperiodtype_as_json_string(dtp.period); break; } case ICAL_FLOAT_VALUE: return json_real(icalvalue_get_float(value)); case ICAL_GEO_VALUE: { struct icalgeotype geo = icalvalue_get_geo(value); obj = json_array(); json_array_append_new(obj, json_real(geo.lat)); json_array_append_new(obj, json_real(geo.lon)); return obj; } case ICAL_INTEGER_VALUE: return json_integer(icalvalue_get_integer(value)); case ICAL_PERIOD_VALUE: str = icalperiodtype_as_json_string(icalvalue_get_period(value)); break; case ICAL_RECUR_VALUE: { struct icalrecurrencetype recur = icalvalue_get_recur(value); obj = json_object(); icalrecurrencetype_add_as_xxx(&recur, obj, &icalrecur_add_int_to_json_object, &icalrecur_add_string_to_json_object); return obj; } case ICAL_REQUESTSTATUS_VALUE: return icalreqstattype_as_json_array(icalvalue_get_requeststatus(value)); case ICAL_TRIGGER_VALUE: { struct icaltriggertype trig = icalvalue_get_trigger(value); if (!icaltime_is_null_time(trig.time)) str = icaltime_as_iso_string(trig.time); else str = icaldurationtype_as_ical_string(trig.duration); break; } case ICAL_UTCOFFSET_VALUE: str = icalvalue_utcoffset_as_iso_string(value); break; default: str = icalvalue_as_ical_string(value); break; } return (str ? json_string(str) : NULL); }
// -------------------------------------------------------------------------- // Export tree to json char * zgtask_tree_export_json (zgtask_tree_t *self, char *path, json_t *json, bool compact) { assert (self); bool is_root = false; if (!json) { json = json_object (); is_root = true; } assert (json); json_t *array = NULL; json_t *obj_array = json_object (); if (!json_is_array (json)) { array = json_array (); json_object_set_new (json, "array", array); } else array = json; json_array_append (array, obj_array); json_object_set_new (obj_array, "name", json_string (self->name)); zgtask_task_t *task = zgtask_tree_get_task (self); if (task) { json_t *obj_task = json_object (); json_object_set_new (obj_array, "task", obj_task); zgtask_task_export_json (task, obj_task); } zgtask_packet_t *packet = (zgtask_packet_t *) zgtask_tree_get_packet (self); if (packet) { json_t *obj_task = json_object (); json_object_set_new (obj_array, "packet", obj_task); zgtask_packet_export_json (packet, obj_task); } if (self->brother) zgtask_tree_export_json (self->brother, 0, array, compact); if (self->child) zgtask_tree_export_json (self->child, 0, obj_array, compact); // Cleaning object array json_decref (obj_array); if (!is_root) return 0; size_t json_flag = JSON_STRICT; if (compact) json_flag = JSON_COMPACT; if (path) json_dump_file (json, path, json_flag); char *json_str = json_dumps (json, json_flag); // Cleaning json_decref (json); return json_str; }
/* * Construct a JSON array for an iCalendar property. */ static json_t *icalproperty_as_json_array(icalproperty *prop) { icalproperty_kind prop_kind; const char *x_name, *property_name = NULL; icalparameter *param; const char *type = NULL; const icalvalue *value; json_t *jprop, *jparams; if (!prop) return NULL; prop_kind = icalproperty_isa(prop); x_name = icalproperty_get_x_name(prop); if (prop_kind == ICAL_X_PROPERTY && x_name) property_name = x_name; else property_name = icalproperty_kind_to_string(prop_kind); if (!property_name) { icalerror_warn("Got a property of an unknown kind."); return NULL; } /* Create property array */ jprop = json_array(); /* Add property name */ json_array_append_new(jprop, json_string(lcase(icalmemory_tmp_copy(property_name)))); /* Add parameters */ jparams = json_object(); for (param = icalproperty_get_first_parameter(prop, ICAL_ANY_PARAMETER); param != 0; param = icalproperty_get_next_parameter(prop, ICAL_ANY_PARAMETER)) { if (icalparameter_isa(param) == ICAL_VALUE_PARAMETER) continue; icalparameter_as_json_object_member(param, jparams); } json_array_append_new(jprop, jparams); /* Add type */ type = icalproperty_value_kind_as_string(prop); json_array_append_new(jprop, json_string(lcase(icalmemory_tmp_copy(type)))); /* Add value */ value = icalproperty_get_value(prop); if (value) { switch (icalproperty_isa(prop)) { case ICAL_CATEGORIES_PROPERTY: case ICAL_RESOURCES_PROPERTY: case ICAL_POLLPROPERTIES_PROPERTY: if (icalvalue_isa(value) == ICAL_TEXT_VALUE) { /* Handle multi-valued properties */ const char *str = icalvalue_as_ical_string(value); tok_t tok; tok_init(&tok, str, ",", TOK_TRIMLEFT|TOK_TRIMRIGHT|TOK_EMPTY); while ((str = tok_next(&tok))) { if (*str) json_array_append_new(jprop, json_string(str)); } tok_fini(&tok); break; } default: json_array_append_new(jprop, icalvalue_as_json_object(value)); break; } } return jprop; }
void virtual_downstream_node_init(VirtualDownstreamNode *node) { node->permissionList = NULL; dslink_map_init(&node->childrenNode, dslink_map_str_cmp, dslink_map_str_key_len_cal, dslink_map_hash_key); node->meta = json_object(); }
/** * \internal * \brief Write meta data on a single line json record */ static void FileWriteJsonRecord(JsonFileLogThread *aft, const Packet *p, const File *ff) { json_t *js = CreateJSONHeader((Packet *)p, 0, "fileinfo"); //TODO const json_t *hjs = NULL; if (unlikely(js == NULL)) return; /* reset */ MemBufferReset(aft->buffer); switch (p->flow->alproto) { case ALPROTO_HTTP: hjs = JsonHttpAddMetadata(p->flow, ff->txid); if (hjs) json_object_set_new(js, "http", hjs); break; case ALPROTO_SMTP: hjs = JsonSMTPAddMetadata(p->flow, ff->txid); if (hjs) json_object_set_new(js, "smtp", hjs); hjs = JsonEmailAddMetadata(p->flow, ff->txid); if (hjs) json_object_set_new(js, "email", hjs); break; } json_object_set_new(js, "app_proto", json_string(AppProtoToString(p->flow->alproto))); json_t *fjs = json_object(); if (unlikely(fjs == NULL)) { json_decref(js); return; } char *s = BytesToString(ff->name, ff->name_len); json_object_set_new(fjs, "filename", json_string(s)); if (s != NULL) SCFree(s); if (ff->magic) json_object_set_new(fjs, "magic", json_string((char *)ff->magic)); switch (ff->state) { case FILE_STATE_CLOSED: json_object_set_new(fjs, "state", json_string("CLOSED")); #ifdef HAVE_NSS if (ff->flags & FILE_MD5) { size_t x; int i; char s[256]; for (i = 0, x = 0; x < sizeof(ff->md5); x++) { i += snprintf(&s[i], 255-i, "%02x", ff->md5[x]); } json_object_set_new(fjs, "md5", json_string(s)); } #endif break; case FILE_STATE_TRUNCATED: json_object_set_new(fjs, "state", json_string("TRUNCATED")); break; case FILE_STATE_ERROR: json_object_set_new(fjs, "state", json_string("ERROR")); break; default: json_object_set_new(fjs, "state", json_string("UNKNOWN")); break; } json_object_set_new(fjs, "stored", (ff->flags & FILE_STORED) ? json_true() : json_false()); if (ff->flags & FILE_STORED) { json_object_set_new(fjs, "file_id", json_integer(ff->file_id)); } json_object_set_new(fjs, "size", json_integer(ff->size)); json_object_set_new(fjs, "tx_id", json_integer(ff->txid)); /* originally just 'file', but due to bug 1127 naming it fileinfo */ json_object_set_new(js, "fileinfo", fjs); OutputJSONBuffer(js, aft->filelog_ctx->file_ctx, &aft->buffer); json_object_del(js, "fileinfo"); switch (p->flow->alproto) { case ALPROTO_HTTP: json_object_del(js, "http"); break; case ALPROTO_SMTP: json_object_del(js, "smtp"); json_object_del(js, "email"); break; } json_object_clear(js); json_decref(js); }
json_t * get_top_hosts(char *filename) { FILE * pFile; char * line; char * running; char * piece; char * ip; char * hostname; char * mac; char * dl; char * ul; char * total; char * ls; int i; json_t * ret=json_array(); line = (char *)calloc(LINE_SIZE,sizeof(char)); running = (char *)calloc(SIZE,sizeof(char)); pFile=fopen(filename,"r"); while(!feof(pFile)) { fscanf(pFile,"%s",line); if(*line) { json_t * obj = json_object(); if(strstr(line, "Running") != NULL){ for(i=0;i<strlen(line);i++) { if(line[i] == ';') sprintf(running,"%s ",running); else sprintf(running,"%s%c",running,line[i]); } json_object_set_new(obj,"running",json_string(running)); } else { i=0; piece = strtok(line,";"); while (piece != NULL) { switch(i) { case 0:ip=piece;break; case 1:hostname=piece;break; case 2:mac=piece;break; case 3:dl=piece;break; case 4:ul=piece;break; case 5:total=piece;break; case 6:ls=piece;break; default:printf("Unknown item!\n");break; } piece=strtok(NULL,";"); i++; } json_object_set_new(obj,"ip",json_string(ip)); json_object_set_new(obj,"hostname",json_string(hostname)); json_object_set_new(obj,"mac",json_string(mac)); json_object_set_new(obj,"dl",json_string(dl)); json_object_set_new(obj,"ul",json_string(ul)); json_object_set_new(obj,"total",json_string(total)); json_object_set_new(obj,"ls",json_string(ls)); } json_array_append_new(ret,obj); } memset(line,0,LINE_SIZE*sizeof(char)); } fclose(pFile); free(line); free(running); return(ret); }
/* This callback handles Janus API requests */ static int janus_websockets_common_callback( struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len, gboolean admin) { const char *log_prefix = admin ? "AdminWSS" : "WSS"; janus_websockets_client *ws_client = (janus_websockets_client *)user; switch(reason) { case LWS_CALLBACK_ESTABLISHED: { /* Is there any filtering we should apply? */ char ip[256]; #ifdef HAVE_LIBWEBSOCKETS_PEER_SIMPLE lws_get_peer_simple(wsi, ip, 256); JANUS_LOG(LOG_VERB, "[%s-%p] WebSocket connection opened from %s\n", log_prefix, wsi, ip); #else char name[256]; lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name, 256, ip, 256); JANUS_LOG(LOG_VERB, "[%s-%p] WebSocket connection opened from %s by %s\n", log_prefix, wsi, ip, name); #endif if(!janus_websockets_is_allowed(ip, admin)) { JANUS_LOG(LOG_ERR, "[%s-%p] IP %s is unauthorized to connect to the WebSockets %s API interface\n", log_prefix, wsi, ip, admin ? "Admin" : "Janus"); /* Close the connection */ lws_callback_on_writable(wsi); return -1; } JANUS_LOG(LOG_VERB, "[%s-%p] WebSocket connection accepted\n", log_prefix, wsi); if(ws_client == NULL) { JANUS_LOG(LOG_ERR, "[%s-%p] Invalid WebSocket client instance...\n", log_prefix, wsi); return -1; } /* Prepare the session */ ws_client->wsi = wsi; ws_client->messages = g_async_queue_new(); ws_client->buffer = NULL; ws_client->buflen = 0; ws_client->bufpending = 0; ws_client->bufoffset = 0; g_atomic_int_set(&ws_client->destroyed, 0); ws_client->ts = janus_transport_session_create(ws_client, NULL); /* Let us know when the WebSocket channel becomes writeable */ lws_callback_on_writable(wsi); JANUS_LOG(LOG_VERB, "[%s-%p] -- Ready to be used!\n", log_prefix, wsi); /* Notify handlers about this new transport */ if(notify_events && gateway->events_is_enabled()) { json_t *info = json_object(); json_object_set_new(info, "event", json_string("connected")); json_object_set_new(info, "admin_api", admin ? json_true() : json_false()); json_object_set_new(info, "ip", json_string(ip)); gateway->notify_event(&janus_websockets_transport, ws_client->ts, info); } return 0; } case LWS_CALLBACK_RECEIVE: { JANUS_LOG(LOG_HUGE, "[%s-%p] Got %zu bytes:\n", log_prefix, wsi, len); if(ws_client == NULL || ws_client->wsi == NULL) { JANUS_LOG(LOG_ERR, "[%s-%p] Invalid WebSocket client instance...\n", log_prefix, wsi); return -1; } if(g_atomic_int_get(&ws_client->destroyed)) return 0; /* Is this a new message, or part of a fragmented one? */ const size_t remaining = lws_remaining_packet_payload(wsi); if(ws_client->incoming == NULL) { JANUS_LOG(LOG_HUGE, "[%s-%p] First fragment: %zu bytes, %zu remaining\n", log_prefix, wsi, len, remaining); ws_client->incoming = g_malloc(len+1); memcpy(ws_client->incoming, in, len); ws_client->incoming[len] = '\0'; JANUS_LOG(LOG_HUGE, "%s\n", ws_client->incoming); } else { size_t offset = strlen(ws_client->incoming); JANUS_LOG(LOG_HUGE, "[%s-%p] Appending fragment: offset %zu, %zu bytes, %zu remaining\n", log_prefix, wsi, offset, len, remaining); ws_client->incoming = g_realloc(ws_client->incoming, offset+len+1); memcpy(ws_client->incoming+offset, in, len); ws_client->incoming[offset+len] = '\0'; JANUS_LOG(LOG_HUGE, "%s\n", ws_client->incoming+offset); } if(remaining > 0 || !lws_is_final_fragment(wsi)) { /* Still waiting for some more fragments */ JANUS_LOG(LOG_HUGE, "[%s-%p] Waiting for more fragments\n", log_prefix, wsi); return 0; } JANUS_LOG(LOG_HUGE, "[%s-%p] Done, parsing message: %zu bytes\n", log_prefix, wsi, strlen(ws_client->incoming)); /* If we got here, the message is complete: parse the JSON payload */ json_error_t error; json_t *root = json_loads(ws_client->incoming, 0, &error); g_free(ws_client->incoming); ws_client->incoming = NULL; /* Notify the core, passing both the object and, since it may be needed, the error */ gateway->incoming_request(&janus_websockets_transport, ws_client->ts, NULL, admin, root, &error); return 0; } case LWS_CALLBACK_SERVER_WRITEABLE: { if(ws_client == NULL || ws_client->wsi == NULL) { JANUS_LOG(LOG_ERR, "[%s-%p] Invalid WebSocket client instance...\n", log_prefix, wsi); return -1; } if(!g_atomic_int_get(&ws_client->destroyed) && !g_atomic_int_get(&stopping)) { janus_mutex_lock(&ws_client->ts->mutex); /* Check if we have a pending/partial write to complete first */ if(ws_client->buffer && ws_client->bufpending > 0 && ws_client->bufoffset > 0 && !g_atomic_int_get(&ws_client->destroyed) && !g_atomic_int_get(&stopping)) { JANUS_LOG(LOG_HUGE, "[%s-%p] Completing pending WebSocket write (still need to write last %d bytes)...\n", log_prefix, wsi, ws_client->bufpending); int sent = lws_write(wsi, ws_client->buffer + ws_client->bufoffset, ws_client->bufpending, LWS_WRITE_TEXT); JANUS_LOG(LOG_HUGE, "[%s-%p] -- Sent %d/%d bytes\n", log_prefix, wsi, sent, ws_client->bufpending); if(sent > -1 && sent < ws_client->bufpending) { /* We still couldn't send everything that was left, we'll try and complete this in the next round */ ws_client->bufpending -= sent; ws_client->bufoffset += sent; } else { /* Clear the pending/partial write queue */ ws_client->bufpending = 0; ws_client->bufoffset = 0; } /* Done for this round, check the next response/notification later */ lws_callback_on_writable(wsi); janus_mutex_unlock(&ws_client->ts->mutex); return 0; } /* Shoot all the pending messages */ char *response = g_async_queue_try_pop(ws_client->messages); if(response && !g_atomic_int_get(&ws_client->destroyed) && !g_atomic_int_get(&stopping)) { /* Gotcha! */ int buflen = LWS_SEND_BUFFER_PRE_PADDING + strlen(response) + LWS_SEND_BUFFER_POST_PADDING; if (buflen > ws_client->buflen) { /* We need a larger shared buffer */ JANUS_LOG(LOG_HUGE, "[%s-%p] Re-allocating to %d bytes (was %d, response is %zu bytes)\n", log_prefix, wsi, buflen, ws_client->buflen, strlen(response)); ws_client->buflen = buflen; ws_client->buffer = g_realloc(ws_client->buffer, buflen); } memcpy(ws_client->buffer + LWS_SEND_BUFFER_PRE_PADDING, response, strlen(response)); JANUS_LOG(LOG_HUGE, "[%s-%p] Sending WebSocket message (%zu bytes)...\n", log_prefix, wsi, strlen(response)); int sent = lws_write(wsi, ws_client->buffer + LWS_SEND_BUFFER_PRE_PADDING, strlen(response), LWS_WRITE_TEXT); JANUS_LOG(LOG_HUGE, "[%s-%p] -- Sent %d/%zu bytes\n", log_prefix, wsi, sent, strlen(response)); if(sent > -1 && sent < (int)strlen(response)) { /* We couldn't send everything in a single write, we'll complete this in the next round */ ws_client->bufpending = strlen(response) - sent; ws_client->bufoffset = LWS_SEND_BUFFER_PRE_PADDING + sent; JANUS_LOG(LOG_HUGE, "[%s-%p] -- Couldn't write all bytes (%d missing), setting offset %d\n", log_prefix, wsi, ws_client->bufpending, ws_client->bufoffset); } /* We can get rid of the message */ free(response); /* Done for this round, check the next response/notification later */ lws_callback_on_writable(wsi); janus_mutex_unlock(&ws_client->ts->mutex); return 0; } janus_mutex_unlock(&ws_client->ts->mutex); } return 0; } case LWS_CALLBACK_CLOSED: { JANUS_LOG(LOG_VERB, "[%s-%p] WS connection down, closing\n", log_prefix, wsi); janus_websockets_destroy_client(ws_client, wsi, log_prefix); JANUS_LOG(LOG_VERB, "[%s-%p] -- closed\n", log_prefix, wsi); return 0; } case LWS_CALLBACK_WSI_DESTROY: { JANUS_LOG(LOG_VERB, "[%s-%p] WS connection down, destroying\n", log_prefix, wsi); janus_websockets_destroy_client(ws_client, wsi, log_prefix); JANUS_LOG(LOG_VERB, "[%s-%p] -- destroyed\n", log_prefix, wsi); return 0; } default: if(wsi != NULL) { JANUS_LOG(LOG_HUGE, "[%s-%p] %d (%s)\n", log_prefix, wsi, reason, janus_websockets_reason_string(reason)); } else { JANUS_LOG(LOG_HUGE, "[%s] %d (%s)\n", log_prefix, reason, janus_websockets_reason_string(reason)); } break; } return 0; }
int update_node_status(char *status, char *local_ipaddr, char *uuid, char *network_uuid) { jlog(L_DEBUG, "update node status"); char *query_str = NULL; json_t *query = NULL; json_t *node = NULL; if ((query = json_object()) == NULL) { jlog(L_ERROR, "json_object failed"); goto out; } if ((json_object_set_new(query, "action", json_string("update-node-status"))) == -1) { jlog(L_ERROR, "json_object_set_new failed"); goto out; } if ((node = json_object()) == NULL) { jlog(L_ERROR, "json_object failed"); goto out; } if ((json_object_set_new(query, "node", node)) == -1) { jlog(L_ERROR, "json_object_set_new failed"); goto out; } if ((json_object_set_new(node, "status", json_string(status))) == -1) { jlog(L_ERROR, "json_object_set_new failed"); goto out; } if ((json_object_set_new(node, "local-ipaddr", json_string(local_ipaddr))) == -1) { jlog(L_ERROR, "json_object_set_new failed"); goto out; } if ((json_object_set_new(node, "uuid", json_string(uuid))) == -1) { jlog(L_ERROR, "json_object_set_new failed"); goto out; } if ((json_object_set_new(node, "networkuuid", json_string(network_uuid))) == -1) { jlog(L_ERROR, "json_object_set_new failed"); goto out; } if ((query_str = json_dumps(query, 0)) == NULL) { jlog(L_ERROR, "json_dumps failed"); goto out; } write(pipefd[1], query_str, strlen(query_str)); json_decref(query); free(query_str); return 0; out: json_decref(query); free(query_str); return -1; }
int dslink_node_add_child(DSLink *link, DSNode *node) { assert(node); assert(node->parent); int ret = 0; if (!node->parent->children) { node->parent->children = malloc(sizeof(Map)); if (!node->parent->children) { return DSLINK_ALLOC_ERR; } if (dslink_map_init(node->parent->children, dslink_map_str_cmp, dslink_map_str_key_len_cal) != 0) { free(node->parent->children); node->parent->children = NULL; return DSLINK_ALLOC_ERR; } } assert(!dslink_map_contains(node->parent->children, (void *) node->name)); { DSNode *tmp = node; if ((ret = dslink_map_set(node->parent->children, (void *) node->name, (void **) &tmp)) != 0) { return ret; } } if (!link->_ws) { return ret; } uint32_t *id = dslink_map_get(link->responder->list_subs, (void *) node->parent->path); if (!id) { return ret; } json_t *top = json_object(); if (!top) { return ret; } json_t *resps = json_array(); if (!resps) { goto cleanup; } json_object_set_new_nocheck(top, "responses", resps); json_t *resp = json_object(); if (!resp) { goto cleanup; } json_array_append_new(resps, resp); json_object_set_new_nocheck(resp, "stream", json_string("open")); json_object_set_new_nocheck(resp, "rid", json_integer(*id)); json_t *updates = json_array(); if (!updates) { goto cleanup; } json_object_set_new_nocheck(resp, "updates", updates); json_t *update = json_array(); if (!update) { goto cleanup; } json_array_append_new(updates, update); dslink_response_list_append_child(update, node); dslink_ws_send_obj(link->_ws, top); cleanup: json_delete(top); return ret; }
void JsonApiHandlerWS::processApi(const string &data, const Params ¶msGET) { VAR_UNUSED(paramsGET); //not used for websocket Params jsonRoot; Params jsonData; //parse the json data json_error_t jerr; json_t *jroot = json_loads(data.c_str(), 0, &jerr); if (!jroot || !json_is_object(jroot)) { cDebugDom("network") << "Error loading json : " << jerr.text; return; } char *d = json_dumps(jroot, JSON_INDENT(4)); if (d) { cDebugDom("network") << d; free(d); } //decode the json root object into jsonParam jansson_decode_object(jroot, jsonRoot); json_t *jdata = json_object_get(jroot, "data"); if (jdata) jansson_decode_object(jdata, jsonData); //Format: { msg: "type", msg_id: id, data: {} } if (jsonRoot["msg"] == "login") { //check for if username/password matches string user = Utils::get_config_option("calaos_user"); string pass = Utils::get_config_option("calaos_password"); if (Utils::get_config_option("cn_user") != "" && Utils::get_config_option("cn_pass") != "") { user = Utils::get_config_option("cn_user"); pass = Utils::get_config_option("cn_pass"); } //Not logged in, need to wait for a correct login if (user != jsonData["cn_user"] || pass != jsonData["cn_pass"]) { cDebugDom("network") << "Login failed!"; json_t *jret = json_object(); json_object_set_new(jret, "success", json_string("false")); sendJson("login", jret, jsonRoot["msg_id"]); //Close the connection on login failure closeConnection.emit(WebSocketFrame::CloseCodeNormal, "login failed!"); } else { json_t *jret = json_object(); json_object_set_new(jret, "success", json_string("true")); sendJson("login", jret, jsonRoot["msg_id"]); loggedin = true; } } else if (loggedin) //only process other api if loggedin { if (jsonRoot["msg"] == "get_home") processGetHome(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "get_state") processGetState(jdata, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "get_states") processGetStates(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "query") processQuery(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "get_param") processGetParam(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "set_param") processSetParam(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "del_param") processDelParam(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "set_state") processSetState(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "get_playlist") processGetPlaylist(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "get_io") processGetIO(jdata, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "audio") processAudio(jdata, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "audio_db") processAudioDb(jdata, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "get_timerange") processGetTimerange(jsonData, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "set_timerange") processSetTimerange(jdata, jsonRoot["msg_id"]); else if (jsonRoot["msg"] == "autoscenario") processAutoscenario(jdata, jsonRoot["msg_id"]); // else if (jsonParam["action"] == "get_cover") // processGetCover(); // else if (jsonParam["action"] == "get_camera_pic") // processGetCameraPic(); // else if (jsonParam["action"] == "config") // processConfig(jroot); } json_decref(jroot); }
static json_t *bunser_object(const char *buf, const char *end, json_int_t *used, json_error_t *jerr) { json_int_t needed; json_int_t total = 0; json_int_t i, nelems; json_t *objval; char keybuf[128]; total = 1; buf++; if (!bunser_int(buf, end - buf, &needed, &nelems)) { *used = needed + total; snprintf(jerr->text, sizeof(jerr->text), "invalid object property count encoding"); return NULL; } total += needed; buf += needed; objval = json_object(); for (i = 0; i < nelems; i++) { const char *start; json_int_t slen; json_t *item; // Read key if (!bunser_bytestring(buf, end - buf, &needed, &start, &slen)) { *used = total + needed; json_decref(objval); snprintf(jerr->text, sizeof(jerr->text), "invalid bytestring for object key"); return NULL; } total += needed; buf += needed; // Saves us allocating a string when the library is going to // do that anyway if ((uint16_t)slen > sizeof(keybuf) - 1) { json_decref(objval); snprintf(jerr->text, sizeof(jerr->text), "object key is too long"); return NULL; } memcpy(keybuf, start, (size_t)slen); keybuf[slen] = '\0'; // Read value item = bunser(buf, end, &needed, jerr); total += needed; buf += needed; if (!item) { json_decref(objval); *used = total; return NULL; } if (json_object_set_new_nocheck(objval, keybuf, item)) { json_decref(item); json_decref(objval); *used = total; snprintf(jerr->text, sizeof(jerr->text), "failed to add object property"); return NULL; } } *used = total; return objval; }