Reimplement the load average plugin in pure Lua.
[wmiirc-lua.git] / luaixp / lixp_util.c
blob61a72bee9b26ce2d87f8235dc71c9294ca8572e0
1 #include <stdio.h>
2 #include <string.h>
3 #include <errno.h>
4 #include <time.h>
6 #include <ixp.h>
7 #include <lua.h>
8 #include <lauxlib.h>
10 #include "lixp_util.h"
13 /* ------------------------------------------------------------------------
14 * error helper
16 int lixp_pusherror(lua_State *L, const char *info)
18 lua_pushnil(L);
19 if (info==NULL) {
20 lua_pushstring(L, strerror(errno));
21 lua_pushnumber(L, errno);
22 return 3;
23 } else if (errno) {
24 lua_pushfstring(L, "%s: %s", info, strerror(errno));
25 lua_pushnumber(L, errno);
26 return 3;
27 } else {
28 lua_pushfstring(L, "%s", info);
29 return 2;
33 /* ------------------------------------------------------------------------
34 * write a buffer to an IXP file
36 int lixp_write_data (IxpCFid *fid, const char *data, size_t data_len)
38 size_t left;
39 off_t ofs = 0;
41 left = data_len;
42 while (left) {
43 int rc = ixp_write(fid, (char*)data + ofs, left);
44 if (rc < 0)
45 return rc;
47 else if (rc > left)
48 return -ENXIO;
50 left -= rc;
51 ofs += rc;
54 return data_len;
57 /* ------------------------------------------------------------------------
58 * dump IXP status structure to lua table
60 static void setrwx(long m, char *s)
62 static char *modes[] = {
63 "---", "--x", "-w-",
64 "-wx", "r--", "r-x",
65 "rw-", "rwx",
67 strncpy(s, modes[m], 3);
70 static void build_modestr(char *buf, const struct IxpStat *stat)
72 buf[0]='-';
73 if(stat->mode & P9_DMDIR)
74 buf[0]='d';
75 buf[1]='-';
76 setrwx((stat->mode >> 6) & 7, &buf[2]);
77 setrwx((stat->mode >> 3) & 7, &buf[5]);
78 setrwx((stat->mode >> 0) & 7, &buf[8]);
79 buf[11] = 0;
82 static void build_timestr(char *buf, const struct IxpStat *stat)
84 ctime_r((time_t*)&stat->mtime, buf);
85 buf[strlen(buf) - 1] = '\0';
89 #define setfield(type,name,value) \
90 lua_pushstring (L, name); \
91 lua_push##type (L, value); \
92 lua_settable (L, -3);
93 int lixp_pushstat (lua_State *L, const struct IxpStat *stat)
95 static char buf[32];
96 lua_newtable (L);
98 setfield(number, "type", stat->type);
99 setfield(number, "dev", stat->dev);
100 //setfield(Qid, "qid", stat->qid); // TODO: what is this?
101 setfield(number, "mode", stat->mode);
102 setfield(number, "atime", stat->atime);
103 setfield(number, "mtime", stat->mtime);
104 setfield(number, "length", stat->length);
105 setfield(string, "name", stat->name);
106 setfield(string, "uid", stat->uid);
107 setfield(string, "gid", stat->gid);
108 setfield(string, "muid", stat->muid);
110 build_modestr(buf, stat);
111 setfield(string, "modestr", buf);
113 build_timestr(buf, stat);
114 setfield(string, "timestr", buf);
116 return 1;