aboutsummaryrefslogtreecommitdiff
path: root/net.c
diff options
context:
space:
mode:
authortomsmeding <tom.smeding@gmail.com>2017-04-14 20:43:29 +0200
committertomsmeding <tom.smeding@gmail.com>2017-04-14 20:43:29 +0200
commitc02fa99188c868496f864a20b1139ec4e6f93c2a (patch)
treea1c2b5ac84405da437bba639da75286a29961770 /net.c
parenta1667f92905da03c1c3e26e8311fa7bd2802ca78 (diff)
server: Factor out net related functions from command.c
Diffstat (limited to 'net.c')
-rw-r--r--net.c75
1 files changed, 75 insertions, 0 deletions
diff --git a/net.c b/net.c
new file mode 100644
index 0000000..8e6644c
--- /dev/null
+++ b/net.c
@@ -0,0 +1,75 @@
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <sys/socket.h>
+#include "net.h"
+
+
+bool net_send_raw_text(int fd,const char *text,i64 len){
+ i64 cursor=0;
+ while(cursor<len){
+ i64 nwr=send(fd,text+cursor,len-cursor,0);
+ if(nwr<0){
+ if(errno==EINTR)continue;
+ if(errno==ECONNRESET||errno==EPIPE)return true;
+ die_perror("send");
+ }
+ cursor+=nwr;
+ }
+ return false;
+}
+
+bool net_send_ok(int fd,const char *tag){
+ char *buf=NULL;
+ i64 len=asprintf(&buf,"%s ok\n",tag);
+ bool closed=net_send_raw_text(fd,buf,len);
+ free(buf);
+ return closed;
+}
+
+bool net_send_error(int fd,const char *tag,const char *msg){
+ char *buf=NULL;
+ i64 len=asprintf(&buf,"%s error %s\n",tag,msg);
+ bool closed=net_send_raw_text(fd,buf,len);
+ free(buf);
+ return closed;
+}
+
+bool net_send_name(int fd,const char *tag,const char *name){
+ char *buf=NULL;
+ i64 len=asprintf(&buf,"%s name %s\n",tag,name);
+ bool closed=net_send_raw_text(fd,buf,len);
+ free(buf);
+ return closed;
+}
+
+bool net_send_list(int fd,const char *tag,i64 count,const char **list){
+ char *buf=NULL;
+ i64 len=asprintf(&buf,"%s list %" PRIi64,tag,count);
+ bool closed=net_send_raw_text(fd,buf,len);
+ free(buf);
+ if(closed)return true;
+
+ if(count>0){
+ i64 bufsz=64;
+ buf=malloc(bufsz,char);
+
+ for(i64 i=0;i<count;i++){
+ i64 len=strlen(list[i]);
+ if(len>=bufsz){
+ bufsz=len+512;
+ buf=realloc(buf,bufsz,char);
+ }
+ memcpy(buf+1,list[i],len);
+ buf[0]=' ';
+ if(net_send_raw_text(fd,buf,len+1)){
+ free(buf);
+ return true;
+ }
+ }
+
+ free(buf);
+ }
+
+ return net_send_raw_text(fd,"\n",1);
+}