void ziflist_reload (ziflist_t *self) { assert (self); zlistx_t *list = (zlistx_t *) self; zlistx_purge (list); #if defined (HAVE_GETIFADDRS) struct ifaddrs *interfaces; if (getifaddrs (&interfaces) == 0) { struct ifaddrs *interface = interfaces; while (interface) { // On Solaris, loopback interfaces have a NULL in ifa_broadaddr if ( interface->ifa_broadaddr && interface->ifa_addr && interface->ifa_addr->sa_family == AF_INET && s_valid_flags (interface->ifa_flags)) { inaddr_t address = *(inaddr_t *) interface->ifa_addr; inaddr_t netmask = *(inaddr_t *) interface->ifa_netmask; inaddr_t broadcast = *(inaddr_t *) interface->ifa_broadaddr; // If the returned broadcast address is the same as source // address, build the broadcast address from the source // address and netmask. if (address.sin_addr.s_addr == broadcast.sin_addr.s_addr) broadcast.sin_addr.s_addr |= ~(netmask.sin_addr.s_addr); interface_t *item = s_interface_new (interface->ifa_name, address, netmask, broadcast); if (item) zlistx_add_end (list, item); } interface = interface->ifa_next; } } freeifaddrs (interfaces); # elif defined (__UNIX__) int sock = socket (AF_INET, SOCK_DGRAM, 0); if (sock != -1) { int num_interfaces = 0; struct ifconf ifconfig = { 0 }; // First ioctl call gets us length of buffer; second call gets us contents if (!ioctl (sock, SIOCGIFCONF, (caddr_t) &ifconfig, sizeof (struct ifconf))) { ifconfig.ifc_buf = (char *) zmalloc (ifconfig.ifc_len); if (!ioctl (sock, SIOCGIFCONF, (caddr_t) &ifconfig, sizeof (struct ifconf))) num_interfaces = ifconfig.ifc_len / sizeof (struct ifreq); } int index; for (index = 0; index < num_interfaces; index++) { struct ifreq *ifr = &ifconfig.ifc_req [index]; // Check interface flags bool is_valid = false; if (!ioctl (sock, SIOCGIFFLAGS, (caddr_t) ifr, sizeof (struct ifreq))) is_valid = s_valid_flags (ifr->ifr_flags); // Get interface properties inaddr_t address = { 0 }; if (!ioctl (sock, SIOCGIFADDR, (caddr_t) ifr, sizeof (struct ifreq))) address = *((inaddr_t *) &ifr->ifr_addr); else is_valid = false; inaddr_t broadcast = { 0 }; if (!ioctl (sock, SIOCGIFBRDADDR, (caddr_t) ifr, sizeof (struct ifreq))) broadcast = *((inaddr_t *) &ifr->ifr_addr); else is_valid = false; inaddr_t netmask = { 0 }; if (!ioctl (sock, SIOCGIFNETMASK, (caddr_t) ifr, sizeof (struct ifreq))) netmask = *((inaddr_t *) &ifr->ifr_addr); else is_valid = false; if (is_valid) { interface_t *item = s_interface_new (ifr->ifr_name, address, netmask, broadcast); if (item) zlistx_add_end (list, item); } } free (ifconfig.ifc_buf); close (sock); } # elif defined (__WINDOWS__) ULONG addr_size = 0; DWORD rc = GetAdaptersAddresses (AF_INET, GAA_FLAG_INCLUDE_PREFIX, NULL, NULL, &addr_size); assert (rc == ERROR_BUFFER_OVERFLOW); PIP_ADAPTER_ADDRESSES pip_addresses = (PIP_ADAPTER_ADDRESSES) zmalloc (addr_size); rc = GetAdaptersAddresses (AF_INET, GAA_FLAG_INCLUDE_PREFIX, NULL, pip_addresses, &addr_size); assert (rc == NO_ERROR); PIP_ADAPTER_ADDRESSES cur_address = pip_addresses; while (cur_address) { PIP_ADAPTER_UNICAST_ADDRESS pUnicast = cur_address->FirstUnicastAddress; PIP_ADAPTER_PREFIX pPrefix = cur_address->FirstPrefix; PWCHAR friendlyName = cur_address->FriendlyName; size_t asciiSize = wcstombs (0, friendlyName, 0) + 1; char *asciiFriendlyName = (char *) zmalloc (asciiSize); wcstombs (asciiFriendlyName, friendlyName, asciiSize); bool valid = (cur_address->OperStatus == IfOperStatusUp) && (pUnicast && pPrefix) && (pUnicast->Address.lpSockaddr->sa_family == AF_INET) && (pPrefix->PrefixLength <= 32); if (valid) { inaddr_t address = *(inaddr_t *) pUnicast->Address.lpSockaddr; inaddr_t netmask; netmask.sin_addr.s_addr = htonl ((0xffffffffU) << (32 - pPrefix->PrefixLength)); inaddr_t broadcast = address; broadcast.sin_addr.s_addr |= ~(netmask.sin_addr.s_addr); interface_t *item = s_interface_new (asciiFriendlyName, address, netmask, broadcast); if (item) zlistx_add_end (list, item); } free (asciiFriendlyName); cur_address = cur_address->Next; } free (pip_addresses); # else # error "Interface detection TBD on this operating system" # endif }
static int do_move(const char *cname, int argc, char **argv) { struct changer_move cmd; int val; /* * On a move command, we expect the following: * * <from ET> <from EU> <to ET> <to EU> [inv] * * where ET == element type and EU == element unit. */ ++argv; --argc; if (argc < 4) { warnx("%s: too few arguments", cname); goto usage; } else if (argc > 5) { warnx("%s: too many arguments", cname); goto usage; } (void) memset(&cmd, 0, sizeof(cmd)); /* <from ET> */ cmd.cm_fromtype = parse_element_type(*argv); ++argv; --argc; /* Check for voltag virtual type */ if (CHET_VT == cmd.cm_fromtype) { find_element(*argv, &cmd.cm_fromtype, &cmd.cm_fromunit); } else { /* <from EU> */ cmd.cm_fromunit = parse_element_unit(*argv); } ++argv; --argc; /* <to ET> */ cmd.cm_totype = parse_element_type(*argv); ++argv; --argc; /* Check for voltag virtual type, and report error */ if (CHET_VT == cmd.cm_totype) errx(1,"%s: voltag only makes sense as an element source", cname); /* <to EU> */ cmd.cm_tounit = parse_element_unit(*argv); ++argv; --argc; /* Deal with optional command modifier. */ if (argc) { val = parse_special(*argv); switch (val) { case SW_INVERT: cmd.cm_flags |= CM_INVERT; break; default: errx(1, "%s: inappropriate modifier `%s'", cname, *argv); /* NOTREACHED */ } } /* Send command to changer. */ if (ioctl(changer_fd, CHIOMOVE, &cmd)) err(1, "%s: CHIOMOVE", changer_name); return (0); usage: (void) fprintf(stderr, "usage: %s %s " "<from ET> <from EU> <to ET> <to EU> [inv]\n", getprogname(), cname); return (1); }
int main (int argc, char **argv) { int fd, rd, i, j, k; struct input_event ev[64]; int version; unsigned short id[4]; unsigned long bit[EV_MAX][NBITS(KEY_MAX)]; char name[256] = "Unknown"; int abs[5]; int counter = 0; int iterations = 0; if (argc < 3) { printf("Usage: evtest /dev/input/eventX <iterations>\n"); printf("Where X = input device number\n"); return 1; } fd = open(argv[argc - 2], O_RDONLY); if (fd < 0) { perror("evtest: cannot open node"); return 1; } iterations = atoi(argv[argc - 1]); printf("Number of iterations %d\n", iterations); if (iterations < 1) { perror("evtest: number of iterations shall be > 1\n"); return 1; } if (ioctl(fd, EVIOCGVERSION, &version)) { perror("evtest: can't get version"); return 1; } printf("Input driver version is %d.%d.%d\n", version >> 16, (version >> 8) & 0xff, version & 0xff); ioctl(fd, EVIOCGID, id); printf("Input device ID: bus 0x%x vendor 0x%x product 0x%x version 0x%x\n", id[ID_BUS], id[ID_VENDOR], id[ID_PRODUCT], id[ID_VERSION]); ioctl(fd, EVIOCGNAME(sizeof(name)), name); printf("Input device name: \"%s\"\n", name); memset(bit, 0, sizeof(bit)); ioctl(fd, EVIOCGBIT(0, EV_MAX), bit[0]); printf("Supported events:\n"); for (i = 0; i < EV_MAX; i++) if (test_bit(i, bit[0])) { printf(" Event type %d (%s)\n", i, events[i] ? events[i] : "?"); if (!i) continue; ioctl(fd, EVIOCGBIT(i, KEY_MAX), bit[i]); for (j = 0; j < KEY_MAX; j++) if (test_bit(j, bit[i])) { printf(" Event code %d (%s)\n", j, names[i] ? (names[i][j] ? names[i][j] : "?") : "?"); if (i == EV_ABS) { ioctl(fd, EVIOCGABS(j), abs); for (k = 0; k < 5; k++) if ((k < 3) || abs[k]) printf(" %s %6d\n", absval[k], abs[k]); } } } printf("Interacting %d times... (interrupt to exit)\n", iterations); while (counter < iterations) { printf("Info : %d of %d iterations\n", counter, iterations); rd = read(fd, ev, sizeof(struct input_event) * 64); if (rd < (int) sizeof(struct input_event)) { printf("yyy\n"); perror("\nevtest: error reading"); return 1; } for (i = 0; i < rd / sizeof(struct input_event); i++) if (ev[i].type == EV_SYN) { printf("Event: time %ld.%06ld, -------------- %s ------------\n", ev[i].time.tv_sec, ev[i].time.tv_usec, ev[i].code ? "Config Sync" : "Report Sync" ); } else if (ev[i].type == EV_MSC && ev[i].code == MSC_RAW) { printf("Event: time %ld.%06ld, type %d (%s), code %d (%s), value %02x\n", ev[i].time.tv_sec, ev[i].time.tv_usec, ev[i].type, events[ev[i].type] ? events[ev[i].type] : "?", ev[i].code, names[ev[i].type] ? (names[ev[i].type][ev[i].code] ? names[ev[i].type][ev[i].code] : "?") : "?", ev[i].value); } else { printf("Event: time %ld.%06ld, type %d (%s), code %d (%s), value %d\n", ev[i].time.tv_sec, ev[i].time.tv_usec, ev[i].type, events[ev[i].type] ? events[ev[i].type] : "?", ev[i].code, names[ev[i].type] ? (names[ev[i].type][ev[i].code] ? names[ev[i].type][ev[i].code] : "?") : "?", ev[i].value); } counter++; } return 0; }
static void handle_signal(int sig) { int serrno = errno; char signame[10] = { '\0' }; pid_t pid; RC_PID *pi; int status = 0; struct winsize ws; sigset_t sset; switch (sig) { case SIGCHLD: do { pid = waitpid(-1, &status, WNOHANG); if (pid < 0) { if (errno != ECHILD) eerror("waitpid: %s", strerror(errno)); return; } } while (!WIFEXITED(status) && !WIFSIGNALED(status)); /* Remove that pid from our list */ if (pid > 0) remove_pid(pid); break; case SIGWINCH: if (rc_logger_tty >= 0) { ioctl(STDIN_FILENO, TIOCGWINSZ, &ws); ioctl(rc_logger_tty, TIOCSWINSZ, &ws); } break; case SIGINT: if (!signame[0]) snprintf(signame, sizeof(signame), "SIGINT"); /* FALLTHROUGH */ case SIGTERM: if (!signame[0]) snprintf(signame, sizeof(signame), "SIGTERM"); /* FALLTHROUGH */ case SIGQUIT: if (!signame[0]) snprintf(signame, sizeof(signame), "SIGQUIT"); eerrorx("%s: caught %s, aborting", applet, signame); /* NOTREACHED */ case SIGUSR1: eerror("rc: Aborting!"); /* Block child signals */ sigemptyset(&sset); sigaddset(&sset, SIGCHLD); sigprocmask(SIG_BLOCK, &sset, NULL); /* Kill any running services we have started */ LIST_FOREACH(pi, &service_pids, entries) kill(pi->pid, SIGTERM); /* Notify plugins we are aborting */ rc_plugin_run(RC_HOOK_ABORT, NULL); exit(EXIT_FAILURE); /* NOTREACHED */ default: eerror("%s: caught unknown signal %d", applet, sig); } /* Restore errno */ errno = serrno; }
void quit(void) { fflush(stdout); ioctl(fileno(stdout), TIOCFLUSH, 0); error("Quit. "); }
/* * This function adds a journal inode to a filesystem, using either * POSIX routines if the filesystem is mounted, or using direct I/O * functions if it is not. */ errcode_t ext2fs_add_journal_inode(ext2_filsys fs, blk_t num_blocks, int flags) { errcode_t retval; ext2_ino_t journal_ino; struct stat st; char jfile[1024]; int mount_flags; int fd = -1; if (flags & EXT2_MKJOURNAL_NO_MNT_CHECK) mount_flags = 0; else if ((retval = ext2fs_check_mount_point(fs->device_name, &mount_flags, jfile, sizeof(jfile)-10))) return retval; if (mount_flags & EXT2_MF_MOUNTED) { #if HAVE_EXT2_IOCTLS int f = 0; #endif strcat(jfile, "/.journal"); /* * If .../.journal already exists, make sure any * immutable or append-only flags are cleared. */ #if defined(HAVE_CHFLAGS) && defined(UF_NODUMP) (void) chflags (jfile, 0); #else #if HAVE_EXT2_IOCTLS fd = open(jfile, O_RDONLY); if (fd >= 0) { ioctl(fd, EXT2_IOC_SETFLAGS, &f); close(fd); } #endif #endif /* Create the journal file */ if ((fd = open(jfile, O_CREAT|O_WRONLY, 0600)) < 0) return errno; /* Note that we can't do lazy journal initialization for mounted * filesystems, since the zero writing is also allocating the * journal blocks. We could use fallocate, but not all kernels * support that, and creating a journal on a mounted ext2 * filesystems is extremely rare these days... Ignore it. */ flags &= ~EXT2_MKJOURNAL_LAZYINIT; if ((retval = write_journal_file(fs, jfile, num_blocks, flags))) goto errout; /* Get inode number of the journal file */ if (fstat(fd, &st) < 0) { retval = errno; goto errout; } #if defined(HAVE_CHFLAGS) && defined(UF_NODUMP) retval = fchflags (fd, UF_NODUMP|UF_IMMUTABLE); #else #if HAVE_EXT2_IOCTLS if (ioctl(fd, EXT2_IOC_GETFLAGS, &f) < 0) { retval = errno; goto errout; } f |= EXT2_NODUMP_FL | EXT2_IMMUTABLE_FL; retval = ioctl(fd, EXT2_IOC_SETFLAGS, &f); #endif #endif if (retval) { retval = errno; goto errout; } if (close(fd) < 0) { retval = errno; fd = -1; goto errout; } journal_ino = st.st_ino; } else { if ((mount_flags & EXT2_MF_BUSY) && !(fs->flags & EXT2_FLAG_EXCLUSIVE)) { retval = EBUSY; goto errout; } journal_ino = EXT2_JOURNAL_INO; if ((retval = write_journal_inode(fs, journal_ino, num_blocks, flags))) return retval; } fs->super->s_journal_inum = journal_ino; fs->super->s_journal_dev = 0; memset(fs->super->s_journal_uuid, 0, sizeof(fs->super->s_journal_uuid)); fs->super->s_feature_compat |= EXT3_FEATURE_COMPAT_HAS_JOURNAL; ext2fs_mark_super_dirty(fs); return 0; errout: if (fd > 0) close(fd); return retval; }
/* * Write an image to NAND. This creates a FCB header and a DBBT (Discovered Bad * Block Table). The DBBT is initialized with the bad blocks known from the mtd * layer. */ static int imx_bbu_internal_v2_write_nand_dbbt(struct imx_internal_bbu_handler *imx_handler, struct bbu_data *data, void *image, int image_len) { struct mtd_info_user meminfo; int fd; struct stat s; int size_available, size_need; int ret; uint32_t *ptr, *num_bb, *bb; uint64_t offset; int block = 0, len, now, blocksize; ret = stat(data->devicefile, &s); if (ret) return ret; size_available = s.st_size; fd = open(data->devicefile, O_RDWR); if (fd < 0) return fd; ret = ioctl(fd, MEMGETINFO, &meminfo); if (ret) goto out; blocksize = meminfo.erasesize; ptr = image + 0x4; *ptr++ = FCB_MAGIC; /* FCB */ *ptr++ = 1; /* FCB version */ ptr = image + 0x78; /* DBBT start page */ *ptr = 4; ptr = image + 4 * 2048 + 4; *ptr++ = DBBT_MAGIC; /* DBBT */ *ptr = 1; /* DBBT version */ ptr = (u32*)(image + 0x2010); /* * This is marked as reserved in the i.MX53 reference manual, but * must be != 0. Otherwise the ROM ignores the DBBT */ *ptr = 1; ptr = (u32*)(image + 0x4004); /* start of DBBT */ num_bb = ptr; bb = ptr + 1; offset = 0; size_need = data->len + 0x8000; /* * Collect bad blocks and construct DBBT */ while (size_need > 0) { ret = ioctl(fd, MEMGETBADBLOCK, &offset); if (ret < 0) goto out; if (ret) { if (!offset) { printf("1st block is bad. This is not supported\n"); ret = -EINVAL; goto out; } debug("bad block at 0x%08llx\n", offset); *num_bb += 1; if (*num_bb == 425) { /* Maximum number of bad blocks the ROM supports */ printf("maximum number of bad blocks reached\n"); ret = -ENOSPC; goto out; } *bb++ = block; offset += blocksize; block++; continue; } size_need -= blocksize; size_available -= blocksize; offset += blocksize; block++; if (size_available < 0) { printf("device is too small"); ret = -ENOSPC; goto out; } } debug("total image size: 0x%08x. Space needed including bad blocks: 0x%08x\n", data->len + 0x8000, data->len + 0x8000 + *num_bb * blocksize); if (data->len + 0x8000 + *num_bb * blocksize > imx_handler->device_size) { printf("needed space (0x%08x) exceeds partition space (0x%08x)\n", data->len + 0x8000 + *num_bb * blocksize, imx_handler->device_size); ret = -ENOSPC; goto out; } len = data->len + 0x8000; offset = 0; /* * Write image to NAND skipping bad blocks */ while (len > 0) { now = min(len, blocksize); ret = ioctl(fd, MEMGETBADBLOCK, &offset); if (ret < 0) goto out; if (ret) { ret = lseek(fd, offset + blocksize, SEEK_SET); if (ret < 0) goto out; offset += blocksize; continue; } debug("writing %d bytes at 0x%08llx\n", now, offset); ret = erase(fd, blocksize, offset); if (ret) goto out; ret = write(fd, image, now); if (ret < 0) goto out; len -= now; image += now; offset += now; } ret = 0; out: close(fd); return ret; }
/** Basic setup to connect NIC to socket. * @param[in] port = port context struct * @param[in] ifname = Name of NIC device, f.e. "eth0" * @param[in] secondary = if >0 then use secondary stack instead of primary * @return >0 if succeeded */ int ecx_setupnic(ecx_portt *port, const char *ifname, int secondary) { int i; int r, rval, ifindex; struct timeval timeout; struct ifreq ifr; struct sockaddr_ll sll; int *psock; rval = 0; if (secondary) { /* secondary port stuct available? */ if (port->redport) { /* when using secondary socket it is automatically a redundant setup */ psock = &(port->redport->sockhandle); *psock = -1; port->redstate = ECT_RED_DOUBLE; port->redport->stack.sock = &(port->redport->sockhandle); port->redport->stack.txbuf = &(port->txbuf); port->redport->stack.txbuflength = &(port->txbuflength); port->redport->stack.tempbuf = &(port->redport->tempinbuf); port->redport->stack.rxbuf = &(port->redport->rxbuf); port->redport->stack.rxbufstat = &(port->redport->rxbufstat); port->redport->stack.rxsa = &(port->redport->rxsa); ecx_clear_rxbufstat(&(port->redport->rxbufstat[0])); } else { /* fail */ return 0; } } else { pthread_mutex_init(&(port->getindex_mutex), NULL); pthread_mutex_init(&(port->tx_mutex) , NULL); pthread_mutex_init(&(port->rx_mutex) , NULL); port->sockhandle = -1; port->lastidx = 0; port->redstate = ECT_RED_NONE; port->stack.sock = &(port->sockhandle); port->stack.txbuf = &(port->txbuf); port->stack.txbuflength = &(port->txbuflength); port->stack.tempbuf = &(port->tempinbuf); port->stack.rxbuf = &(port->rxbuf); port->stack.rxbufstat = &(port->rxbufstat); port->stack.rxsa = &(port->rxsa); ecx_clear_rxbufstat(&(port->rxbufstat[0])); psock = &(port->sockhandle); } /* we use RAW packet socket, with packet type ETH_P_ECAT */ *psock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ECAT)); timeout.tv_sec = 0; timeout.tv_usec = 1; r = setsockopt(*psock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); r = setsockopt(*psock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); i = 1; r = setsockopt(*psock, SOL_SOCKET, SO_DONTROUTE, &i, sizeof(i)); /* connect socket to NIC by name */ strcpy(ifr.ifr_name, ifname); r = ioctl(*psock, SIOCGIFINDEX, &ifr); ifindex = ifr.ifr_ifindex; strcpy(ifr.ifr_name, ifname); ifr.ifr_flags = 0; /* reset flags of NIC interface */ r = ioctl(*psock, SIOCGIFFLAGS, &ifr); /* set flags of NIC interface, here promiscuous and broadcast */ ifr.ifr_flags = ifr.ifr_flags | IFF_PROMISC | IFF_BROADCAST; r = ioctl(*psock, SIOCGIFFLAGS, &ifr); /* bind socket to protocol, in this case RAW EtherCAT */ sll.sll_family = AF_PACKET; sll.sll_ifindex = ifindex; sll.sll_protocol = htons(ETH_P_ECAT); r = bind(*psock, (struct sockaddr *)&sll, sizeof(sll)); /* setup ethernet headers in tx buffers so we don't have to repeat it */ for (i = 0; i < EC_MAXBUF; i++) { ec_setupheader(&(port->txbuf[i])); port->rxbufstat[i] = EC_BUF_EMPTY; } ec_setupheader(&(port->txbuf2)); if (r == 0) rval = 1; return rval; }
int ooSocketGetInterfaceList(OOCTXT *pctxt, OOInterface **ifList) { OOSOCKET sock; struct ifconf ifc; int ifNum; OOInterface *pIf=NULL; struct sockaddr_in sin; OOTRACEDBGA1("Retrieving local interfaces\n"); if(ooSocketCreateUDP(&sock)!= ASN_OK) { OOTRACEERR1("Error:Failed to create udp socket - " "ooSocketGetInterfaceList\n"); return -1; } #ifdef SIOCGIFNUM if(ioctl(sock, SIOCGIFNUM, &ifNum) >= 0) { OOTRACEERR1("Error: ioctl for ifNum failed\n"); return -1; } #else ifNum = 50; #endif ifc.ifc_len = ifNum * sizeof(struct ifreq); ifc.ifc_req = (struct ifreq *)memAlloc(pctxt, ifNum *sizeof(struct ifreq)); if(!ifc.ifc_req) { OOTRACEERR1("Error:Memory - ooSocketGetInterfaceList - ifc.ifc_req\n"); return -1; } if (ioctl(sock, SIOCGIFCONF, &ifc) >= 0) { void * ifEndList = (char *)ifc.ifc_req + ifc.ifc_len; struct ifreq *ifName; struct ifreq ifReq; int flags; for (ifName = ifc.ifc_req; (void*)ifName < ifEndList; ifName++) { char *pName=NULL; char addr[50]; #ifdef ifr_netmask char mask[50]; #endif pIf = (struct OOInterface*)memAlloc(pctxt, sizeof(struct OOInterface)); pName = (char*)memAlloc(pctxt, strlen(ifName->ifr_name)+1); if(!pIf) { OOTRACEERR1("Error:Memory - ooSocketGetInterfaceList - " "pIf/pName\n"); return -1; } OOTRACEDBGA2("\tInterface name: %s\n", ifName->ifr_name); strcpy(ifReq.ifr_name, ifName->ifr_name); strcpy(pName, ifName->ifr_name); pIf->name = pName; /* Check whether the interface is up*/ if (ioctl(sock, SIOCGIFFLAGS, &ifReq) < 0) { OOTRACEERR2("Error:Unable to determine status of interface %s\n", pName); memFreePtr(pctxt, pIf->name); memFreePtr(pctxt, pIf); continue; } flags = ifReq.ifr_flags; if (!(flags & IFF_UP)) { OOTRACEWARN2("Warn:Interface %s is not up\n", pName); memFreePtr(pctxt, pIf->name); memFreePtr(pctxt, pIf); continue; } /* Retrieve interface address */ if (ioctl(sock, SIOCGIFADDR, &ifReq) < 0) { OOTRACEWARN2("Warn:Unable to determine address of interface %s\n", pName); memFreePtr(pctxt, pIf->name); memFreePtr(pctxt, pIf); continue; } memcpy(&sin, &ifReq.ifr_addr, sizeof(struct sockaddr_in)); strcpy(addr, ast_inet_ntoa(sin.sin_addr)); OOTRACEDBGA2("\tIP address is %s\n", addr); pIf->addr = (char*)memAlloc(pctxt, strlen(addr)+1); if(!pIf->addr) { OOTRACEERR1("Error:Memory - ooSocketGetInterfaceList - " "pIf->addr\n"); memFreePtr(pctxt, pIf->name); memFreePtr(pctxt, pIf); return -1; } strcpy(pIf->addr, addr); #ifdef ifr_netmask if (ioctl(sock, SIOCGIFNETMASK, &ifReq) < 0) { OOTRACEWARN2("Warn:Unable to determine mask for interface %s\n", pName); memFreePtr(pctxt, pIf->name); memFreePtr(pctxt, pIf->addr); memFreePtr(pctxt, pIf); continue; } memcpy(&sin, &ifReq.ifr_netmask, sizeof(struct sockaddr_in)); strcpy(mask, ast_inet_ntoa(sin.sin_addr)); OOTRACEDBGA2("\tMask is %s\n", mask); pIf->mask = (char*)memAlloc(pctxt, strlen(mask)+1); if(!pIf->mask) { OOTRACEERR1("Error:Memory - ooSocketGetInterfaceList - " "pIf->mask\n"); memFreePtr(pctxt, pIf->name); memFreePtr(pctxt, pIf->addr); memFreePtr(pctxt, pIf); return -1; } strcpy(pIf->mask, mask); #endif pIf->next = NULL; /* Add to the list */ if(!*ifList) { *ifList = pIf; pIf = NULL; } else{ pIf->next = *ifList; *ifList = pIf; pIf=NULL; } /* #if defined(OO_FREEBSD) || defined(OO_OPENBSD) || defined(OO_NETBSD) || defined(OO_MACOSX) || defined(OO_VXWORKS) || defined(OO_RTEMS) || defined(OO_QNX) #ifndef _SIZEOF_ADDR_IFREQ #define _SIZEOF_ADDR_IFREQ(ifr) \ ((ifr).ifr_addr.sa_len > sizeof(struct sockaddr) ? \ (sizeof(struct ifreq) - sizeof(struct sockaddr) + \ (ifr).ifr_addr.sa_len) : sizeof(struct ifreq)) #endif ifName = (struct ifreq *)((char *)ifName + _SIZEOF_ADDR_IFREQ(*ifName)); #else ifName++; */ } } return ASN_OK; }
static int do_voltag(const char *cname, int argc, char **argv) { int force = 0; int clear = 0; int alternate = 0; int c; struct changer_set_voltag_request csvr; bzero(&csvr, sizeof(csvr)); optind = optreset = 1; while ((c = getopt(argc, argv, "fca")) != -1) { switch (c) { case 'f': force = 1; break; case 'c': clear = 1; break; case 'a': alternate = 1; break; default: warnx("%s: bad option", cname); goto usage; } } argc -= optind; argv += optind; if (argc < 2) { warnx("%s: missing element specification", cname); goto usage; } csvr.csvr_type = parse_element_type(argv[0]); csvr.csvr_addr = (u_int16_t)atol(argv[1]); if (!clear) { if (argc < 3 || argc > 4) { warnx("%s: missing argument", cname); goto usage; } if (force) csvr.csvr_flags = CSVR_MODE_REPLACE; else csvr.csvr_flags = CSVR_MODE_SET; if (strlen(argv[2]) > sizeof(csvr.csvr_voltag.cv_volid)) { warnx("%s: volume label too long", cname); goto usage; } strlcpy((char *)csvr.csvr_voltag.cv_volid, argv[2], sizeof(csvr.csvr_voltag.cv_volid)); if (argc == 4) { csvr.csvr_voltag.cv_serial = (u_int16_t)atol(argv[3]); } } else { if (argc != 2) { warnx("%s: unexpected argument", cname); goto usage; } csvr.csvr_flags = CSVR_MODE_CLEAR; } if (alternate) { csvr.csvr_flags |= CSVR_ALTERNATE; } if (ioctl(changer_fd, CHIOSETVOLTAG, &csvr)) err(1, "%s: CHIOSETVOLTAG", changer_name); return 0; usage: (void) fprintf(stderr, "usage: %s %s [-fca] <element> [<voltag> [<vsn>] ]\n", getprogname(), cname); return 1; }
/* * sscr_init -- * Create a pty setup for a shell. */ static int sscr_init(SCR *sp) { SCRIPT *sc; const char *sh, *sh_path; /* We're going to need a shell. */ if (opts_empty(sp, O_SHELL, 0)) return (1); MALLOC_RET(sp, sc, SCRIPT *, sizeof(SCRIPT)); sp->script = sc; sc->sh_prompt = NULL; sc->sh_prompt_len = 0; /* * There are two different processes running through this code. * They are the shell and the parent. */ sc->sh_master = sc->sh_slave = -1; if (tcgetattr(STDIN_FILENO, &sc->sh_term) == -1) { msgq(sp, M_SYSERR, "tcgetattr"); goto err; } /* * Turn off output postprocessing and echo. */ sc->sh_term.c_oflag &= ~OPOST; sc->sh_term.c_cflag &= ~(ECHO|ECHOE|ECHONL|ECHOK); #ifdef TIOCGWINSZ if (ioctl(STDIN_FILENO, TIOCGWINSZ, &sc->sh_win) == -1) { msgq(sp, M_SYSERR, "tcgetattr"); goto err; } if (sscr_pty(&sc->sh_master, &sc->sh_slave, sc->sh_name, &sc->sh_term, &sc->sh_win) == -1) { msgq(sp, M_SYSERR, "pty"); goto err; } #else if (sscr_pty(&sc->sh_master, &sc->sh_slave, sc->sh_name, &sc->sh_term, NULL) == -1) { msgq(sp, M_SYSERR, "pty"); goto err; } #endif /* * __TK__ huh? * Don't use vfork() here, because the signal semantics differ from * implementation to implementation. */ switch (sc->sh_pid = fork()) { case -1: /* Error. */ msgq(sp, M_SYSERR, "fork"); err: if (sc->sh_master != -1) (void)close(sc->sh_master); if (sc->sh_slave != -1) (void)close(sc->sh_slave); return (1); case 0: /* Utility. */ /* * XXX * So that shells that do command line editing turn it off. */ (void)setenv("TERM", "emacs", 1); (void)setenv("TERMCAP", "emacs:", 1); (void)setenv("EMACS", "t", 1); (void)setsid(); #ifdef TIOCSCTTY /* * 4.4BSD allocates a controlling terminal using the TIOCSCTTY * ioctl, not by opening a terminal device file. POSIX 1003.1 * doesn't define a portable way to do this. If TIOCSCTTY is * not available, hope that the open does it. */ (void)ioctl(sc->sh_slave, TIOCSCTTY, 0); #endif (void)close(sc->sh_master); (void)dup2(sc->sh_slave, STDIN_FILENO); (void)dup2(sc->sh_slave, STDOUT_FILENO); (void)dup2(sc->sh_slave, STDERR_FILENO); (void)close(sc->sh_slave); /* Assumes that all shells have -i. */ sh_path = O_STR(sp, O_SHELL); if ((sh = strrchr(sh_path, '/')) == NULL) sh = sh_path; else ++sh; execl(sh_path, sh, "-i", NULL); msgq_str(sp, M_SYSERR, sh_path, "execl: %s"); _exit(127); default: /* Parent. */ break; } if (sscr_getprompt(sp)) return (1); F_SET(sp, SC_SCRIPT); F_SET(sp->gp, G_SCRWIN); return (0); }
static int do_status(const char *cname, int argc, char **argv) { struct changer_params cp; struct changer_element_status_request cesr; int i; u_int16_t base, count, chet, schet, echet; const char *description; int pvoltag = 0; int avoltag = 0; int sense = 0; int scsi = 0; int source = 0; int intaddr = 0; int c; count = 0; base = 0; description = NULL; optind = optreset = 1; while ((c = getopt(argc, argv, "vVsSbaI")) != -1) { switch (c) { case 'v': pvoltag = 1; break; case 'V': avoltag = 1; break; case 's': sense = 1; break; case 'S': source = 1; break; case 'b': scsi = 1; break; case 'I': intaddr = 1; break; case 'a': pvoltag = avoltag = source = sense = scsi = intaddr = 1; break; default: warnx("%s: bad option", cname); goto usage; } } argc -= optind; argv += optind; /* * On a status command, we expect the following: * * [<ET> [<start> [<end>] ] ] * * where ET == element type, start == first element to report, * end == number of elements to report * * If we get no arguments, we get the status of all * known element types. */ if (argc > 3) { warnx("%s: too many arguments", cname); goto usage; } /* * Get params from changer. Specifically, we need the element * counts. */ if (ioctl(changer_fd, CHIOGPARAMS, (char *)&cp)) err(1, "%s: CHIOGPARAMS", changer_name); if (argc > 0) schet = echet = parse_element_type(argv[0]); else { schet = CHET_MT; echet = CHET_DT; } if (argc > 1) { base = (u_int16_t)atol(argv[1]); count = 1; } if (argc > 2) count = (u_int16_t)atol(argv[2]) - base + 1; for (chet = schet; chet <= echet; ++chet) { switch (chet) { case CHET_MT: if (count == 0) count = cp.cp_npickers; else if (count > cp.cp_npickers) errx(1, "not that many pickers in device"); description = "picker"; break; case CHET_ST: if (count == 0) count = cp.cp_nslots; else if (count > cp.cp_nslots) errx(1, "not that many slots in device"); description = "slot"; break; case CHET_IE: if (count == 0) count = cp.cp_nportals; else if (count > cp.cp_nportals) errx(1, "not that many portals in device"); description = "portal"; break; case CHET_DT: if (count == 0) count = cp.cp_ndrives; else if (count > cp.cp_ndrives) errx(1, "not that many drives in device"); description = "drive"; break; default: /* To appease gcc -Wuninitialized. */ count = 0; description = NULL; } if (count == 0) { if (argc == 0) continue; else { printf("%s: no %s elements\n", changer_name, description); return (0); } } bzero(&cesr, sizeof(cesr)); cesr.cesr_element_type = chet; cesr.cesr_element_base = base; cesr.cesr_element_count = count; /* Allocate storage for the status structures. */ cesr.cesr_element_status = (struct changer_element_status *) calloc((size_t)count, sizeof(struct changer_element_status)); if (!cesr.cesr_element_status) errx(1, "can't allocate status storage"); if (avoltag || pvoltag) cesr.cesr_flags |= CESR_VOLTAGS; if (ioctl(changer_fd, CHIOGSTATUS, (char *)&cesr)) { free(cesr.cesr_element_status); err(1, "%s: CHIOGSTATUS", changer_name); } /* Dump the status for each reported element. */ for (i = 0; i < count; ++i) { struct changer_element_status *ces = &(cesr.cesr_element_status[i]); printf("%s %d: %s", description, ces->ces_addr, bits_to_string(ces->ces_flags, CESTATUS_BITS)); if (sense) printf(" sense: <0x%02x/0x%02x>", ces->ces_sensecode, ces->ces_sensequal); if (pvoltag) printf(" voltag: <%s:%d>", ces->ces_pvoltag.cv_volid, ces->ces_pvoltag.cv_serial); if (avoltag) printf(" avoltag: <%s:%d>", ces->ces_avoltag.cv_volid, ces->ces_avoltag.cv_serial); if (source) { if (ces->ces_flags & CES_SOURCE_VALID) printf(" source: <%s %d>", element_type_name( ces->ces_source_type), ces->ces_source_addr); else printf(" source: <>"); } if (intaddr) printf(" intaddr: <%d>", ces->ces_int_addr); if (scsi) { printf(" scsi: <"); if (ces->ces_flags & CES_SCSIID_VALID) printf("%d", ces->ces_scsi_id); else putchar('?'); putchar(':'); if (ces->ces_flags & CES_LUN_VALID) printf("%d", ces->ces_scsi_lun); else putchar('?'); putchar('>'); } putchar('\n'); } free(cesr.cesr_element_status); count = 0; } return (0); usage: (void) fprintf(stderr, "usage: %s %s [-vVsSbaA] [<element type> [<start-addr> [<end-addr>] ] ]\n", getprogname(), cname); return (1); }
static int do_position(const char *cname, int argc, char **argv) { struct changer_position cmd; int val; /* * On a position command, we expect the following: * * <to ET> <to EU> [inv] * * where ET == element type and EU == element unit. */ ++argv; --argc; if (argc < 2) { warnx("%s: too few arguments", cname); goto usage; } else if (argc > 3) { warnx("%s: too many arguments", cname); goto usage; } (void) memset(&cmd, 0, sizeof(cmd)); /* <to ET> */ cmd.cp_type = parse_element_type(*argv); ++argv; --argc; /* <to EU> */ cmd.cp_unit = parse_element_unit(*argv); ++argv; --argc; /* Deal with optional command modifier. */ if (argc) { val = parse_special(*argv); switch (val) { case SW_INVERT: cmd.cp_flags |= CP_INVERT; break; default: errx(1, "%s: inappropriate modifier `%s'", cname, *argv); /* NOTREACHED */ } } /* Send command to changer. */ if (ioctl(changer_fd, CHIOPOSITION, &cmd)) err(1, "%s: CHIOPOSITION", changer_name); return (0); usage: (void) fprintf(stderr, "usage: %s %s <to ET> <to EU> [inv]\n", getprogname(), cname); return (1); }
static int do_exchange(const char *cname, int argc, char **argv) { struct changer_exchange cmd; int val; /* * On an exchange command, we expect the following: * * <src ET> <src EU> <dst1 ET> <dst1 EU> [<dst2 ET> <dst2 EU>] [inv1] [inv2] * * where ET == element type and EU == element unit. */ ++argv; --argc; if (argc < 4) { warnx("%s: too few arguments", cname); goto usage; } else if (argc > 8) { warnx("%s: too many arguments", cname); goto usage; } (void) memset(&cmd, 0, sizeof(cmd)); /* <src ET> */ cmd.ce_srctype = parse_element_type(*argv); ++argv; --argc; /* Check for voltag virtual type */ if (CHET_VT == cmd.ce_srctype) { find_element(*argv, &cmd.ce_srctype, &cmd.ce_srcunit); } else { /* <from EU> */ cmd.ce_srcunit = parse_element_unit(*argv); } ++argv; --argc; /* <dst1 ET> */ cmd.ce_fdsttype = parse_element_type(*argv); ++argv; --argc; /* Check for voltag virtual type */ if (CHET_VT == cmd.ce_fdsttype) { find_element(*argv, &cmd.ce_fdsttype, &cmd.ce_fdstunit); } else { /* <from EU> */ cmd.ce_fdstunit = parse_element_unit(*argv); } ++argv; --argc; /* * If the next token is a special word or there are no more * arguments, then this is a case of simple exchange. * dst2 == src. */ if ((argc == 0) || is_special(*argv)) { cmd.ce_sdsttype = cmd.ce_srctype; cmd.ce_sdstunit = cmd.ce_srcunit; goto do_special; } /* <dst2 ET> */ cmd.ce_sdsttype = parse_element_type(*argv); ++argv; --argc; if (CHET_VT == cmd.ce_sdsttype) errx(1,"%s %s: voltag only makes sense as an element source", cname, *argv); /* <dst2 EU> */ cmd.ce_sdstunit = parse_element_unit(*argv); ++argv; --argc; do_special: /* Deal with optional command modifiers. */ while (argc) { val = parse_special(*argv); ++argv; --argc; switch (val) { case SW_INVERT1: cmd.ce_flags |= CE_INVERT1; break; case SW_INVERT2: cmd.ce_flags |= CE_INVERT2; break; default: errx(1, "%s: inappropriate modifier `%s'", cname, *argv); /* NOTREACHED */ } } /* Send command to changer. */ if (ioctl(changer_fd, CHIOEXCHANGE, &cmd)) err(1, "%s: CHIOEXCHANGE", changer_name); return (0); usage: (void) fprintf(stderr, "usage: %s %s <src ET> <src EU> <dst1 ET> <dst1 EU>\n" " [<dst2 ET> <dst2 EU>] [inv1] [inv2]\n", getprogname(), cname); return (1); }
int run_once(struct xwii_iface *iface) { struct xwii_event event; int ret = 0; struct vt_stat vtstat; int vt = 0; int i; int console = 0; char *device = "/dev/console"; //char *device = "/dev/tty0"; console = open(device, O_RDWR); if (console < 0) { fprintf(stderr, "/dev/console problems. Do you have enough permission ?\n"); exit(3); } if ((ioctl(console, VT_GETSTATE, &vtstat) < 0) || vt == -1) { fprintf(stderr, "/dev/console problems. Do you have enough permission ?\n"); exit(3); } close(console); vt = vtstat.v_active; printf("Start vt %i.\n",vt); if (vt > 10) vt = 0; if (vt < 0) { printf("Error getting vt.\n"); return -1; } for (i=0; i<4; i++) { printf("Setting led %i to %i.\n", i+1, ledmap[vt][i]); ret = xwii_iface_set_led(iface, i+1, ledmap[vt][i]); if (ret) { printf("Error setting led %i to %i.\n", i+1, ledmap[vt][i]); return ret; } } while (true) { ret = xwii_iface_poll(iface, &event); if (ret == -EAGAIN) { usleep(50000); } else if (ret) { printf("Error: Read failed with err:%d\n", ret); return ret; } else if (event.type == XWII_EVENT_KEY && event.v.key.state) { console = open(device, O_RDWR); //got some errors when leaving console open over switches... if (console < 0) { fprintf(stderr, "/dev/console problems. Do you have enough permission ?\n"); exit(3); } if ((ioctl(console, VT_GETSTATE, &vtstat) < 0) || vt == -1) { fprintf(stderr, "/dev/console problems. Do you have enough permission ?\n"); exit(3); } else printf("old-vt %i. ",vt); vt = vtstat.v_active; switch (event.v.key.code) { case XWII_KEY_TWO: vt += 2; case XWII_KEY_ONE: vt -= 1; if (vt < 1) vt = 1; if (vt > 10) vt = 10; if (ioctl(console, VT_ACTIVATE, vt) != 0) { fprintf(stderr, "/dev/console problems. Do you have enough permission ?\n"); exit(3); } else printf("Switched to vt %i.\n",vt); for (i=0; i<4; i++) { ret = xwii_iface_set_led(iface, i+1, ledmap[vt][i]); if (ret) { printf("Error setting led %i to %i.\n", i+1, ledmap[vt][i]); return ret; } } break; default: continue; } close(console); } } return ret; }
static gint gst_imx_v4l2src_capture_setup(GstImxV4l2VideoSrc *v4l2src) { struct v4l2_format fmt = {0}; struct v4l2_streamparm parm = {0}; struct v4l2_frmsizeenum fszenum = {0}; v4l2_std_id id; gint input; gint fd_v4l; fd_v4l = open(v4l2src->devicename, O_RDWR, 0); if (fd_v4l < 0) { GST_ERROR_OBJECT(v4l2src, "Unable to open %s", v4l2src->devicename); return -1; } if (ioctl (fd_v4l, VIDIOC_G_STD, &id) < 0) { GST_WARNING_OBJECT(v4l2src, "VIDIOC_G_STD failed: %s", strerror(errno)); } else { if (ioctl (fd_v4l, VIDIOC_S_STD, &id) < 0) { GST_ERROR_OBJECT(v4l2src, "VIDIOC_S_STD failed"); close(fd_v4l); return -1; } } fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (ioctl(fd_v4l, VIDIOC_G_FMT, &fmt) < 0) { GST_ERROR_OBJECT(v4l2src, "VIDIOC_G_FMT failed"); close(fd_v4l); return -1; } GST_DEBUG_OBJECT(v4l2src, "pixelformat = %d field = %d", fmt.fmt.pix.pixelformat, fmt.fmt.pix.field); fszenum.index = v4l2src->capture_mode; fszenum.pixel_format = fmt.fmt.pix.pixelformat; if (ioctl(fd_v4l, VIDIOC_ENUM_FRAMESIZES, &fszenum) < 0) { GST_ERROR_OBJECT(v4l2src, "VIDIOC_ENUM_FRAMESIZES failed: %s", strerror(errno)); close(fd_v4l); return -1; } v4l2src->capture_width = fszenum.discrete.width; v4l2src->capture_height = fszenum.discrete.height; GST_INFO_OBJECT(v4l2src, "capture mode %d: %dx%d", v4l2src->capture_mode, v4l2src->capture_width, v4l2src->capture_height); input = v4l2src->input; if (ioctl(fd_v4l, VIDIOC_S_INPUT, &input) < 0) { GST_ERROR_OBJECT(v4l2src, "VIDIOC_S_INPUT failed: %s", strerror(errno)); close(fd_v4l); return -1; } parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; parm.parm.capture.timeperframe.numerator = v4l2src->fps_d; parm.parm.capture.timeperframe.denominator = v4l2src->fps_n; parm.parm.capture.capturemode = v4l2src->capture_mode; if (ioctl(fd_v4l, VIDIOC_S_PARM, &parm) < 0) { GST_ERROR_OBJECT(v4l2src, "VIDIOC_S_PARM failed: %s", strerror(errno)); close(fd_v4l); return -1; } /* Get the actual frame period if possible */ if (parm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) { v4l2src->fps_n = parm.parm.capture.timeperframe.denominator; v4l2src->fps_d = parm.parm.capture.timeperframe.numerator; } fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; fmt.fmt.pix.bytesperline = 0; fmt.fmt.pix.priv = 0; fmt.fmt.pix.sizeimage = 0; fmt.fmt.pix.width = v4l2src->capture_width; fmt.fmt.pix.height = v4l2src->capture_height; if (ioctl(fd_v4l, VIDIOC_S_FMT, &fmt) < 0) { GST_ERROR_OBJECT(v4l2src, "VIDIOC_S_FMT failed: %s", strerror(errno)); close(fd_v4l); return -1; } return fd_v4l; }
int data_on_connection(int fd, callback_remove_handler remove) { int nread; char *network_packet; char network_line[8192]; char *p; unsigned long id; char string[1024]; unsigned long msg_id = UINT32_MAX; int version; ioctl(fd, FIONREAD, &nread); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "new connection data = %d\n",nread); if(nread == 0) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, "%d failed, got 0 close connection to listener ", fd); close(fd); FD_CLR(fd, &readfds); remove(fd); network_client_dump (); return 0; } if ( nread >= 8192 ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, "%d failed, more than 8192 close connection to listener ", fd); close(fd); FD_CLR(fd, &readfds); remove(fd); return 0; } /* read the whole package */ network_packet=malloc((nread+1) * sizeof(char)); read(fd, network_packet, nread); network_packet[nread]='\0'; memset(network_line, 0, 8192); p=network_packet; p_sem(sem_id); while ( get_network_line(p, network_line) ) { if ( strlen(network_line) > 0 ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "line = [%s]",network_line); } if ( !strncmp(network_line, "MSGID: ", strlen("MSGID: ")) ) { /* read message id */ msg_id=strtoul(&(network_line[strlen("MSGID: ")]), NULL, 10); p+=strlen(network_line); } else if ( !strncmp(network_line, "Version: ", strlen("Version: ")) ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: VERSION"); id=strtoul(&(network_line[strlen("Version: ")]), NULL, 10); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "VERSION=%ld", id); if ( id < VERSION ) { network_client_set_version(fd, id); } else { network_client_set_version(fd, VERSION); } /* reset message id */ msg_id = UINT32_MAX; p+=strlen(network_line); } else if ( !strncmp(network_line, "Capabilities: ", strlen("Capabilities: ")) ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: Capabilities"); version=network_client_get_version(fd); if ( version > -1 ) { memset(string, 0, sizeof(string)); snprintf(string, sizeof(string), "Version: %d\nCapabilities: \n\n", version); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "SEND: %s", string); write(fd, string, strlen(string)); } else { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "Capabilities recv, but no version line"); } p+=strlen(network_line); } else if ( !strncmp(network_line, "GET_DN ", strlen("GET_DN ")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: GET_DN"); id=strtoul(&(network_line[strlen("GET_DN ")]), NULL, 10); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "id: %ld",id); if ( id <= notify_last_id.id) { char *dn_string = NULL; univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "try to read %ld from cache", id); /* try to read from cache */ if ( (dn_string = notifier_cache_get(id)) == NULL ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "%ld not found in cache", id); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "%ld get one dn", id); /* read from transaction file, because not in cache */ if( (dn_string=notify_transcation_get_one_dn ( id )) == NULL ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "%ld failed ", id); /* TODO: maybe close connection? */ univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, "%d failed, close connection to listener ", fd); close(fd); FD_CLR(fd, &readfds); remove(fd); return 0; } } if ( dn_string != NULL ) { snprintf(string, sizeof(string), "MSGID: %ld\n%s\n\n",msg_id,dn_string); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "--> %d: [%s]",fd, string); write(fd, string, strlen(string)); free(dn_string); } } else { /* set wanted id */ network_client_set_next_id(fd, id); network_client_set_msg_id(fd, msg_id); } p+=strlen(network_line)+1; msg_id = UINT32_MAX; } else if ( !strncmp(network_line, "GET_ID", strlen("GET_ID")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: GET_ID"); memset(string, 0, sizeof(string)); snprintf(string, sizeof(string), "MSGID: %ld\n%ld\n\n",msg_id,notify_last_id.id); write(fd, string, strlen(string)); p+=strlen(network_line)+1; msg_id = UINT32_MAX; } else if ( !strncmp(network_line, "GET_SCHEMA_ID", strlen("GET_SCHEMA_ID")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: GET_SCHEMA_ID"); memset(string, 0, sizeof(string)); snprintf(string, sizeof(string), "MSGID: %ld\n%ld\n\n",msg_id,SCHEMA_ID); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "--> %d: [%s]",fd, string); write(fd, string, strlen(string)); p+=strlen(network_line)+1; msg_id = UINT32_MAX; } else if ( !strncmp(network_line, "ALIVE", strlen("ALIVE")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: ALIVE"); snprintf(string, sizeof(string), "MSGID: %ld\nOKAY\n\n",msg_id); write(fd, string, strlen(string)); p+=strlen(network_line)+1; msg_id = UINT32_MAX; } else { p+=strlen(network_line); if (strlen(network_line) == 0 ) { p+=1; } else { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, "Drop package [%s]", network_line); } } } v_sem(sem_id); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "END Package"); network_client_dump (); return 0; }
static gboolean gst_imx_v4l2src_decide_allocation(GstBaseSrc *bsrc, GstQuery *query) { GstImxV4l2VideoSrc *v4l2src = GST_IMX_V4L2SRC(bsrc); struct v4l2_format fmt; GstBufferPool *pool; guint size, min, max; gboolean update; GstStructure *config; GstCaps *caps; gst_query_parse_allocation(query, &caps, NULL); /* Determine min and max */ if (gst_query_get_n_allocation_pools(query) > 0) { gst_query_parse_nth_allocation_pool(query, 0, NULL, NULL, &min, &max); update = TRUE; } else { min = max = 0; update = FALSE; } if (min != 0) /* Need an extra buffer to capture while other buffers * are downstream */ min += 1; else min = v4l2src->queue_size; fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (ioctl(GST_IMX_FD_OBJECT_GET_FD(v4l2src->fd_obj_v4l), VIDIOC_G_FMT, &fmt) < 0) { GST_ERROR_OBJECT(v4l2src, "VIDIOC_G_FMT failed"); return FALSE; } size = fmt.fmt.pix.sizeimage; /* no repooling; leads to stream off situation due to pool start/stop */ pool = gst_base_src_get_buffer_pool(bsrc); if (!pool) { pool = gst_imx_v4l2_buffer_pool_new(v4l2src->fd_obj_v4l, v4l2src->metaCropX, v4l2src->metaCropY, v4l2src->metaCropWidth, v4l2src->metaCropHeight); config = gst_buffer_pool_get_config(pool); gst_buffer_pool_config_set_params(config, caps, size, min, max); gst_buffer_pool_config_add_option(config, GST_BUFFER_POOL_OPTION_VIDEO_META); gst_buffer_pool_set_config(pool, config); } if (update) gst_query_set_nth_allocation_pool(query, 0, pool, size, min, max); else gst_query_add_allocation_pool(query, pool, size, min, max); gst_object_unref(pool); return TRUE; }
bool mdtSerialPortPosix::setAttributes(const QString &portName) { struct serial_struct serinfo; // Close previous opened port this->close(); // Clear previous attributes pvAvailableBaudRates.clear(); // Try to open port pvFd = ::open(portName.toStdString().c_str(), O_RDONLY | O_NOCTTY | O_NDELAY); if(pvFd < 0){ mdtError e(MDT_UNDEFINED_ERROR, "can not open port '" + portName + "'", mdtError::Error); e.setSystemError(errno, strerror(errno)); MDT_ERROR_SET_SRC(e, "mdtSerialPortPosix"); e.commit(); pvName = ""; return false; } // Set port name pvName = portName; // Set the UART type if(ioctl(pvFd, TIOCGSERIAL, &serinfo) < 0){ pvUartType = UT_UNKNOW; ::close(pvFd); return false; } // Map the type switch(serinfo.type){ case PORT_8250: pvUartType = UT_8250; case PORT_16450: pvUartType = UT_16450; break; case PORT_16550: pvUartType = UT_16550; break; case PORT_16550A: pvUartType = UT_16550A; break; case PORT_CIRRUS: pvUartType = UT_CIRRUS; break; case PORT_16650: pvUartType = UT_16650; break; case PORT_16650V2: pvUartType = UT_16650V2; break; case PORT_16750: pvUartType = UT_16750; break; case PORT_STARTECH: pvUartType = UT_STARTECH; break; case PORT_16C950: pvUartType = UT_16C950; break; case PORT_16654: pvUartType = UT_16654; break; case PORT_16850: pvUartType = UT_16850; break; case PORT_RSA: pvUartType = UT_RSA; break; default: pvUartType = UT_UNKNOW; ::close(pvFd); return false; } // Get available baud rates list pvAvailableBaudRates << 50; pvAvailableBaudRates << 75; pvAvailableBaudRates << 110; pvAvailableBaudRates << 134; // Note: is 134.5 pvAvailableBaudRates << 150; pvAvailableBaudRates << 200; pvAvailableBaudRates << 300; pvAvailableBaudRates << 600; pvAvailableBaudRates << 1200; pvAvailableBaudRates << 1800; pvAvailableBaudRates << 2400; pvAvailableBaudRates << 4800; pvAvailableBaudRates << 9600; pvAvailableBaudRates << 19200; pvAvailableBaudRates << 38400; #ifdef B57600 pvAvailableBaudRates << 57600; #endif #ifdef B76800 pvAvailableBaudRates << 76800; #endif #ifdef B115200 pvAvailableBaudRates << 115200; #endif #ifdef B230400 pvAvailableBaudRates << 230400; #endif #ifdef B460800 pvAvailableBaudRates << 460800; #endif #ifdef B500000 pvAvailableBaudRates << 500000; #endif #ifdef B576000 pvAvailableBaudRates << 576000; #endif #ifdef B921600 pvAvailableBaudRates << 921600; #endif #ifdef B1000000 pvAvailableBaudRates << 1000000; #endif #ifdef B1152000 pvAvailableBaudRates << 1152000; #endif #ifdef B1500000 pvAvailableBaudRates << 1500000; #endif #ifdef B2000000 pvAvailableBaudRates << 2000000; #endif #ifdef B2500000 pvAvailableBaudRates << 2500000; #endif #ifdef B3000000 pvAvailableBaudRates << 3000000; #endif #ifdef B3500000 pvAvailableBaudRates << 3500000; #endif #ifdef B4000000 pvAvailableBaudRates << 4000000; #endif // End of attributes, close port ::close(pvFd); return true; }
static int doread(int fd, FILE *of, const char *_devname) { char *trackbuf; int rv, fdopts, recoverable, nerrs = 0; unsigned int nbytes, tracksize, mediasize, secsize, n; struct fdc_status fdcs; struct fd_type fdt; if (ioctl(fd, FD_GTYPE, &fdt) == -1) err(EX_OSERR, "ioctl(FD_GTYPE) failed -- not a floppy?"); secsize = 128 << fdt.secsize; tracksize = fdt.sectrac * secsize; mediasize = tracksize * fdt.tracks * fdt.heads; if ((trackbuf = malloc(tracksize)) == NULL) errx(EX_TEMPFAIL, "out of memory"); if (!quiet) fprintf(stderr, "Reading %d * %d * %d * %d medium at %s\n", fdt.tracks, fdt.heads, fdt.sectrac, secsize, _devname); for (nbytes = 0; nbytes < mediasize;) { if (lseek(fd, nbytes, SEEK_SET) != nbytes) err(EX_OSERR, "cannot lseek()"); rv = read(fd, trackbuf, tracksize); if (rv == 0) { /* EOF? */ warnx("premature EOF after %u bytes", nbytes); return (EX_OK); } if ((unsigned)rv == tracksize) { nbytes += rv; if (!quiet) fprintf(stderr, "%5d KB\r", nbytes / 1024); fwrite(trackbuf, sizeof(unsigned char), rv, of); fflush(of); continue; } if (rv == -1) { /* fall back reading one sector at a time */ for (n = 0; n < tracksize; n += secsize) { if (lseek(fd, nbytes, SEEK_SET) != nbytes) err(EX_OSERR, "cannot lseek()"); rv = read(fd, trackbuf, secsize); if ((unsigned) rv == secsize) { nbytes += rv; if (!quiet) fprintf(stderr, "%5d KB\r", nbytes / 1024); fwrite(trackbuf, sizeof(unsigned char), rv, of); fflush(of); continue; } if (rv == -1) { if (errno != EIO) { if (!quiet) putc('\n', stderr); perror("non-IO error"); return (EX_OSERR); } if (ioctl(fd, FD_GSTAT, &fdcs) == -1) errx(EX_IOERR, "floppy IO error, but no FDC status"); nerrs++; recoverable = fdcs.status[2] & NE7_ST2_DD; if (!quiet) { printstatus(&fdcs, 0); fputs(" (", stderr); if (!recoverable) fputs("not ", stderr); fputs("recoverable)", stderr); } if (!recover) { if (!quiet) putc('\n', stderr); return (EX_IOERR); } memset(trackbuf, fillbyte, secsize); if (recoverable) { fdopts |= FDOPT_NOERROR; if (ioctl(fd, FD_SOPTS, &fdopts) == -1) err(EX_OSERR, "ioctl(fd, FD_SOPTS, FDOPT_NOERROR)"); rv = read(fd, trackbuf, secsize); if ((unsigned)rv != secsize) err(EX_IOERR, "read() with FDOPT_NOERROR still fails"); fdopts &= ~FDOPT_NOERROR; (void)ioctl(fd, FD_SOPTS, &fdopts); } if (!quiet) { if (recoverable) fprintf(stderr, ": recovered"); else fprintf(stderr, ": dummy"); fprintf(stderr, " data @ %#x ... %#x\n", nbytes, nbytes + secsize - 1); } nbytes += secsize; fwrite(trackbuf, sizeof(unsigned char), secsize, of); fflush(of); continue; } errx(EX_OSERR, "unexpected read() result: %d", rv); } } if ((unsigned)rv < tracksize) { /* should not happen */ nbytes += rv; if (!quiet) fprintf(stderr, "\nshort after %5d KB\r", nbytes / 1024); fwrite(trackbuf, sizeof(unsigned char), rv, of); fflush(of); continue; } } if (!quiet) { putc('\n', stderr); if (nerrs) fprintf(stderr, "%d error%s\n", nerrs, nerrs > 1? "s": ""); } return (nerrs? EX_IOERR: EX_OK); }
int main(int argc, char** argv) { char *fileName = NULL; int width = 0, height = 0; bool manual = false; bool random = true; int step = 50000; struct option long_options[] = { {"file", required_argument, 0, 'f'}, {"width", required_argument, 0, 'w'}, {"height", required_argument, 0, 'h'}, {"manual", optional_argument, 0, 'm'}, {"random", optional_argument, 0, 'r'}, {"step", required_argument, 0, 't'}, {NULL, 0, NULL, 0} }; int option_index = 0; int c; while ((c = getopt_long(argc, argv, "f:w:h:mrt:", long_options, &option_index)) != -1) { switch(c) { case 'f': fileName = optarg; break; case 'w': width = atoi(optarg); break; case 'h': height = atoi(optarg); break; case 'm': manual = true; break; case 'r': random = true; break; case 't': step = atoi(optarg) * 1000; break; } } if(width == 0 || height == 0) { struct winsize w; ioctl(0, TIOCGWINSZ, &w); if(width == 0) { width = w.ws_col - 2; } if(height == 0) { height = w.ws_row - 3; } } TheLife life(width, height); if(fileName) { FILE* f = fopen(fileName, "r"); if(f == NULL) { printf("Failed to open file"); return 1; } int x = 0, y = 0; char c; while(fscanf(f, "%c", &c) == 1) { if(c == '\n') { x = 0; y++; } if(c == '1') { life.setLive(x, y); } x++; } } else if(random) { life.generate(); } life.render(); while(1) { if(manual) { getchar(); } else { usleep(step); } life.step(); life.render(); } }
/** * Opens the DVB tuner */ dvb_device_t *dvb_open (vlc_object_t *obj) { dvb_device_t *d = malloc (sizeof (*d)); if (unlikely(d == NULL)) return NULL; d->obj = obj; uint8_t adapter = var_InheritInteger (obj, "dvb-adapter"); d->device = var_InheritInteger (obj, "dvb-device"); d->dir = dvb_open_adapter (adapter); if (d->dir == -1) { msg_Err (obj, "cannot access adapter %"PRIu8": %s", adapter, vlc_strerror_c(errno)); free (d); return NULL; } d->frontend = -1; d->cam = NULL; d->budget = var_InheritBool (obj, "dvb-budget-mode"); #ifndef USE_DMX if (d->budget) #endif { d->demux = dvb_open_node (d, "demux", O_RDONLY); if (d->demux == -1) { msg_Err (obj, "cannot access demultiplexer: %s", vlc_strerror_c(errno)); vlc_close (d->dir); free (d); return NULL; } if (ioctl (d->demux, DMX_SET_BUFFER_SIZE, 1 << 20) < 0) msg_Warn (obj, "cannot expand demultiplexing buffer: %s", vlc_strerror_c(errno)); /* We need to filter at least one PID. The tap for TS demultiplexing * cannot be configured otherwise. So add the PAT. */ struct dmx_pes_filter_params param; param.pid = d->budget ? 0x2000 : 0x000; param.input = DMX_IN_FRONTEND; param.output = DMX_OUT_TSDEMUX_TAP; param.pes_type = DMX_PES_OTHER; param.flags = DMX_IMMEDIATE_START; if (ioctl (d->demux, DMX_SET_PES_FILTER, ¶m) < 0) { msg_Err (obj, "cannot setup TS demultiplexer: %s", vlc_strerror_c(errno)); goto error; } #ifndef USE_DMX } else { for (size_t i = 0; i < MAX_PIDS; i++) d->pids[i].pid = d->pids[i].fd = -1; d->demux = dvb_open_node (d, "dvr", O_RDONLY); if (d->demux == -1) { msg_Err (obj, "cannot access DVR: %s", vlc_strerror_c(errno)); vlc_close (d->dir); free (d); return NULL; } #endif } int ca = dvb_open_node (d, "ca", O_RDWR); if (ca != -1) { d->cam = en50221_Init (obj, ca); if (d->cam == NULL) vlc_close (ca); } else msg_Dbg (obj, "conditional access module not available: %s", vlc_strerror_c(errno)); return d; error: dvb_close (d); return NULL; }
static void npfctl(int action, int argc, char **argv) { int fd, ret, ver, boolval; npf_ioctl_table_t tbl; char *arg; fd = open(NPF_DEV_PATH, O_RDONLY); if (fd == -1) { err(EXIT_FAILURE, "cannot open '%s'", NPF_DEV_PATH); } ret = ioctl(fd, IOC_NPF_VERSION, &ver); if (ver != NPF_VERSION) { errx(EXIT_FAILURE, "incompatible NPF interface version (%d, kernel %d)", NPF_VERSION, ver); } switch (action) { case NPFCTL_START: boolval = true; ret = ioctl(fd, IOC_NPF_SWITCH, &boolval); break; case NPFCTL_STOP: boolval = false; ret = ioctl(fd, IOC_NPF_SWITCH, &boolval); break; case NPFCTL_RELOAD: npfctl_init_data(); npfctl_parsecfg(argc < 3 ? NPF_CONF_PATH : argv[2]); ret = npfctl_ioctl_send(fd); break; case NPFCTL_FLUSH: /* Pass empty configuration to flush. */ npfctl_init_data(); ret = npfctl_ioctl_send(fd); if (ret) { break; } ret = npf_sessions_send(fd, NULL); break; case NPFCTL_TABLE: if (argc < 5) { usage(); } tbl.nct_tid = atoi(argv[2]); if (strcmp(argv[3], "add") == 0) { /* Add table entry. */ tbl.nct_action = NPF_IOCTL_TBLENT_ADD; arg = argv[4]; } else if (strcmp(argv[3], "rem") == 0) { /* Remove entry. */ tbl.nct_action = NPF_IOCTL_TBLENT_REM; arg = argv[4]; } else { /* Default: lookup. */ tbl.nct_action = 0; arg = argv[3]; } if (!npfctl_parse_cidr(arg, npfctl_get_addrfamily(arg), &tbl.nct_addr, &tbl.nct_mask)) { errx(EXIT_FAILURE, "invalid CIDR '%s'", arg); } ret = ioctl(fd, IOC_NPF_TABLE, &tbl); break; case NPFCTL_STATS: ret = npfctl_print_stats(fd); break; case NPFCTL_SESSIONS_SAVE: ret = npf_sessions_recv(fd, NPF_SESSDB_PATH); if (ret) { errx(EXIT_FAILURE, "could not save sessions to '%s'", NPF_SESSDB_PATH); } break; case NPFCTL_SESSIONS_LOAD: ret = npf_sessions_send(fd, NPF_SESSDB_PATH); if (ret) { errx(EXIT_FAILURE, "no sessions loaded from '%s'", NPF_SESSDB_PATH); } break; } if (ret) { err(EXIT_FAILURE, "ioctl"); } close(fd); }
/** * Reads TS data from the tuner. * @return number of bytes read, 0 on EOF, -1 if no data (yet). */ ssize_t dvb_read (dvb_device_t *d, void *buf, size_t len, int ms) { struct pollfd ufd[2]; int n; if (d->cam != NULL) en50221_Poll (d->cam); ufd[0].fd = d->demux; ufd[0].events = POLLIN; if (d->frontend != -1) { ufd[1].fd = d->frontend; ufd[1].events = POLLPRI; n = 2; } else n = 1; errno = 0; n = vlc_poll_i11e (ufd, n, ms); if (n == 0) errno = EAGAIN; if (n <= 0) return -1; if (d->frontend != -1 && ufd[1].revents) { struct dvb_frontend_event ev; if (ioctl (d->frontend, FE_GET_EVENT, &ev) < 0) { if (errno == EOVERFLOW) { msg_Err (d->obj, "cannot dequeue events fast enough!"); return -1; } msg_Err (d->obj, "cannot dequeue frontend event: %s", vlc_strerror_c(errno)); return 0; } dvb_frontend_status(d->obj, ev.status); } if (ufd[0].revents) { ssize_t val = read (d->demux, buf, len); if (val == -1 && (errno != EAGAIN && errno != EINTR)) { if (errno == EOVERFLOW) { msg_Err (d->obj, "cannot demux data fast enough!"); return -1; } msg_Err (d->obj, "cannot demux: %s", vlc_strerror_c(errno)); return 0; } return val; } return -1; }
int main(int argc, char **argv) { char *fn; int fd, err; struct ceph_ioctl_layout l; struct ceph_ioctl_dataloc dl; if (argc < 3) { printf("usage: ceph_test_ioctls <filename> <offset>\n"); return 1; } fn = argv[1]; fd = open(fn, O_CREAT|O_RDWR, 0644); if (fd < 0) { perror("couldn't open file"); return 1; } /* get layout */ err = ioctl(fd, CEPH_IOC_GET_LAYOUT, (unsigned long)&l); if (err < 0) { perror("ioctl IOC_GET_LAYOUT error"); return 1; } printf("layout:\n stripe_unit %lld\n stripe_count %lld\n object_size %lld\n data_pool %lld\n", (long long)l.stripe_unit, (long long)l.stripe_count, (long long)l.object_size, (long long)l.data_pool); /* set layout */ l.stripe_unit = 1048576; l.stripe_count = 2; err = ioctl(fd, CEPH_IOC_SET_LAYOUT, (unsigned long)&l); if (err < 0) { perror("ioctl IOC_SET_LAYOUT error"); return 1; } printf("set layout, writing to file\n"); printf("file %s\n", fn); /* get layout again */ err = ioctl(fd, CEPH_IOC_GET_LAYOUT, (unsigned long)&l); if (err < 0) { perror("ioctl IOC_GET_LAYOUT error"); return 1; } printf("layout:\n stripe_unit %lld\n stripe_count %lld\n object_size %lld\n data_pool %lld\n", (long long)l.stripe_unit, (long long)l.stripe_count, (long long)l.object_size, (long long)l.data_pool); /* dataloc */ dl.file_offset = atoll(argv[2]); err = ioctl(fd, CEPH_IOC_GET_DATALOC, (unsigned long)&dl); if (err < 0) { perror("ioctl IOC_GET_DATALOC error"); return 1; } printf("dataloc:\n"); printf(" file_offset %lld (of object start)\n", (long long)dl.file_offset); printf(" object '%s'\n object_offset %lld\n object_size %lld object_no %lld\n", dl.object_name, (long long)dl.object_offset, (long long)dl.object_size, (long long)dl.object_no); printf(" block_offset %lld\n block_size %lld\n", (long long)dl.block_offset, (long long)dl.block_size); char buf[80]; getnameinfo((struct sockaddr *)&dl.osd_addr, sizeof(dl.osd_addr), buf, sizeof(buf), 0, 0, NI_NUMERICHOST); printf(" osd%lld %s\n", (long long)dl.osd, buf); if (argc < 4) return 0; /* set dir default layout */ printf("testing dir policy setting\n"); fd = open(argv[3], O_RDONLY); if (fd < 0) { perror("couldn't open dir"); return 1; } l.object_size = 1048576; l.stripe_count = 1; err = ioctl(fd, CEPH_IOC_SET_LAYOUT_POLICY, (unsigned long)&l); if (err < 0) { perror("ioctl IOC_SET_LAYOUT_POLICY error"); return 1; } printf("set layout, creating file\n"); snprintf(new_file_name, sizeof(new_file_name), "%s/testfile", argv[3]); fd = open(new_file_name, O_CREAT | O_RDWR, 0644); if (fd < 0) { perror("couldn't open file"); return 1; } err = ioctl(fd, CEPH_IOC_GET_LAYOUT, (unsigned long)&l); if (err < 0) { perror("ioctl IOC_GET_LAYOUT error"); return 1; } printf("layout:\n stripe_unit %lld\n stripe_count %lld\n object_size %lld\n data_pool %lld\n", (long long)l.stripe_unit, (long long)l.stripe_count, (long long)l.object_size, (long long)l.data_pool); return 0; }
static int audio_open(AVFormatContext * s1, int is_output, const char *audio_device) { AudioData *s = s1->priv_data; int audio_fd; int tmp, err; char *flip = getenv("AUDIO_FLIP_LEFT"); if (is_output) audio_fd = avpriv_open(audio_device, O_WRONLY); else audio_fd = avpriv_open(audio_device, O_RDONLY); if (audio_fd < 0) { av_log(s1, AV_LOG_ERROR, "%s: %s\n", audio_device, strerror(errno)); return AVERROR(EIO); } if (flip && *flip == '1') { s->flip_left = 1; } /* non blocking mode */ if (!is_output) { if (fcntl(audio_fd, F_SETFL, O_NONBLOCK) < 0) { av_log(s1, AV_LOG_WARNING, "%s: Could not enable non block mode (%s)\n", audio_device, strerror(errno)); } } s->frame_size = AUDIO_BLOCK_SIZE; /* select format : favour native format */ err = ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &tmp); #if HAVE_BIGENDIAN if (tmp & AFMT_S16_BE) { tmp = AFMT_S16_BE; } else if (tmp & AFMT_S16_LE) { tmp = AFMT_S16_LE; } else { tmp = 0; } #else if (tmp & AFMT_S16_LE) { tmp = AFMT_S16_LE; } else if (tmp & AFMT_S16_BE) { tmp = AFMT_S16_BE; } else { tmp = 0; } #endif switch (tmp) { case AFMT_S16_LE: s->codec_id = AV_CODEC_ID_PCM_S16LE; break; case AFMT_S16_BE: s->codec_id = AV_CODEC_ID_PCM_S16BE; break; default: av_log(s1, AV_LOG_ERROR, "Soundcard does not support 16 bit sample format\n"); close(audio_fd); return AVERROR(EIO); } err = ioctl(audio_fd, SNDCTL_DSP_SETFMT, &tmp); if (err < 0) { av_log(s1, AV_LOG_ERROR, "SNDCTL_DSP_SETFMT: %s\n", strerror(errno)); goto fail; } tmp = (s->channels == 2); err = ioctl(audio_fd, SNDCTL_DSP_STEREO, &tmp); if (err < 0) { av_log(s1, AV_LOG_ERROR, "SNDCTL_DSP_STEREO: %s\n", strerror(errno)); goto fail; } tmp = s->sample_rate; err = ioctl(audio_fd, SNDCTL_DSP_SPEED, &tmp); if (err < 0) { av_log(s1, AV_LOG_ERROR, "SNDCTL_DSP_SPEED: %s\n", strerror(errno)); goto fail; } s->sample_rate = tmp; /* store real sample rate */ s->fd = audio_fd; return 0; fail: close(audio_fd); return AVERROR(EIO); }
static int DSP_OpenAudio(_THIS, SDL_AudioSpec *spec) { char audiodev[1024]; int format; int value; int frag_spec; Uint16 test_format; /* Open the audio device */ audio_fd = SDL_OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0); if ( audio_fd < 0 ) { SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); return(-1); } mixbuf = NULL; /* Make the file descriptor use blocking writes with fcntl() */ { long flags; flags = fcntl(audio_fd, F_GETFL); flags &= ~O_NONBLOCK; if ( fcntl(audio_fd, F_SETFL, flags) < 0 ) { SDL_SetError("Couldn't set audio blocking mode"); return(-1); } } /* Get a list of supported hardware formats */ if ( ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &value) < 0 ) { perror("SNDCTL_DSP_GETFMTS"); SDL_SetError("Couldn't get audio format list"); return(-1); } /* Try for a closest match on audio format */ format = 0; for ( test_format = SDL_FirstAudioFormat(spec->format); ! format && test_format; ) { #ifdef DEBUG_AUDIO fprintf(stderr, "Trying format 0x%4.4x\n", test_format); #endif switch ( test_format ) { case AUDIO_U8: if ( value & AFMT_U8 ) { format = AFMT_U8; } break; case AUDIO_S16LSB: if ( value & AFMT_S16_LE ) { format = AFMT_S16_LE; } break; case AUDIO_S16MSB: if ( value & AFMT_S16_BE ) { format = AFMT_S16_BE; } break; #if 0 /* * These formats are not used by any real life systems so they are not * needed here. */ case AUDIO_S8: if ( value & AFMT_S8 ) { format = AFMT_S8; } break; case AUDIO_U16LSB: if ( value & AFMT_U16_LE ) { format = AFMT_U16_LE; } break; case AUDIO_U16MSB: if ( value & AFMT_U16_BE ) { format = AFMT_U16_BE; } break; #endif default: format = 0; break; } if ( ! format ) { test_format = SDL_NextAudioFormat(); } } if ( format == 0 ) { SDL_SetError("Couldn't find any hardware audio formats"); return(-1); } spec->format = test_format; /* Set the audio format */ value = format; if ( (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) || (value != format) ) { perror("SNDCTL_DSP_SETFMT"); SDL_SetError("Couldn't set audio format"); return(-1); } /* Set the number of channels of output */ value = spec->channels; if ( ioctl(audio_fd, SNDCTL_DSP_CHANNELS, &value) < 0 ) { perror("SNDCTL_DSP_CHANNELS"); SDL_SetError("Cannot set the number of channels"); return(-1); } spec->channels = value; /* Set the DSP frequency */ value = spec->freq; if ( ioctl(audio_fd, SNDCTL_DSP_SPEED, &value) < 0 ) { perror("SNDCTL_DSP_SPEED"); SDL_SetError("Couldn't set audio frequency"); return(-1); } spec->freq = value; /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(spec); /* Determine the power of two of the fragment size */ for ( frag_spec = 0; (0x01<<frag_spec) < spec->size; ++frag_spec ); if ( (0x01<<frag_spec) != spec->size ) { SDL_SetError("Fragment size must be a power of two"); return(-1); } frag_spec |= 0x00020000; /* two fragments, for low latency */ /* Set the audio buffering parameters */ #ifdef DEBUG_AUDIO fprintf(stderr, "Requesting %d fragments of size %d\n", (frag_spec >> 16), 1<<(frag_spec&0xFFFF)); #endif if ( ioctl(audio_fd, SNDCTL_DSP_SETFRAGMENT, &frag_spec) < 0 ) { perror("SNDCTL_DSP_SETFRAGMENT"); fprintf(stderr, "Warning: Couldn't set audio fragment size\n"); } #ifdef DEBUG_AUDIO { audio_buf_info info; ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info); fprintf(stderr, "fragments = %d\n", info.fragments); fprintf(stderr, "fragstotal = %d\n", info.fragstotal); fprintf(stderr, "fragsize = %d\n", info.fragsize); fprintf(stderr, "bytes = %d\n", info.bytes); } #endif /* Allocate mixing buffer */ mixlen = spec->size; mixbuf = (Uint8 *)SDL_AllocAudioMem(mixlen); if ( mixbuf == NULL ) { return(-1); } memset(mixbuf, spec->silence, spec->size); /* Get the parent process id (we're the parent of the audio thread) */ parent = getpid(); /* We're ready to rock and roll. :-) */ return(0); }
/* ARGSUSED */ static void oob(int signo __unused) { struct termios tty; int atmark, n, rcvd; char waste[BUFSIZ], mark; rcvd = 0; while (recv(rem, &mark, 1, MSG_OOB) < 0) { switch (errno) { case EWOULDBLOCK: /* * Urgent data not here yet. It may not be possible * to send it yet if we are blocked for output and * our input buffer is full. */ if (rcvcnt < (int)sizeof(rcvbuf)) { n = read(rem, rcvbuf + rcvcnt, sizeof(rcvbuf) - rcvcnt); if (n <= 0) return; rcvd += n; } else { n = read(rem, waste, sizeof(waste)); if (n <= 0) return; } continue; default: return; } } if (mark & TIOCPKT_WINDOW) { /* Let server know about window size changes */ (void)kill(ppid, SIGUSR1); } if (!eight && (mark & TIOCPKT_NOSTOP)) { (void)tcgetattr(0, &tty); tty.c_iflag &= ~IXON; (void)tcsetattr(0, TCSANOW, &tty); } if (!eight && (mark & TIOCPKT_DOSTOP)) { (void)tcgetattr(0, &tty); tty.c_iflag |= (deftty.c_iflag & IXON); (void)tcsetattr(0, TCSANOW, &tty); } if (mark & TIOCPKT_FLUSHWRITE) { (void)tcflush(1, TCIOFLUSH); for (;;) { if (ioctl(rem, SIOCATMARK, &atmark) < 0) { warn("ioctl"); break; } if (atmark) break; n = read(rem, waste, sizeof (waste)); if (n <= 0) break; } /* * Don't want any pending data to be output, so clear the recv * buffer. If we were hanging on a write when interrupted, * don't want it to restart. If we were reading, restart * anyway. */ rcvcnt = 0; longjmp(rcvtop, 1); } /* oob does not do FLUSHREAD (alas!) */ /* * If we filled the receive buffer while a read was pending, longjmp * to the top to restart appropriately. Don't abort a pending write, * however, or we won't know how much was written. */ if (rcvd && rcvstate == READING) longjmp(rcvtop, 1); }
void* ServerRoutine ( void* Context ) { struct sockaddr_un addr; __int32_t lxBusFd, socketFd, clientFd, error; ADSS_BUS_CLIENT_CONNECT_SERVER_MSG connectMsg; size_t size; __uint8_t readBuffer[260]; __uint64_t tokenId; pid_t newPid; // // Get the ADSS file descriptor // lxBusFd = (__int32_t)(__int64_t)Context; // // Create a Unix domain socket // socketFd = socket(AF_UNIX, SOCK_STREAM, 0); if (socketFd < 0) { return NULL; } // // Unlink the socket if it already exists, so that we can recreate it // unlink("/tmp/lxexec-socket"); // // Bind it to the path that the lxexec binary looks for // memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, "/tmp/lxexec-socket", sizeof(addr.sun_path) - 1); error = bind(socketFd, (struct sockaddr*)&addr, sizeof(addr)); if (error == -1) { return NULL; } // // Make the socket RW by everyone // error = fchmod(socketFd, 777); if (error == -1) { return NULL; } // // Listen for new connections, with a backlog of 1 // error = listen(socketFd, 1); if (error == -1) { return NULL; } // // Sit in a loop accepting connections // while (1) { // // Accept the incoming connection // clientFd = accept(socketFd, NULL, NULL); if (clientFd == -1) { continue; } // // Read the input // memset(readBuffer, 0, sizeof(readBuffer)); size = read(clientFd, readBuffer, sizeof(readBuffer)); if (size <= 0) { close(clientFd); continue; } // // Connect to the "lxserver" server port // connectMsg.Timeout = 0xFFFFFFFF; connectMsg.ServerName = "lxserver"; connectMsg.Flags = ADSS_CONNECT_WAIT_FOR_SERVER_FLAG; error = ioctl(lxBusFd, IOCTL_ADSS_BUS_CLIENT_CONNECT_SERVER, &connectMsg); if (error != 0) { close(clientFd); continue; } // // Set the correct file descriptor mode for access // error = fcntl(connectMsg.ServerHandle, F_SETFD, O_WRONLY); if (error != 0) { close(connectMsg.ServerHandle); close(clientFd); continue; } // // Check if this is a token request // if (readBuffer[0] == '\0') { // // Pass it on // write(connectMsg.ServerHandle, readBuffer, size); // // Now read the reply // size = read(connectMsg.ServerHandle, &tokenId, sizeof(tokenId)); if (size <= 0) { close(connectMsg.ServerHandle); close(clientFd); continue; } // // Unmarshal the token // error = ioctl(connectMsg.ServerHandle, IOCTL_ADSS_IPC_CONNECTION_UNMARSHAL_FORK_TOKEN, &tokenId); if (error != 0) { close(connectMsg.ServerHandle); close(clientFd); continue; } // // Now fork a new process! // newPid = fork(); if (newPid == 0) { close(connectMsg.ServerHandle); close(clientFd); while (1) pause(); } } else { // // Now send the actual message // write(connectMsg.ServerHandle, readBuffer, size); } // // Cleanup the connection // close(connectMsg.ServerHandle); close(clientFd); } }
/* * find_element() * * Given a <voltag> find the chager element and unit, or exit * with an error if it isn't found. We grab the changer status * and iterate until we find a match, or crap out. */ static void find_element(char *voltag, uint16_t *et, uint16_t *eu) { struct changer_params cp; struct changer_element_status_request cesr; struct changer_element_status *ch_ces, *ces; int found = 0; size_t elem, total_elem; /* * Get the changer parameters, we're interested in the counts * for all types of elements to perform our search. */ if (ioctl(changer_fd, CHIOGPARAMS, (char *)&cp)) err(1, "%s: CHIOGPARAMS", changer_name); /* Allocate some memory for the results */ total_elem = (cp.cp_nslots + cp.cp_ndrives + cp.cp_npickers + cp.cp_nportals); ch_ces = (struct changer_element_status *) calloc(total_elem, sizeof(struct changer_element_status)); if (NULL == ch_ces) errx(1, "can't allocate status storage"); ces = ch_ces; /* Read in the changer slots */ if (cp.cp_nslots > 0) { (void) memset(&cesr, 0, sizeof(cesr)); cesr.cesr_element_type = CHET_ST; cesr.cesr_element_base = 0; cesr.cesr_element_count = cp.cp_nslots; cesr.cesr_flags |= CESR_VOLTAGS; cesr.cesr_element_status = ces; if (ioctl(changer_fd, CHIOGSTATUS, (char *)&cesr) == -1) { free(ch_ces); err(1, "%s: CHIOGSTATUS", changer_name); } ces += cp.cp_nslots; } /* Read in the drive information */ if (cp.cp_ndrives > 0 ) { (void) memset(&cesr, 0, sizeof(cesr)); cesr.cesr_element_type = CHET_DT; cesr.cesr_element_base = 0; cesr.cesr_element_count = cp.cp_ndrives; cesr.cesr_flags |= CESR_VOLTAGS; cesr.cesr_element_status = ces; if (ioctl(changer_fd, CHIOGSTATUS, (char *)&cesr) == -1) { free(ch_ces); err(1, "%s: CHIOGSTATUS", changer_name); } ces += cp.cp_ndrives; } /* Read in the portal information */ if (cp.cp_nportals > 0 ) { (void) memset(&cesr, 0, sizeof(cesr)); cesr.cesr_element_type = CHET_IE; cesr.cesr_element_base = 0; cesr.cesr_element_count = cp.cp_nportals; cesr.cesr_flags |= CESR_VOLTAGS; cesr.cesr_element_status = ces; if (ioctl(changer_fd, CHIOGSTATUS, (char *)&cesr) == -1) { free(ch_ces); err(1, "%s: CHIOGSTATUS", changer_name); } ces += cp.cp_nportals; } /* Read in the picker information */ if (cp.cp_npickers > 0) { (void) memset(&cesr, 0, sizeof(cesr)); cesr.cesr_element_type = CHET_MT; cesr.cesr_element_base = 0; cesr.cesr_element_count = cp.cp_npickers; cesr.cesr_flags |= CESR_VOLTAGS; cesr.cesr_element_status = ces; if (ioctl(changer_fd, CHIOGSTATUS, (char *)&cesr) == -1) { free(ch_ces); err(1, "%s: CHIOGSTATUS", changer_name); } } /* * Now search the list the specified <voltag> */ for (elem = 0; elem <= total_elem; ++elem) { ces = &ch_ces[elem]; /* Make sure we have a tape in this element */ if ((ces->ces_flags & (CES_STATUS_ACCESS|CES_STATUS_FULL)) != (CES_STATUS_ACCESS|CES_STATUS_FULL)) continue; /* Check to see if it is our target */ if (strcasecmp(voltag, (const char *)ces->ces_pvoltag.cv_volid) == 0) { *et = ces->ces_type; *eu = ces->ces_addr; ++found; break; } } if (!found) { errx(1, "%s: unable to locate voltag: %s", changer_name, voltag); } free(ch_ces); return; }