void runServer(const char *host, int port){ socketFd = socket(AF_INET, SOCK_STREAM, 0); if (socketFd < 0) { errorlog("create socket"); return; } setNonBlock(socketFd); struct sockaddr_in serverAddr; memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = inet_addr(host); serverAddr.sin_port = htons(port); if(bindSock(socketFd, &serverAddr, sizeof(serverAddr)) < 0){ errorlog("bind socket"); return; } if (listen(socketFd, max_bind_num) < 0) { errorlog("listen socket"); return; } waitAccept(); }
//自猜 int baiduapi_mkdir(const char *path, mode_t mode) { (void) mode; char buff[2048]; char fullpath[PATHLEN]; snprintf(fullpath, sizeof(fullpath) - 1, "%s%s", basepath, path); snprintf(buff, sizeof(buff) - 1, "https://pcs.baidu.com/rest/2.0/pcs/file?" "method=mkdir&" "access_token=%s&" "path=%s" , Access_Token, URLEncode(fullpath)); FILE *tpfile = tmpfile(); if (!tpfile) { int lasterrno = errno; errorlog("create temp file error:%s\n", strerror(errno)); return -lasterrno; } Http *r = Httpinit(buff); if (r == NULL) { int lasterrno = errno; errorlog("can't resolve domain:%s\n", strerror(errno)); fclose(tpfile); return -lasterrno; } r->method = get; r->writefunc = savetofile; r->writeprame = tpfile; if ((errno = request(r)) != CURLE_OK) { errorlog("network error:%d\n", errno); fclose(tpfile); Httpdestroy(r); return -EPROTO; } Httpdestroy(r); json_object *json_get = json_object_from_FILE(tpfile); fclose(tpfile); if (json_get == NULL) { errorlog("json_object_from_FILE filed!\n"); return -EPROTO; } json_object *jerror_code; if (json_object_object_get_ex(json_get, "error_code",&jerror_code)) { int errorno = json_object_get_int(jerror_code) ; json_object_put(json_get); return handleerror(errorno); } json_object_put(json_get); return 0; }
/* funzione utilizzate per la creazione di semafori, memorie e code di messaggi. * ritorna 1 se tutte le risorse sono allocate correttamente, 0 altrimenti. */ int server_start() { log_date(LOG_PATH, "(start) Avvio server"); get_date(start_date); // Creazione di semafori, memorie e code di messaggi if ((semid = semget(SEMKEY, SEM_TOT, 0600 | IPC_CREAT)) == -1) errorlog(LOG_PATH, "Semafori non allocati"); if ((shmid = shmget(SHMKEY, sizeof(repo), 0600 | IPC_CREAT)) == -1) errorlog( LOG_PATH, "Area di memoria Repository non allocata"); if ((shmlog = shmget(BUFFER_SHMKEY, sizeof(buffer), 0600 | IPC_CREAT)) == -1) errorlog( LOG_PATH, "Area di memoria LOG non allocata"); if ((shmls = shmget(LS_SHMKEY, sizeof(numlettori), 0600 | IPC_CREAT)) == -1) errorlog( LOG_PATH, "Area di memoria LETTORI/SCRITTORI non allocata"); if ((shmauth = shmget(AUTH_SHMKEY, sizeof(auth), 0600 | IPC_CREAT)) == -1) errorlog( LOG_PATH, "Area di memoria AUTORIZZAZIONI non allocata"); if ((shmpush = shmget(PUSH_SHMKEY, sizeof(push), 0600 | IPC_CREAT)) == -1) errorlog( LOG_PATH, "Area di memoria PUSH non allocata"); if ((msgid = msgget(MSGKEY, IPC_CREAT | 0600)) == -1) errorlog(LOG_PATH, "Coda messaggi non allocata"); // Controllo errori all'avvio */ if (semid == -1 || shmid == -1 || shmlog == -1 || shmls == -1 || shmauth == -1 || shmpush == -1 || msgid == -1) server_stop(); if (!setup()) { errorlog(LOG_PATH, "(start) File del repository iniziale non trovato"); return 0; } return 1; }
static int set_option_srv(char *filename, int line, OPTION *option, char *p) { SERVER *serv; char *q; struct servent *svp; int i; if (p == NULL) { errorlog("%s: line %d: bogus option value", filename, line); return (-1); } serv = (SERVER *) option->val; for (i = 0; i < serv->max; i++) { free(serv->name[i]); } serv->max = 0; while ((p = strtok(p, ", \t")) != NULL) { if ((q = strchr(p,':')) != NULL) { *q = '\0'; q++; serv->port[serv->max] = atoi(q); } else { if (!strcmp(option->name,"authserver")) if ((svp = getservbyname ("radius", "udp")) == NULL) serv->port[serv->max] = PW_AUTH_UDP_PORT; else serv->port[serv->max] = ntohs ((unsigned int) svp->s_port); else if (!strcmp(option->name, "acctserver")) if ((svp = getservbyname ("radacct", "udp")) == NULL) serv->port[serv->max] = PW_ACCT_UDP_PORT; else serv->port[serv->max] = ntohs ((unsigned int) svp->s_port); else { errorlog("%s: line %d: no default port for %s", filename, line, option->name); return (-1); } } serv->name[serv->max++] = strdup(p); p = NULL; } return 0; }
//从服务器读一个block void readblock(block *tb) { block b = *tb; free(tb); size_t startp = b.bno * RBS; char buff[2048]; char fullpath[PATHLEN]; snprintf(fullpath, sizeof(fullpath) - 1, "%s%s", basepath, b.fd->path); snprintf(buff, sizeof(buff) - 1, "https://pcs.baidu.com/rest/2.0/pcs/file?" "method=download&" "access_token=%s&" "path=%s" , Access_Token, URLEncode(fullpath)); char range[100] = {0}; snprintf(range, sizeof(range) - 1, "%lu-%lu", startp, startp + RBS - 1); char buf[RBS]; buffstruct bs = {0, RBS, buf}; Http *r = Httpinit(buff); if (r == NULL) { errorlog("can't resolve domain:%s\n", strerror(errno)); goto ret; } r->method = get; r->writefunc = savetobuff; r->writeprame = &bs; r->range = range; if ((errno = request(r)) != CURLE_OK) { errorlog("network error:%d\n", errno); Httpdestroy(r); goto ret; } Httpdestroy(r); pthread_mutex_lock(&b.fd->lock); lseek(b.fd->file, startp, SEEK_SET); write(b.fd->file,bs.buf, bs.offset); b.fd->cache.r.mask[b.bno / 32] |= 1 << (b.bno % 32); pthread_mutex_unlock(&b.fd->lock); return; ret: pthread_mutex_lock(&b.fd->lock); b.fd->cache.r.taskid[b.bno] = 0; pthread_mutex_unlock(&b.fd->lock); }
bool sbbs_t::checkfname(char *fname) { char str[256]; int c=0,d; if(fname[0]=='-' || strcspn(fname,ILLEGAL_FILENAME_CHARS)!=strlen(fname)) { SAFEPRINTF(str,"Suspicious filename attempt: '%s'",fname); errorlog(str); return(false); } if(strstr(fname,"..")) return(false); #if 0 /* long file name support */ if(strcspn(fname,".")>8) return(false); #endif d=strlen(fname); while(c<d) { if(fname[c]<=' ' || fname[c]&0x80) return(false); c++; } return(true); }
static void recv_config_pppoa(int mru, u_int32_t asyncmap, int pcomp, int accomp) { if (mru > pppoatm_max_mru) errorlog("Couldn't increase MRU to %d", mru); }
/********************************************************************** *%FUNCTION: etherType *%ARGUMENTS: * packet -- a received PPPoE packet *%RETURNS: * ethernet packet type (see /usr/include/net/ethertypes.h) *%DESCRIPTION: * Checks the ethernet packet header to determine its type. * We should only be receveing DISCOVERY and SESSION types if the BPF * is set up correctly. Logs an error if an unexpected type is received. * Note that the ethernet type names come from "pppoe.h" and the packet * packet structure names use the LINUX dialect to maintain consistency * with the rest of this file. See the BSD section of "pppoe.h" for * translations of the data structure names. ***********************************************************************/ UINT16_t etherType(PPPoEPacket *packet) { UINT16_t type = (UINT16_t) ntohs(packet->ethHdr.h_proto); if (type != Eth_PPPOE_Discovery && type != Eth_PPPOE_Session) { errorlog("Invalid ether type 0x%x", type); } return type; }
static int set_option_auo(char *filename, int line, OPTION *option, char *p) { int *iptr; if (p == NULL) { warnlog("%s: line %d: bogus option value", filename, line); return (-1); } if ((iptr = (int *) malloc(sizeof(iptr))) == NULL) { novm("read_config"); return (-1); } *iptr = 0; p = strtok(p, ", \t"); if (!strncmp(p, "local", 5)) *iptr = AUTH_LOCAL_FST; else if (!strncmp(p, "radius", 6)) *iptr = AUTH_RADIUS_FST; else { errorlog("%s: auth_order: unknown keyword: %s", filename, p); return (-1); } p = strtok(NULL, ", \t"); if (p && (*p != '\0')) { if ((*iptr & AUTH_RADIUS_FST) && !strcmp(p, "local")) *iptr = (*iptr) | AUTH_LOCAL_SND; else if ((*iptr & AUTH_LOCAL_FST) && !strcmp(p, "radius")) *iptr = (*iptr) | AUTH_RADIUS_SND; else { errorlog("%s: auth_order: unknown or unexpected keyword: %s", filename, p); return (-1); } } option->val = (void *) iptr; return 0; }
void lbind_register(lua_State *L, const char * funcname, lbind_function f) { lua_pushcfunction(L, lregister); lua_pushlightuserdata(L, (void *)funcname); lua_pushlightuserdata(L, f); int ret = lua_pcall(L, 2, 0, 0); if (ret != LUA_OK) { // ignore the error message, If you need log error message, use lua_tostring(L, -1) errorlog(L); } }
/* Funzione utilizzata per disallocare le risorse */ void server_stop() { int notread = 1; //Stampa i messagggi in coda while (number_msges_in_queue(msgid) != 0) { msgrcv(msgid, &req, msgl, 0, 0); writebuf("(messaggio) %d - pid %d - todo: %d tip: %ld\n", notread++, req.pid, req.todo, req.tipo); } termina_push(); //Termino i push // Scrittura su file del buffer buffer *log; log = (buffer *) shmat(shmlog, NULL, 0); if (log->n > 0) writelog(LOG_PATH, log->text, "a"); shmdt(log); // Salvo il repository attuale del server char mypack[MAX_STR + 5];int i = 0; char pidlog[25]; sprintf(pidlog, "%s_%d.repo", LOG_PATH, padre); log_date(pidlog, "(shutdown) Salvataggio repository su file"); for (; i < rep->n; i++) { sprintf(mypack, "%s %d\n", rep->lista[i].nome, rep->lista[i].ver); writelog(pidlog, mypack, "a"); } shmdt(rep); shmdt(aut); shmdt(pus); shmdt(ls); // Rimozione risorse allocate if (semctl(semid, 0, IPC_RMID) == -1) errorlog(LOG_PATH, "(shutdown) Impossibile rimuovere semafori"); if (shmctl(shmid, 0, IPC_RMID) == -1) errorlog(LOG_PATH, "(shutdown) Impossibile rimuovere Area di memoria Repository"); if (shmctl(shmlog, 0, IPC_RMID) == -1) errorlog(LOG_PATH, "(shutdown) Impossibile rimuovere Area di memoria LOG"); if (shmctl(shmls, 0, IPC_RMID) == -1) errorlog(LOG_PATH, "(shutdown) Impossibile rimuovere Area di memoria LETTORI/SCRITTORI"); if (shmctl(shmauth, 0, IPC_RMID) == -1) errorlog(LOG_PATH, "(shutdown) Impossibile rimuovere Area di memoria AUTORIZZAZIONI"); if (shmctl(shmpush, 0, IPC_RMID) == -1) errorlog(LOG_PATH, "(shutdown) Impossibile rimuovere Area di memoria PUSH"); if (msgctl(msgid, 0, IPC_RMID) == -1) errorlog(LOG_PATH, "(shutdown) Impossibile rimuovere coda messaggi"); //Statistiche log_date(LOG_PATH, "(stats) "); log_date(LOG_PATH, "(stats) %d richieste elaborate", counter_r); log_date(LOG_PATH, "(stats) %d richieste di download", counter_d); log_date(LOG_PATH, "(stats) %d richieste di upload", counter_u); log_date(LOG_PATH, "(stats) %d autorizzazioni client push", counter_p); log_date(LOG_PATH, "(stats) %d autorizzazioni client upload", counter_a); log_date(LOG_PATH, "(stats) Data di accensione\t --> %s", start_date); get_date(start_date); log_date(LOG_PATH, "(stats) Data di spegnimento\t --> %s", start_date); log_date(LOG_PATH, "(stats) "); log_date(LOG_PATH, "(shutdown) Spegnimento server completato"); exit(0); }
struct vars * lbind_args(lua_State *L) { struct vars * args = argvars(L,1); // try fetch args, never raise error if (args) return args; lua_pushcfunction(L, lnewargs); if (lua_pcall(L,0,1,0) != LUA_OK) { errorlog(L); return NULL; } args = lua_touserdata(L, -1); lua_pop(L, 1); return args; }
/*处理百度服务器返回的各种乱七八糟的错误码,转换成errno形式的 * 只有我经常碰到的错误,并且我能对应得上的一些 * 如果返回111,即AT过期,则刷新AT */ static int handleerror(const int error) { switch (error) { case 3: errno = ESRCH; break; case 4: errno = EACCES; break; case 5: errno = EPERM; break; case 111: //Access_Token 过期,重新刷新 refreshtoken(); errno = EAGAIN; break; case 31021: errno = ENETUNREACH; break; case 31023: errno = EINVAL; break; case 31061: errno = EEXIST; break; case 31062: errno = EBADF; break; case 31066: errno = ENOENT; break; case 31202: errno = ENOENT; break; default: errorlog("No defined errno:%d\n", error); errno = EPROTO; break; } return -errno; }
/* * 打开一个文件,如果这个文件在缓存里面存在,直接指向它,并将计数器加一 * 如果只读打开的话,生成一个读缓存文件 * 如果只写,读写打开,这个文件在服务器上存在的话,不行! * 否则,返回文件不存在 */ int baiduapi_open(const char *path, struct fuse_file_info *fi) { filedec *f = getfcache(path); if (f) { if ((f->flags & DELETE) || (f->type == forread && (fi->flags & O_ACCMODE) != O_RDONLY)) { pthread_mutex_unlock(&f->lock); return -EACCES; } fi->fh = (uint64_t) f; f->count++; if (f->flags & TRANSF) { f->flags |= REOPEN; } pthread_mutex_unlock(&f->lock); return 0; } struct stat t; int ret = baiduapi_getattr(path, &t); if (ret == -ENOENT) { if (fi->flags & O_CREAT) { //如果要求创建文件则调用create return baiduapi_create(path, 0, fi); } else { //否则返回文件不存在 return ret; } } else if ((fi->flags & O_ACCMODE) == O_RDONLY) { filedec *f = initfcache(path); if (f == NULL) { int lasterrno = errno; errorlog("Init fcache error:%s\n", strerror(errno)); return -lasterrno; } f->type = forread; f->count = 1; f->lengh = t.st_size; f->ctime = t.st_ctim.tv_sec; f->mtime = t.st_mtim.tv_sec; fi->fh = (uint64_t) f; return 0; } return -EACCES; }
static int ldofile(lua_State *L) { const char * filename = (const char *)lua_touserdata(L, 1); int ret = luaL_loadfile(L, filename); if (ret != LUA_OK) { // ignore the error message errorlog(L); if (ret == LUA_ERRFILE) { lua_pushinteger(L, LF_NOTFOUND); } else { lua_pushinteger(L, LF_ERRPARSE); } return 1; } ret = lua_pcall(L, 0, 0, 0); if (ret != LUA_OK) { // ignore the error message errorlog(L); lua_pushinteger(L, LF_ERRRUN); return 1; } lua_pushinteger(L, 0); return 1; }
int lbind_dofile(lua_State *L, const char * filename) { lua_pushcfunction(L, ldofile); lua_pushlightuserdata(L, (void *)filename); int ret = lua_pcall(L, 1, 1, 0); if (ret != LUA_OK) { // ignore the error message, If you need log error message, use lua_tostring(L, -1) errorlog(L); return -1; } else { int ret = lua_tointeger(L, -1); lua_pop(L, 1); return ret; } }
void waitAccept(){ PollfdHandler pfdHandler(max_bind_num); pfdHandler.addOneFd(socketFd, POLLIN | POLLOUT | POLLERR); while (true) { poll(pfdHandler.fds, pfdHandler.getCount(), -1); for (int i = 0; i < pfdHandler.getCount(); i++) { if(pfdHandler.fds[i].fd == socketFd){ if(pfdHandler.fds[i].revents){ int clientFd = accept(socketFd, NULL, NULL); if (clientFd < 0 && errno == EAGAIN) { //errorlog("accept"); }else{ pfdHandler.addOneFd(clientFd, POLLIN | POLLOUT | POLLERR); debuglog("one client connected! i = %d\n", i); } } }else{ if(pfdHandler.fds[i].revents & POLLIN){ debuglog("POLLIN! i = %d\n", i); char buf[4096], bf[512]; memset(buf, 0, 4096); memset(bf, 0, 512); ssize_t len = -1; char *p = buf; while ((len = read(pfdHandler.fds[i].fd, bf, 512)) > 0) { memcpy(p, bf, len); p += len; } if(len == 0 || (len < 0 && errno == EAGAIN)){ debuglog("client receive msg ok, msg=%s \n", buf); }else if(len < 0){ debuglog("client receive msg then remove client \n"); pfdHandler.removeOneFd(pfdHandler.fds[i].fd); } } if(pfdHandler.fds[i].revents & POLLOUT){ //debuglog("POLLOUT i = %d!\n", i); } if(pfdHandler.fds[i].revents & POLLERR){ debuglog("error i = %d, ", i); errorlog("POLLERR! then remove client!\n"); pfdHandler.removeOneFd(pfdHandler.fds[i].fd); } } } } }
struct vars * lbind_call(lua_State *L, const char * funcname, struct vars *args) { lua_pushcfunction(L, lcall); lua_pushlightuserdata(L, (void *)funcname); lua_pushlightuserdata(L, args); int ret = lua_pcall(L, 2, 1, 0); if (ret == LUA_OK) { struct vars * result = lua_touserdata(L,-1); lua_pop(L, 1); return result; } else { // ignore the error message, If you need log error message, use lua_tostring(L, -1) errorlog(L); return NULL; } }
static void send_config_pppoa(int mtu, u_int32_t asyncmap, int pcomp, int accomp) { int sock; struct ifreq ifr; if (mtu > pppoatm_max_mtu) errorlog("Couldn't increase MTU to %d", mtu); sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) fatallog("Couldn't create IP socket: %m"); strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)); ifr.ifr_mtu = mtu; if (ioctl(sock, SIOCSIFMTU, (caddr_t) &ifr) < 0) fatallog("ioctl(SIOCSIFMTU): %m"); (void) close (sock); }
static int set_option_int(char *filename, int line, OPTION *option, char *p) { int *iptr; if (p == NULL) { errorlog("%s: line %d: bogus option value", filename, line); return (-1); } if ((iptr = (int *) malloc(sizeof(iptr))) == NULL) { novm("read_config"); return (-1); } *iptr = atoi(p); option->val = (void *) iptr; return 0; }
//创建一个文件,并把它加到filelist里面 int baiduapi_create(const char *path, mode_t mode, struct fuse_file_info *fi) { (void) mode; filedec *f = initfcache(path); if (f == NULL) { int lasterrno = errno; errorlog("Init fcache error:%s\n", strerror(errno)); return -lasterrno; } f->type = forwrite; f->count = 1; f->ctime = time(NULL); SETD(f->cache.w.flags, 0); fi->fh = (uint64_t) f; return 0; }
static int pwfd_passwd (char *user, char *passwd) { int readgood, red; if (passwdfd == -1) return -1; if (passwd == NULL) return 1; if (passwdfd == -2) { strcpy (passwd, save_passwd); return 1; } readgood = 0; do { red = read (passwdfd, passwd + readgood, MAXSECRETLEN - 1 - readgood); if (red == 0) break; if (red < 0) { errorlog("Can't read secret from fd\n"); readgood = -1; break; } readgood += red; } while (readgood < MAXSECRETLEN - 1); close (passwdfd); if (readgood < 0) return 0; passwd[readgood] = 0; strcpy (save_passwd, passwd); passwdfd = -2; return 1; }
int rc_find_server (char *server_name, UINT4 *ip_addr, char *secret) { UINT4 myipaddr = 0; int len; int result; FILE *clientfd; char *h; char *s; char *host2; char buffer[128]; char hostnm[AUTH_ID_LEN + 1]; /* Get the IP address of the authentication server */ if ((*ip_addr = rc_get_ipaddr (server_name)) == (UINT4) 0) return (-1); if ((clientfd = fopen (rc_conf_str("servers"), "r")) == (FILE *) NULL) { errorlog("rc_find_server: couldn't open file: %m: %s", rc_conf_str("servers")); return (-1); } myipaddr = rc_own_ipaddress(); result = 0; while (fgets (buffer, sizeof (buffer), clientfd) != (char *) NULL) { if (*buffer == '#') continue; if ((h = strtok (buffer, " \t\n")) == NULL) /* first hostname */ continue; memset (hostnm, '\0', AUTH_ID_LEN); len = strlen (h); if (len > AUTH_ID_LEN) { len = AUTH_ID_LEN; } strncpy (hostnm, h, (size_t) len); hostnm[AUTH_ID_LEN] = '\0'; if ((s = strtok (NULL, " \t\n")) == NULL) /* and secret field */ continue; memset (secret, '\0', MAX_SECRET_LENGTH); len = strlen (s); if (len > MAX_SECRET_LENGTH) { len = MAX_SECRET_LENGTH; } strncpy (secret, s, (size_t) len); secret[MAX_SECRET_LENGTH] = '\0'; if (!strchr (hostnm, '/')) /* If single name form */ { if (find_match (ip_addr, hostnm) == 0) { result++; break; } } else /* <name1>/<name2> "paired" form */ { strtok (hostnm, "/"); if (find_match (&myipaddr, hostnm) == 0) { /* If we're the 1st name, target is 2nd */ host2 = strtok (NULL, " "); if (find_match (ip_addr, host2) == 0) { result++; break; } } else /* If we were 2nd name, target is 1st name */ { if (find_match (ip_addr, hostnm) == 0) { result++; break; } } } } fclose (clientfd); if (result == 0) { memset (buffer, '\0', sizeof (buffer)); memset (secret, '\0', sizeof (secret)); errorlog("rc_find_server: couldn't find RADIUS server %s in %s", server_name, rc_conf_str("servers")); return (-1); } return 0; }
static int test_config(char *filename) { #if 0 struct stat st; char *file; #endif if (!(rc_conf_srv("authserver")->max)) { errorlog("%s: no authserver specified", filename); return (-1); } if (!(rc_conf_srv("acctserver")->max)) { errorlog("%s: no acctserver specified", filename); return (-1); } if (!rc_conf_str("servers")) { errorlog("%s: no servers file specified", filename); return (-1); } if (!rc_conf_str("dictionary")) { errorlog("%s: no dictionary specified", filename); return (-1); } if (rc_conf_int("radius_timeout") <= 0) { errorlog("%s: radius_timeout <= 0 is illegal", filename); return (-1); } if (rc_conf_int("radius_retries") <= 0) { errorlog("%s: radius_retries <= 0 is illegal", filename); return (-1); } #if 0 file = rc_conf_str("login_local"); if (stat(file, &st) == 0) { if (!S_ISREG(st.st_mode)) { errorlog("%s: not a regular file: %s", filename, file); return (-1); } } else { errorlog("%s: file not found: %s", filename, file); return (-1); } file = rc_conf_str("login_radius"); if (stat(file, &st) == 0) { if (!S_ISREG(st.st_mode)) { errorlog("%s: not a regular file: %s", filename, file); return (-1); } } else { errorlog("%s: file not found: %s", filename, file); return (-1); } #endif if (rc_conf_int("login_tries") <= 0) { errorlog("%s: login_tries <= 0 is illegal", filename); return (-1); } if (rc_conf_str("seqfile") == NULL) { errorlog("%s: seqfile not specified", filename); return (-1); } if (rc_conf_int("login_timeout") <= 0) { errorlog("%s: login_timeout <= 0 is illegal", filename); return (-1); } if (rc_conf_str("mapfile") == NULL) { errorlog("%s: mapfile not specified", filename); return (-1); } if (rc_conf_str("nologin") == NULL) { errorlog("%s: nologin not specified", filename); return (-1); } return 0; }
int rc_read_config(char *filename) { FILE *configfd; char buffer[512], *p; OPTION *option; int line, pos; if ((configfd = fopen(filename,"r")) == NULL) { errorlog("rc_read_config: can't open %s: %m", filename); return (-1); } line = 0; while ((fgets(buffer, sizeof(buffer), configfd) != NULL)) { line++; p = buffer; if ((*p == '\n') || (*p == '#') || (*p == '\0')) continue; p[strlen(p)-1] = '\0'; if ((pos = strcspn(p, "\t ")) == 0) { errorlog("%s: line %d: bogus format: %s", filename, line, p); return (-1); } p[pos] = '\0'; if ((option = find_option(p, OT_ANY)) == NULL) { errorlog("%s: line %d: unrecognized keyword: %s", filename, line, p); return (-1); } if (option->status != ST_UNDEF) { errorlog("%s: line %d: duplicate option line: %s", filename, line, p); return (-1); } p += pos+1; while (isspace(*p)) p++; switch (option->type) { case OT_STR: if (set_option_str(filename, line, option, p) < 0) return (-1); break; case OT_INT: if (set_option_int(filename, line, option, p) < 0) return (-1); break; case OT_SRV: if (set_option_srv(filename, line, option, p) < 0) return (-1); break; case OT_AUO: if (set_option_auo(filename, line, option, p) < 0) return (-1); break; default: fatallog("rc_read_config: impossible case branch!"); abort(); } } fclose(configfd); return test_config(filename); }
/********************************************************************** *%FUNCTION: openInterface *%ARGUMENTS: * ifname -- name of interface * type -- Ethernet frame type * hwaddr -- if non-NULL, set to the hardware address *%RETURNS: * A raw socket for talking to the Ethernet card. Exits on error. *%DESCRIPTION: * Opens a raw Ethernet socket ***********************************************************************/ int openInterface(char const *ifname, UINT16_t type, unsigned char *hwaddr) { int optval=1; int fd; struct ifreq ifr; int domain, stype; #ifdef HAVE_STRUCT_SOCKADDR_LL struct sockaddr_ll sa; #else struct sockaddr sa; #endif memset(&sa, 0, sizeof(sa)); #ifdef HAVE_STRUCT_SOCKADDR_LL domain = PF_PACKET; stype = SOCK_RAW; #else domain = PF_INET; stype = SOCK_PACKET; #endif if ((fd = socket(domain, stype, htons(type))) < 0) { /* Give a more helpful message for the common error case */ if (errno == EPERM) { fatallog("Cannot create raw socket -- pppoe must be run as root."); } fatallog("cannot create the raw socket: %m"); } if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)) < 0) { fatallog("setsockopt(SOL_SOCKET, SO_BROADCAST): %m"); } /* Fill in hardware address */ if (hwaddr) { strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)); if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) { fatallog("ioctl(SIOCGIFHWADDR): %m"); } memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, ETH_ALEN); #ifdef ARPHRD_ETHER if (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) { fatallog("Interface %s is not Ethernet", ifname); } #endif if (NOT_UNICAST(hwaddr)) { fatallog("Interface %s has broadcast/multicast MAC address", ifname); } } /* Sanity check on MTU */ strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)); if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) { fatallog("ioctl(SIOCGIFMTU): %m"); } if (ifr.ifr_mtu < ETH_DATA_LEN) { errorlog("Interface %s has MTU of %d -- should be %d." " You may have serious connection problems.", ifname, ifr.ifr_mtu, ETH_DATA_LEN); } #ifdef HAVE_STRUCT_SOCKADDR_LL /* Get interface index */ sa.sll_family = AF_PACKET; sa.sll_protocol = htons(type); strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)); if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) { fatallog("ioctl(SIOCFIGINDEX): Could not get interface index: %m"); } sa.sll_ifindex = ifr.ifr_ifindex; #else strcpy(sa.sa_data, ifname); #endif /* We're only interested in packets on specified interface */ if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0) { fatallog("bind: %m"); } return fd; }
/*********************************************************************** *%FUNCTION: receivePacket *%ARGUMENTS: * sock -- socket to read from * pkt -- place to store the received packet * size -- set to size of packet in bytes *%RETURNS: * >= 0 if all OK; < 0 if error *%DESCRIPTION: * Receives a packet ***********************************************************************/ int receivePacket(int sock, PPPoEPacket *pkt, int *size) { #ifdef USE_BPF struct bpf_hdr hdr; int seglen, copylen; if (bpfSize <= 0) { bpfOffset = 0; if ((bpfSize = read(sock, bpfBuffer, bpfLength)) < 0) { fatallog("receivePacket: read: %m"); } } if (bpfSize < sizeof(hdr)) { errorlog("Truncated bpf packet header: len=%d", bpfSize); clearPacketHeader(pkt); /* resets bpfSize and bpfOffset */ return 0; } memcpy(&hdr, bpfBuffer + bpfOffset, sizeof(hdr)); if (hdr.bh_caplen != hdr.bh_datalen) { errorlog("Truncated bpf packet: caplen=%d, datalen=%d", hdr.bh_caplen, hdr.bh_datalen); clearPacketHeader(pkt); /* resets bpfSize and bpfOffset */ return 0; } seglen = hdr.bh_hdrlen + hdr.bh_caplen; if (seglen > bpfSize) { errorlog("Truncated bpf packet: seglen=%d, bpfSize=%d", seglen, bpfSize); clearPacketHeader(pkt); /* resets bpfSize and bpfOffset */ return 0; } seglen = BPF_WORDALIGN(seglen); *size = copylen = ((hdr.bh_caplen < sizeof(PPPoEPacket)) ? hdr.bh_caplen : sizeof(PPPoEPacket)); memcpy(pkt, bpfBuffer + bpfOffset + hdr.bh_hdrlen, copylen); if (seglen >= bpfSize) { bpfSize = bpfOffset = 0; } else { bpfSize -= seglen; bpfOffset += seglen; } #else #ifdef USE_DLPI struct strbuf data; int flags = 0; int retval; data.buf = (char *) pkt; data.maxlen = MAXDLBUF; data.len = 0; if ((retval = getmsg(sock, NULL, &data, &flags)) < 0) { fatallog("receivePacket: getmsg: %m"); } *size = data.len; #else if ((*size = recv(sock, pkt, sizeof(PPPoEPacket), 0)) < 0) { fatallog("receivePacket: recv: %m"); } #endif #endif return 0; }
int rc_read_dictionary (char *filename) { FILE *dictfd; char dummystr[AUTH_ID_LEN]; char namestr[AUTH_ID_LEN]; char valstr[AUTH_ID_LEN]; char attrstr[AUTH_ID_LEN]; char typestr[AUTH_ID_LEN]; char vendorstr[AUTH_ID_LEN]; int line_no; DICT_ATTR *attr; DICT_VALUE *dval; VENDOR_DICT *vdict; char buffer[256]; int value; int type; int n; int retcode; if ((dictfd = fopen (filename, "r")) == (FILE *) NULL) { errorlog( "rc_read_dictionary: couldn't open dictionary %s: %s", filename, strerror(errno)); return (-1); } line_no = 0; retcode = 0; while (fgets (buffer, sizeof (buffer), dictfd) != (char *) NULL) { line_no++; /* Skip empty space */ if (*buffer == '#' || *buffer == '\0' || *buffer == '\n') { continue; } if (strncmp (buffer, "VENDOR", 6) == 0) { /* Read the VENDOR line */ if (sscanf(buffer, "%s%s%d", dummystr, namestr, &value) != 3) { errorlog("rc_read_dictionary: invalid vendor on line %d of dictionary %s", line_no, filename); retcode = -1; break; } /* Validate entry */ if (strlen (namestr) > NAME_LENGTH) { errorlog("rc_read_dictionary: invalid name length on line %d of dictionary %s", line_no, filename); retcode = -1; break; } /* Create new vendor entry */ vdict = (VENDOR_DICT *) malloc (sizeof (VENDOR_DICT)); if (!vdict) { novm("rc_read_dictionary"); retcode = -1; break; } strcpy(vdict->vendorname, namestr); vdict->vendorcode = value; vdict->attributes = NULL; vdict->next = vendor_dictionaries; vendor_dictionaries = vdict; } else if (strncmp (buffer, "ATTRIBUTE", 9) == 0) { /* Read the ATTRIBUTE line. It is one of: * ATTRIBUTE attr_name attr_val type OR * ATTRIBUTE attr_name attr_val type vendor */ vendorstr[0] = 0; n = sscanf(buffer, "%s%s%s%s%s", dummystr, namestr, valstr, typestr, vendorstr); if (n != 4 && n != 5) { errorlog("rc_read_dictionary: invalid attribute on line %d of dictionary %s", line_no, filename); retcode = -1; break; } /* * Validate all entries */ if (strlen (namestr) > NAME_LENGTH) { errorlog("rc_read_dictionary: invalid name length on line %d of dictionary %s", line_no, filename); retcode = -1; break; } if (strlen (vendorstr) > NAME_LENGTH) { errorlog("rc_read_dictionary: invalid name length on line %d of dictionary %s", line_no, filename); retcode = -1; break; } if (!isdigit (*valstr)) { errorlog("rc_read_dictionary: invalid value on line %d of dictionary %s", line_no, filename); retcode = -1; break; } value = atoi (valstr); if (strcmp (typestr, "string") == 0) { type = PW_TYPE_STRING; } else if (strcmp (typestr, "integer") == 0) { type = PW_TYPE_INTEGER; } else if (strcmp (typestr, "ipaddr") == 0) { type = PW_TYPE_IPADDR; } else if (strcmp (typestr, "date") == 0) { type = PW_TYPE_DATE; } else { errorlog("rc_read_dictionary: invalid type on line %d of dictionary %s", line_no, filename); retcode = -1; break; } /* Search for vendor if supplied */ if (*vendorstr) { vdict = rc_dict_findvendor(vendorstr); if (!vdict) { errorlog("rc_read_dictionary: unknown vendor on line %d of dictionary %s", line_no, filename); retcode = -1; break; } } else { vdict = NULL; } /* Create a new attribute for the list */ if ((attr = (DICT_ATTR *) malloc (sizeof (DICT_ATTR))) == (DICT_ATTR *) NULL) { novm("rc_read_dictionary"); retcode = -1; break; } strcpy (attr->name, namestr); if (vdict) { attr->vendorcode = vdict->vendorcode; } else { attr->vendorcode = VENDOR_NONE; } attr->value = value; attr->type = type; /* Insert it into the list */ if (vdict) { attr->next = vdict->attributes; vdict->attributes = attr; } else { attr->next = dictionary_attributes; dictionary_attributes = attr; } } else if (strncmp (buffer, "VALUE", 5) == 0) { /* Read the VALUE line */ if (sscanf (buffer, "%s%s%s%s", dummystr, attrstr, namestr, valstr) != 4) { errorlog("rc_read_dictionary: invalid value entry on line %d of dictionary %s", line_no, filename); retcode = -1; break; } /* * Validate all entries */ if (strlen (attrstr) > NAME_LENGTH) { errorlog("rc_read_dictionary: invalid attribute length on line %d of dictionary %s", line_no, filename); retcode = -1; break; } if (strlen (namestr) > NAME_LENGTH) { errorlog("rc_read_dictionary: invalid name length on line %d of dictionary %s", line_no, filename); retcode = -1; break; } if (!isdigit (*valstr)) { errorlog("rc_read_dictionary: invalid value on line %d of dictionary %s", line_no, filename); retcode = -1; break; } value = atoi (valstr); /* Create a new VALUE entry for the list */ if ((dval = (DICT_VALUE *) malloc (sizeof (DICT_VALUE))) == (DICT_VALUE *) NULL) { novm("rc_read_dictionary"); retcode = -1; break; } strcpy (dval->attrname, attrstr); strcpy (dval->name, namestr); dval->value = value; /* Insert it into the list */ dval->next = dictionary_values; dictionary_values = dval; } else if (strncmp (buffer, "INCLUDE", 7) == 0) { /* Read the INCLUDE line */ if (sscanf (buffer, "%s%s", dummystr, namestr) != 2) { errorlog("rc_read_dictionary: invalid include entry on line %d of dictionary %s", line_no, filename); retcode = -1; break; } if (rc_read_dictionary(namestr) == -1) { retcode = -1; break; } } } fclose (dictfd); return retcode; }
int main(int argc, char* argv[]) #endif { setlocale(LC_NUMERIC, "C"); std::stringstream dummy; PATHMANAGER::Init(dummy, dummy); /// open Log file //---------------------------------------------------------------- std::string logfilename = PATHMANAGER::GetLogDir() + "/log.txt"; std::ofstream logfile(logfilename.c_str()); if (!logfile) { std::cerr << "Couldn't open log file: " << logfilename << std::endl; return EXIT_FAILURE; } // set up logging arrangement logging::splitterstreambuf infosplitter(std::cout, logfile); std::ostream infosplitterstream(&infosplitter); logging::splitterstreambuf errorsplitter(std::cerr, logfile); std::ostream errorsplitterstream(&errorsplitter); logging::logstreambuf infolog("INFO: ", infosplitterstream); //logstreambuf infolog("INFO: ", logfile); logging::logstreambuf errorlog("ERROR: ", errorsplitterstream); // primary logging ostreams std::ostream info_output(&infolog); std::ostream error_output(&errorlog);/**/ /// Load Settings //---------------------------------------------------------------- SETTINGS* settings = new SETTINGS(); std::string setFile = PATHMANAGER::GetSettingsFile(); if (!PATHMANAGER::FileExists(setFile)) { info_output << "Settings not found - loading defaults." << std::endl; LoadDefaultSet(settings,setFile); } settings->Load(setFile); // LOAD if (settings->version != SET_VER) // loaded older, use default { info_output << "Settings found, but older version - loading defaults." << std::endl; LoadDefaultSet(settings,setFile); settings->Load(setFile); // LOAD } // HACK: we initialize paths a second time now that we have the output streams PATHMANAGER::Init(info_output, error_output); /// Game start //---------------------------------------------------------------- GAME* pGame = new GAME(info_output, error_output, settings); std::list <std::string> args;//(argv, argv + argc); pGame->Start(args); //game.End(); App* pApp = new App(); pApp->pSet = settings; pApp->pGame = pGame; pGame->pOgreGame = pApp; try { if (settings->multi_thr > 0) boost::thread t(VprThread, pApp); #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 pApp->Run( settings->ogre_dialog || lpCmdLine[0]!=0 ); //Release change- #else pApp->Run( settings->ogre_dialog); #endif } catch (Ogre::Exception& e) { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 MessageBoxA( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL); #else std::cerr << "An exception has occured: " << e.getFullDescription().c_str() << std::endl; #endif } info_output << "Exiting" << std::endl; delete pApp; delete pGame; delete settings; return 0; }
int main(int argc, char *argv[]) { /* Richiesta di shutdown server */ if (argc > 1) if (!strcmp(argv[1], "shutdown") || !strcmp(argv[1], "-f")) shutdown(); else { printf("Errore parametro in input\n\n"); exit(0); } /* Avvio del server */ server_start(); int termina = FALSE; do { // Sono il padre if (termina && number_msges_in_queue(msgid) == 0) server_stop(); if (padre == -1) { errorlog(LOG_PATH, "Impossibile eseguire la fork"); server_stop(); } // In attesa di messaggi dal client if(msg_receive(&req, msgl, msgid, 1) < 0) { errorlog(LOG_PATH, "Impossibile ricevere messaggi"); server_stop(); } if (req.pid == -2) termina = TRUE; else { // Statistiche counter_r++; if(req.todo == M_DOWN || req.todo == M_DALL) counter_d++; else if(req.todo == M_ADD || req.todo == M_UPD) counter_u++; else if(req.todo == M_PUSH) counter_p++; else if(req.todo == M_AUTH && req.pwd != -1) //Non conto i logout counter_a++; // Fine Statistiche waitS(SEM_SERVER); //WAIT su semaforo per avere al massimo 5 figli del server padre = fork(); } } while (padre); /* Sono il figlio */ if (!padre) { // Invio di un pacchetto dal server al client if (req.todo == M_DOWN) download_one(); // Riceve un pacchetto dal client da aggiungere else if (req.todo == M_ADD) aggiungi_pkg(); // Riceve un pacchetto dal client da aggiornare else if (req.todo == M_UPD) aggiorna_pkg(); // Richiesta di tutto il repository da parte del cliente else if (req.todo == M_DALL) download_all(); // Autenticazione clienti di upload else if (req.todo == M_AUTH) autentica(); // Registrazione client push else if (req.todo == M_PUSH) registra_push(); else writebuf("(unknow)\t %d Richiesta non riconosciuta [ERRORE] \n", req.pid); //WAIT su semaforo per lasciare la possibilità ad un altro figlio del server di generarsi signalS(SEM_SERVER); } return 0; }