Sun, 04 Dec 2022 13:01:00 +0100
implement most nsapi expression operators
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2017 Olaf Wintermann. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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 HOLDER 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. */ #include "srvctrlsocket.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <sys/un.h> SrvConnection* srvctrl_connet(char *socketfile) { if(!socketfile) { fprintf(stderr, "srvctrl_connect: no socketfile\n"); return NULL; } size_t len = strlen(socketfile); if(len == 0) { fprintf(stderr, "srvctrl_connect: invalid socket path\n"); return NULL; } if(len > 100) { fprintf(stderr, "srvctrl_connect: socket path too long\n"); return NULL; } int fd = socket(AF_UNIX, SOCK_STREAM, 0); if(fd == -1) { perror("srvctrl_connect: cannot create socket"); return NULL; } struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; memcpy(addr.sun_path, socketfile, len); if(connect(fd, (struct sockaddr*)&addr, sizeof(addr))) { perror("srvctrl_connect"); close(fd); return NULL; } FILE *stream = fdopen(fd, "r+"); if(!stream) { close(fd); return NULL; } SrvConnection *conn = calloc(1, sizeof(SrvConnection)); conn->socket = fd; conn->stream = stream; return conn; } void srvctrl_close(SrvConnection *conn) { fclose(conn->stream); free(conn); } int srvctrl_readmsg(SrvConnection *conn, SrvMsg *msg) { int type = 0; uint16_t length; type = fgetc(conn->stream); if(type == EOF) { return 1; } if(fread(&length, 1, 2, conn->stream) != 2) { return -1; } msg->type = type; msg->length = length; msg->message = malloc(length); size_t r = fread(msg->message, 1, length, conn->stream); if(r != length) { free(msg->message); return -1; } return 0; }