/* Since a socket endpoint is represented as a file descriptor, we can use * read() and write() to communicate with a socket, as long as it is * connected. Although we can exchange data using read() and write(), that * is about all we can do with these two functions. If we want to specify * options, receive packets from multiple clients, or send out-of-band data, * we need to use on of the six socket functions designed for data transfer. * * The simplest one is send(). It is similar to write(), but allows us to * specify flags to change how the data we want to transmit is treated. * #include <sys/socket.h> * ssize_t send(int sockfd, const void *buf, size_t nbytes, int flags); * Returns: number of bytes sent if OK, -1 on error * Like write(), the socket has to be connected to use send(). The buf and * nbytes arguments have the same meaning as they do with write(). * send()函数的flags可能取值为:MSG_DONTROUTE, MSG_DONTWAIT, MSG_EOR, MSG_OOB * * If send() returns success, it doesn't necessarily mean that the process * at the other end of the connection receives the data. All we are * guaranteed is that when send() succeeds, the data has been delivered to * the network drivers without error. * * With a protocol that supports message boundaries, if we try to send a * single message larger than the maximum supported by the protocol, send() * will fail with errno set to EMSGSIZE. With a byte-stream protocol, send() * will block until the entire amount of data has been transmitted. * * The sendto() function is similar to send(). The diffrence is that * sendto() allows us to specify a destination address to be used with * connectionless socket. * ssize_t sendto(int sockfd, const void *buf, size_t nbytes, int flags, * const struct sockaddr *destaddr, socklen_t destlen); * Returns: number of bytes sent if OK, -1 on error * With a connection-oriented socket, the destination address is ignored, as * the destination is implied by the connection. With a connectionless * socket, we can't use send() unless the destination address is first set * by calling connect(), so sendto() gives us an alternate way to send a * message. * * We have one more choice when transmitting data over a socket. We can call * sendmsg() with a msghdr structure to specify multiple buffers from which * to transmit data, similar to the writev() function. * ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags); * Returns: number of bytes sent if OK, -1 on error * 关于这个函数的其他信息可查看man手册. */ int main(void) { struct addrinfo *ailist, *aip; struct addrinfo hint; int sockfd, n, err; char *hostname; /* To find out its address, the server needs to get the name of the host on * which it is running. Some systems don't define the _SC_HOST_NAME_MAX * constant, so we use HOST_NAME_MAX in this case. If the system doesn't * define HOST_NAME_MAX, we define it ourselves. POSIX.1 states that the * minimum value for the host name is 255 bytes, not including the * terminating null, so we define HOST_NAME_MAX to be 256 to include the * terminating null. * man sysconf 中对 HOST_NAME_MAX, _SC_HOST_NAME_MAX 解释如下: * Max length of a hostname, not including the terminating null byte, as * returned by gethostname(). Must not be less than _POSIX_HOST_NAME_MAX * (255). */ #ifdef _SC_HOST_NAME_MAX n = sysconf(_SC_HOST_NAME_MAX); if (n < 0) #endif n = HOST_NAME_MAX; if ((hostname = malloc(n)) == NULL) { perror("malloc error"); exit(1); } if (gethostname(hostname, n) < 0) { perror("gethostname error"); exit(1); } daemonize("ruptimed"); hint.ai_flags = AI_CANONNAME; hint.ai_family = 0; hint.ai_socktype = SOCK_STREAM; /* 只获取tcp类型的服务 */ hint.ai_protocol = 0; hint.ai_addrlen = 0; hint.ai_addr = NULL; hint.ai_canonname = NULL; hint.ai_next = NULL; /* 注意, "ruptime" 服务并不是标准服务,系统中默认是没有这个服务的,运行 * 时,getaddrinfo()函数报错: Servname not supported for ai_socktype * 解决这个问题的方法是:将"ruptime"服务添加到/etc/services文件中,这样 * getaddrinfo()函数就能获取到该服务,不会再报错. */ if ((err = getaddrinfo(hostname, "ruptime", &hint, &ailist)) != 0) { syslog(LOG_ERR, "getaddrinfo error: %s\n", gai_strerror(err)); exit(1); } for (aip = ailist; aip != NULL; aip = aip->ai_next) { if ((sockfd = initserver(SOCK_STREAM, aip->ai_addr, aip->ai_addrlen, QLEN)) >= 0) { serve(sockfd); exit(0); } } exit(1); }
/* This creates a header by determining the hostname and reading the corresponding information out of the READOUT.conf file. */ _BOS_RCTR::_BOS_RCTR(u_int runNumber,u_int runExtNumber) : _BOS(*(u_int *)"RCTR",rctrRevNbr,0) { rctr = new RCTR_HEADER; rctr->streamNumber=0; rctr->numberOfModules=0; nextFile(runNumber,runExtNumber); // read number of streams GetDefaultUnsigned(rctr->totalNumberOfStreams,configFile,"numberOfStreams"); rctr->totalNumberOfChassis=rctr->totalNumberOfStreams; if (rctr->totalNumberOfChassis>MAXNumberOfStreams) { cout << "Too much streams !" << endl; return; } // determine hostname char chostname[100]; gethostname(chostname,100); char* point=strchr(chostname,'.'); // remove domain name if (point) *point=0; string thisHost = chostname; // read config data & try to determine streamNumber Config_V myConf[MAXNumberOfStreams]; // run configuration: detektor id, card, channel and settings for(unsigned int i = 0;i<rctr->totalNumberOfStreams;i++) { char streamHostStr[10]; sprintf(streamHostStr,"host%d",i+1); // string streamHostStr = form("host%d",i+1); string streamHost; GetDefaultString(streamHost,configFile,streamHostStr); myConf[i] = GetConfigVal(configFile,streamHost+":"); if (streamHost==thisHost) { if (myConf[i].size()>0) rctr->streamNumber=myConf[i][0].getStream(); else cout << "There is no configuration for this stream !" << endl; } } // determine # of modules (total) and # of ch per mod for (u_int s=0;s<rctr->totalNumberOfStreams;s++) { bool found; int curModules=0; // numberOfModules in stream s // look for the existence of modules with number 0..16 for (u_int module=0;module<=16;module++) { // module number to check for int curChNumber=0; // number of of channels in the current module found=false; // if module 'module' was found in the current stream for (u_int i=0;i<myConf[s].size();i++) { // look for the module in all channels of current stream if (myConf[s][i].getModule()==module) { curChNumber++; found=true; } // if myConf } // for i if (found) { numberOfChannels.push_back(curChNumber); curModules++; } }; if (s+1==rctr->streamNumber) rctr->numberOfModules=curModules; // in this file } // for s rctr->totalNumberOfModules=numberOfChannels.size(); //total in run rctr->numberOfChannels=(rctr->streamNumber>0) ? myConf[rctr->streamNumber-1].size() : 0; rctr->experiment = NTOF_as_int; bos->length=sizeof(RCTR_HEADER)/sizeof(int)+rctr->totalNumberOfModules; }
void ServerActivatorImpl::initialize() { try { CORBA::Object_var root_poa_obj = orb_->resolve_initial_references ("RootPOA"); root_poa_ = PortableServer::POA::_narrow (root_poa_obj); } catch (CORBA::ORB::InvalidName&) { std::cerr << "ServerActivatorImpl: Fatal error - no root POA available." << std::endl; throw CannotInitialize(); } catch (CORBA::SystemException&) { std::cerr << "ServerActivatorImpl: Fatal error - cannot narrow root POA." << std::endl; throw CannotInitialize(); } root_poa_manager_ = root_poa_->the_POAManager(); root_poa_manager_->activate(); CosNaming::NamingContext_var ns; // Now try to bind with the Name Service try { CORBA::Object_var ns_obj = orb_->resolve_initial_references ("NameService"); ns = CosNaming::NamingContext::_narrow (ns_obj); } catch (CORBA::ORB::InvalidName&) { std::cerr << "ServerActivatorImpl: Name Service not found" << std::endl; throw CannotInitialize(); } catch (CORBA::SystemException&) { std::cerr << "ServerActivatorImpl: Cannot narrow object reference of Name Service" << std::endl; throw CannotInitialize(); } if (CORBA::is_nil (ns)) { std::cerr << "ServerActivatorImpl: Name Service is nil" << std::endl; throw CannotInitialize(); } // Create the Qedo and Activators naming context CosNaming::Name current_name; current_name.length (1); current_name[0].id = CORBA::string_dup ("Qedo"); current_name[0].kind = CORBA::string_dup (""); try { ns->bind_new_context (current_name); } catch (CosNaming::NamingContext::AlreadyBound&) { // Ignore this exception } catch (CORBA::SystemException&) { std::cerr << "ServerActivatorImpl: CORBA system exception during binding context 'Qedo'" << std::endl; throw CannotInitialize(); } current_name.length(2); current_name[1].id = CORBA::string_dup ("Activators"); current_name[1].kind = CORBA::string_dup (""); try { ns->bind_new_context (current_name); } catch (CosNaming::NamingContext::AlreadyBound&) { // Ignore this exception } catch (CORBA::SystemException&) { std::cerr << "ServerActivatorImpl: CORBA system exception during binding context 'Activators'" << std::endl; throw CannotInitialize(); } // Now bind this Component Server Activator with the Name Service, use the name Qedo/Activators/<hostname> char hostname[256]; if (gethostname (hostname, 256)) { std::cerr << "ServerActivatorImpl: Cannot determine my hostname" << std::endl; throw CannotInitialize(); } std::cout << "ServerActivatorImpl: Binding Component Server Activator under Qedo/Activators/" << hostname << std::endl; current_name.length (3); current_name[2].id = CORBA::string_dup (hostname); current_name[2].kind = CORBA::string_dup (""); CORBA::Object_var my_ref = this->_this(); try { ns->bind (current_name, my_ref); } catch (CosNaming::NamingContext::AlreadyBound&) { try { ns->rebind (current_name, my_ref); } catch (CosNaming::NamingContext::InvalidName&) { std::cerr << "ServerActivatorImpl: Name Service complains about an invalid name" << std::endl; throw CannotInitialize(); } catch (CORBA::SystemException&) { std::cerr << "ServerActivatorImpl: CORBA system exception in rebind()" << std::endl; throw CannotInitialize(); } } catch (CosNaming::NamingContext::InvalidName&) { std::cerr << "ServerActivatorImpl: Name Service complains about an invalid name" << std::endl; throw CannotInitialize(); } catch (CORBA::SystemException&) { std::cerr << "ServerActivatorImpl: CORBA system exception during bind()" << std::endl; throw CannotInitialize(); } }
char * TRANS(GetMyNetworkId) (XtransConnInfo ciptr) { int family = ciptr->family; char *addr = ciptr->addr; char hostnamebuf[256]; char *networkId = NULL; char *transName = ciptr->transptr->TransName; if (gethostname (hostnamebuf, sizeof (hostnamebuf)) < 0) { return (NULL); } hostnamebuf[sizeof(hostnamebuf)-1] = '\0'; switch (family) { #if defined(UNIXCONN) || defined(STREAMSCONN) || defined(LOCALCONN) || defined(OS2PIPECONN) case AF_UNIX: { struct sockaddr_un *saddr = (struct sockaddr_un *) addr; networkId = (char *) xalloc (3 + strlen (transName) + strlen (hostnamebuf) + strlen (saddr->sun_path)); sprintf (networkId, "%s/%s:%s", transName, hostnamebuf, saddr->sun_path); break; } #endif /* defined(UNIXCONN) || defined(STREAMSCONN) || defined(LOCALCONN) || defined(OS2PIPECONN) */ #if defined(TCPCONN) || defined(STREAMSCONN) || defined(MNX_TCPCONN) case AF_INET: { struct sockaddr_in *saddr = (struct sockaddr_in *) addr; char portnumbuf[10]; sprintf (portnumbuf, "%d", ntohs (saddr->sin_port)); networkId = (char *) xalloc (3 + strlen (transName) + strlen (hostnamebuf) + strlen (portnumbuf)); sprintf (networkId, "%s/%s:%s", transName, hostnamebuf, portnumbuf); break; } #endif /* defined(TCPCONN) || defined(STREAMSCONN) || MNX_TCPCONN */ #if defined(DNETCONN) case AF_DECnet: { struct sockaddr_dn *saddr = (struct sockaddr_dn *) addr; networkId = (char *) xalloc ( 13 + strlen (hostnamebuf) + saddr->sdn_objnamel); sprintf (networkId, "dnet/%s::%s", hostnamebuf, saddr->sdn_objname); break; } #endif /* defined(DNETCONN) */ default: break; } return (networkId); }
static int setup_child(pid_t *pid, const char *term, const char *attr, char *const *argv) { int master; char ttyname[20]; DBUG_ENTER("setup_child"); switch ((*pid = pty_fork(&master, ttyname, 0, 0))) { case -1: DBUG_PRINT("startup", ("forkpty: failed")); DBUG_RETURN(-errno); /*NOTREACHED*/ case 0: { const char *shell; DBUG_PROCESS("child"); DBUG_PRINT("info", ("TERM=%s", term)); if (term) setenv("TERM", term, 1); DBUG_PRINT("info", ("attributes=%s", attr)); if (attr) init_pty(0, attr); if (!(shell = argv[0])) { char *s0; uid_t uid; struct passwd *pw; shell = "/bin/bash"; s0 = "-bash"; /* get user's login shell */ if (!(pw = getpwuid(uid = getuid()))) { DBUG_PRINT("error", ("getpwuid(%ld) failed: %s", uid, strerror(errno))); } else if (!(shell = pw->pw_shell) || *shell != '/') { DBUG_PRINT("error", ("bad shell for user id %ld", uid)); } else { DBUG_PRINT("info", ("got shell %s", shell)); s0 = strrchr(shell, '/'); s0 = str_dup(s0); assert(s0 != 0); s0[0] = '-'; } DBUG_PRINT("info", ("startup %s (%s)", shell, s0)); execl(shell, s0, (char *)0); } else { DBUG_PRINT("info", ("startup %s", *argv)); execvp(*argv, argv); } DBUG_PRINT("error", ("exec* failed: %s", strerror(errno))); perror(shell); exit(111); /*NOTREACHED*/ } default: { // Parent process. fcntl(master, F_SETFL, O_NONBLOCK); char *dev = ptsname(master); if (dev) { struct utmp ut; memset(&ut, 0, sizeof ut); if (!strncmp(dev, "/dev/", 5)) dev += 5; strlcpy(ut.ut_line, dev, sizeof ut.ut_line); if (dev[1] == 't' && dev[2] == 'y') dev += 3; if (!strncmp(dev, "pts/", 4)) dev += 4; strncpy(ut.ut_id, dev, sizeof ut.ut_id); ut.ut_type = USER_PROCESS; ut.ut_pid = (long int)*pid; ut.ut_time = time(0); strlcpy(ut.ut_user, getlogin() ?: "?", sizeof ut.ut_user); gethostname(ut.ut_host, sizeof ut.ut_host); login(&ut); } } } DBUG_PRINT("startup", ("forkpty:pid=%ld:master=%d:ttyname=%s", (long int)*pid, master, ttyname)); DBUG_RETURN(master); }
int main(int argc, char* argv[]) { int port; int expiration; char* targetURI; char* eventType; char* contentType; char* realm; char* user; char* password; // Initialize logging. OsSysLog::initialize(0, "test"); OsSysLog::setOutputFile(0, "log"); OsSysLog::setLoggingPriority(PRI_DEBUG); OsSysLog::setLoggingPriorityForFacility(FAC_SIP_INCOMING_PARSED, PRI_ERR); if (!parseArgs(argc, argv, &port, &expiration, &targetURI, &eventType, &contentType, &realm, &user, &password)) { usage(argv[0]); exit(1); } // The domain name to call myself, obtained from the gethostname() // system call. char buffer[100]; memset(buffer, 0, sizeof (buffer)); // Do not allow gethostname to write over the last NUL in buffer[]. gethostname(buffer, (sizeof (buffer)) - 1); UtlString myDomainName(buffer, strlen(buffer)); // Use "example.com" if gethostname() failed. if (myDomainName.isNull()) { myDomainName = "example.com"; } UtlString fromString = "sip:dialogwatch@" + myDomainName; Url fromUri(fromString, TRUE); // Create the SIP Subscribe Client SipLineMgr lineMgr; // Add credentials if they were specified. if (realm) { UtlString id; id += "sip:"; id += user; id += "@"; id += realm; Url identity(id, TRUE); SipLine line( fromUri // user entered url ,identity // identity url ,user // user ,TRUE // visible ,SipLine::LINE_STATE_PROVISIONED ,TRUE // auto enable ,FALSE // use call handling ); lineMgr.addLine(line); UtlString cred_input; UtlString cred_digest; cred_input.append(user); cred_input.append(":"); cred_input.append(realm); cred_input.append(":"); cred_input.append(password); NetMd5Codec::encode(cred_input.data(), cred_digest); fprintf(stderr, "Adding identity '%s': user='******' realm='%s' password='******' H(A1)='%s'\n", identity.toString().data(), user, realm, password, cred_digest.data() ); assert(lineMgr.addCredentialForLine(identity, realm, user, cred_digest, HTTP_DIGEST_AUTHENTICATION)); } SipUserAgent* pSipUserAgent = new SipUserAgent(port, port, PORT_NONE, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &lineMgr); // Add the 'eventlist' extension, so dialogwatch can subscribe to // event lists. pSipUserAgent->allowExtension("eventlist"); if (!pSipUserAgent->isOk()) { fprintf(stderr, "Unable to bind to port %d\n", port); exit(1); } SipDialogMgr dialogManager; SipRefreshManager refreshMgr(*pSipUserAgent, dialogManager); refreshMgr.start(); SipSubscribeClient sipSubscribeClient(*pSipUserAgent, dialogManager, refreshMgr); sipSubscribeClient.start(); // Construct a name-addr from targetURI, in case it contains parameters. UtlString toUri; toUri = "<"; toUri += targetURI; toUri += ">"; UtlString earlyDialogHandle; fprintf(stderr, "resourceId '%s' fromString '%s' toUri '%s' event '%s' content-type '%s' port=%d expiration=%d\n", targetURI, fromString.data(), toUri.data(), eventType, contentType, port, expiration); UtlBoolean status = sipSubscribeClient.addSubscription(targetURI, eventType, contentType, fromString.data(), toUri.data(), NULL, expiration, (void *) NULL, subscriptionStateCallback, notifyEventCallback, earlyDialogHandle); if (!status) { fprintf(stderr, "Subscription attempt failed.\n"); exit(1); } else { fprintf(stderr, "Subscription attempt succeeded. Handle: '%s'\n", earlyDialogHandle.data()); } while (1) { sleep(1000); } }
scap_t* scap_open_live(char *error) { #ifdef _WIN32 snprintf(error, SCAP_LASTERR_SIZE, "live capture not supported on windows"); return NULL; #elif defined(__APPLE__) snprintf(error, SCAP_LASTERR_SIZE, "live capture not supported on OSX"); return NULL; #else uint32_t j; char dev[255]; scap_t* handle = NULL; int len; uint32_t ndevs; uint32_t res; // // Allocate the handle // handle = (scap_t*)malloc(sizeof(scap_t)); if(!handle) { snprintf(error, SCAP_LASTERR_SIZE, "error allocating the scap_t structure"); return NULL; } // // Preliminary initializations // handle->m_ndevs = 0; handle->m_proclist = NULL; handle->m_file = NULL; handle->m_file_evt_buf = NULL; handle->m_evtcnt = 0; handle->m_addrlist = NULL; handle->m_userlist = NULL; handle->m_emptybuf_timeout_ms = BUFFER_EMPTY_WAIT_TIME_MS; // // Find out how many devices we have to open, which equals to the number of CPUs // ndevs = sysconf(_SC_NPROCESSORS_ONLN); // // Allocate the device descriptors. // len = RING_BUF_SIZE * 2; handle->m_devs = (scap_device*)malloc(ndevs * sizeof(scap_device)); if(!handle->m_devs) { scap_close(handle); snprintf(error, SCAP_LASTERR_SIZE, "error allocating the device handles"); return NULL; } // // Allocate the array of poll fds. // handle->m_pollfds = (struct pollfd*)malloc(ndevs * sizeof(struct pollfd)); if(!handle->m_pollfds) { scap_close(handle); snprintf(error, SCAP_LASTERR_SIZE, "error allocating the device handles"); return NULL; } for(j = 0; j < ndevs; j++) { handle->m_devs[j].m_buffer = (char*)MAP_FAILED; handle->m_devs[j].m_bufinfo = (struct ppm_ring_buffer_info*)MAP_FAILED; } handle->m_ndevs = ndevs; // // Extract machine information // handle->m_machine_info.num_cpus = sysconf(_SC_NPROCESSORS_ONLN); handle->m_machine_info.memory_size_bytes = (uint64_t)sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE); gethostname(handle->m_machine_info.hostname, sizeof(handle->m_machine_info.hostname) / sizeof(handle->m_machine_info.hostname[0])); handle->m_machine_info.reserved1 = 0; handle->m_machine_info.reserved2 = 0; handle->m_machine_info.reserved3 = 0; handle->m_machine_info.reserved4 = 0; // // Create the interface list // if(scap_create_iflist(handle) != SCAP_SUCCESS) { scap_close(handle); snprintf(error, SCAP_LASTERR_SIZE, "error creating the interface list"); return NULL; } // // Create the user list // if(scap_create_userlist(handle) != SCAP_SUCCESS) { scap_close(handle); snprintf(error, SCAP_LASTERR_SIZE, "error creating the interface list"); return NULL; } // // Create the process list // error[0] = '\0'; if((res = scap_proc_scan_proc_dir(handle, "/proc", -1, -1, NULL, error, true)) != SCAP_SUCCESS) { scap_close(handle); snprintf(error, SCAP_LASTERR_SIZE, "error creating the process list. Make sure you have root credentials."); return NULL; } handle->m_fake_kernel_proc.tid = -1; handle->m_fake_kernel_proc.pid = -1; handle->m_fake_kernel_proc.flags = 0; snprintf(handle->m_fake_kernel_proc.comm, SCAP_MAX_PATH_SIZE, "kernel"); snprintf(handle->m_fake_kernel_proc.exe, SCAP_MAX_PATH_SIZE, "kernel"); handle->m_fake_kernel_proc.args[0] = 0; // // Open and initialize all the devices // for(j = 0; j < handle->m_ndevs; j++) { // // Open the device // sprintf(dev, "/dev/sysdig%d", j); if((handle->m_devs[j].m_fd = open(dev, O_RDWR | O_SYNC)) < 0) { if(errno == EBUSY) { snprintf(error, SCAP_LASTERR_SIZE, "device %s is already open. You can't run multiple instances of sysdig.", dev); } else { snprintf(error, SCAP_LASTERR_SIZE, "error opening device %s. Make sure you have root credentials and that the sysdig-probe module is loaded.", dev); } scap_close(handle); return NULL; } // // Init the polling fd for the device // handle->m_pollfds[j].fd = handle->m_devs[j].m_fd; handle->m_pollfds[j].events = POLLIN; // // Map the ring buffer // handle->m_devs[j].m_buffer = (char*)mmap(0, len, PROT_READ, MAP_SHARED, handle->m_devs[j].m_fd, 0); if(handle->m_devs[j].m_buffer == MAP_FAILED) { // we cleanup this fd and then we let scap_close() take care of the other ones close(handle->m_devs[j].m_fd); scap_close(handle); snprintf(error, SCAP_LASTERR_SIZE, "error mapping the ring buffer for device %s", dev); return NULL; } // // Map the ppm_ring_buffer_info that contains the buffer pointers // handle->m_devs[j].m_bufinfo = (struct ppm_ring_buffer_info*)mmap(0, sizeof(struct ppm_ring_buffer_info), PROT_READ | PROT_WRITE, MAP_SHARED, handle->m_devs[j].m_fd, 0); if(handle->m_devs[j].m_bufinfo == MAP_FAILED) { // we cleanup this fd and then we let scap_close() take care of the other ones munmap(handle->m_devs[j].m_buffer, len); close(handle->m_devs[j].m_fd); scap_close(handle); snprintf(error, SCAP_LASTERR_SIZE, "error mapping the ring buffer info for device %s", dev); return NULL; } // // Additional initializations // handle->m_devs[j].m_lastreadsize = 0; handle->m_devs[j].m_sn_len = 0; scap_stop_dropping_mode(handle); } return handle; #endif // _WIN32 }
int condor_gethostname(char *name, size_t namelen) { if (nodns_enabled()) { char tmp[MAXHOSTNAMELEN]; char *param_buf; // First, we try NETWORK_INTERFACE if ( (param_buf = param( "NETWORK_INTERFACE" )) ) { char ip_str[MAXHOSTNAMELEN]; // reimplement with condor_sockaddr and to_ip_string() condor_sockaddr addr; dprintf( D_HOSTNAME, "NO_DNS: Using NETWORK_INTERFACE='%s' " "to determine hostname\n", param_buf ); snprintf( ip_str, MAXHOSTNAMELEN, "%s", param_buf ); free( param_buf ); if (!addr.from_ip_string(ip_str)) { dprintf(D_HOSTNAME, "NO_DNS: NETWORK_INTERFACE is invalid: %s\n", ip_str); return -1; } MyString hostname = convert_ipaddr_to_hostname(addr); if (hostname.Length() >= (int) namelen) { return -1; } strcpy(name, hostname.Value()); return 0; } // Second, we try COLLECTOR_HOST // To get the hostname with NODNS we are going to jump // through some hoops. We will try to make a UDP // connection to the COLLECTOR_HOST. This will result in not // only letting us call getsockname to find an IP for this // machine, but it will select the proper IP that we can // use to contact the COLLECTOR_HOST if ( (param_buf = param( "COLLECTOR_HOST" )) ) { //struct hostent *collector_ent; int s; //SOCKET_LENGTH_TYPE addr_len; char collector_host[MAXHOSTNAMELEN]; char *idx; //struct sockaddr_in addr, collector_addr; condor_sockaddr collector_addr; condor_sockaddr addr; std::vector<condor_sockaddr> collector_addrs; dprintf( D_HOSTNAME, "NO_DNS: Using COLLECTOR_HOST='%s' " "to determine hostname\n", param_buf ); // Get only the name portion of the COLLECTOR_HOST if ((idx = index(param_buf, ':'))) { *idx = '\0'; } snprintf( collector_host, MAXHOSTNAMELEN, "%s", param_buf ); free( param_buf ); // Now that we have the name we need an IP collector_addrs = resolve_hostname(collector_host); if (collector_addrs.empty()) { dprintf(D_HOSTNAME, "NO_DNS: Failed to get IP address of collector " "host '%s'\n", collector_host); return -1; } collector_addr = collector_addrs.front(); collector_addr.set_port(1980); // We are doing UDP, the benefit is connect will not send // any network traffic on a UDP socket if (-1 == (s = socket(collector_addr.get_aftype(), SOCK_DGRAM, 0))) { dprintf(D_HOSTNAME, "NO_DNS: Failed to create socket, errno=%d (%s)\n", errno, strerror(errno)); return -1; } if (condor_connect(s, collector_addr)) { close(s); dprintf(D_HOSTNAME, "NO_DNS: Failed to bind socket, errno=%d (%s)\n", errno, strerror(errno)); return -1; } if (condor_getsockname(s, addr)) { close(s); dprintf(D_HOSTNAME, "NO_DNS: Failed to get socket name, errno=%d (%s)\n", errno, strerror(errno)); return -1; } close(s); MyString hostname = convert_ipaddr_to_hostname(addr); if (hostname.Length() >= (int) namelen) { return -1; } strcpy(name, hostname.Value()); return 0; } // Last, we try gethostname() if ( gethostname( tmp, MAXHOSTNAMELEN ) == 0 ) { dprintf( D_HOSTNAME, "NO_DNS: Using gethostname()='%s' " "to determine hostname\n", tmp ); std::vector<condor_sockaddr> addrs; MyString my_hostname(tmp); addrs = resolve_hostname_raw(my_hostname); if (addrs.empty()) { dprintf(D_HOSTNAME, "NO_DNS: resolve_hostname_raw() failed, errno=%d" " (%s)\n", errno, strerror(errno)); return -1; } MyString hostname = convert_ipaddr_to_hostname(addrs.front()); if (hostname.Length() >= (int) namelen) { return -1; } strcpy(name, hostname.Value()); return 0; } dprintf(D_HOSTNAME, "Failed in determining hostname for this machine\n"); return -1; } else { return gethostname(name, namelen); } }
main(int argc, char *argv[]) { char localmachine[256]; cache_inode_client_t client; LRU_parameter_t lru_param; LRU_status_t lru_status; cache_inode_fsal_data_t fsdata; fsal_status_t status; fsal_parameter_t init_param; fsal_name_t name; fsal_path_t path; fsal_attrib_mask_t mask; fsal_path_t pathroot; fsal_attrib_list_t attribs; fsal_handle_t root_handle; cache_inode_endofdir_t eod_met; cache_inode_dir_entry_t dirent_array[100]; cache_inode_dir_entry_t dirent_array_loop[5]; unsigned int nbfound; unsigned int begin_cookie = 0; hash_buffer_t key, value; uid_t uid; fsal_cred_t cred; cache_inode_status_t cache_status; cache_inode_parameter_t cache_param; cache_inode_client_parameter_t cache_client_param; hash_table_t *ht = NULL; fsal_attrib_list_t attrlookup; cache_entry_t *cache_entry_root = NULL; cache_entry_t *cache_entry_lookup = NULL; cache_entry_t *cache_entry_lookup2 = NULL; cache_entry_t *cache_entry_lookup3 = NULL; cache_entry_t *cache_entry_lookup4 = NULL; cache_entry_t *cache_entry_dircont = NULL; cache_inode_gc_policy_t gcpol; char *configfile = argv[1]; int i = 0; int rc = 0; /* Init the Buddy System allocation */ if((rc = BuddyInit(NULL)) != BUDDY_SUCCESS) { LogTest("Error initializing memory allocator"); exit(1); } /* init debug */ SetDefaultLogging("TEST"); SetNamePgm("test_cache_inode"); SetNameFunction("main"); InitLogging(); #if defined( _USE_GHOSTFS ) if(argc != 2) { LogTest("Please set the configuration file as parameter"); exit(1); } #endif /* Obtention du nom de la machine */ if(gethostname(localmachine, sizeof(localmachine)) != 0) { LogError(COMPONENT_STDOUT,ERR_SYS, ERR_GETHOSTNAME, errno); exit(1); } else SetNameHost(localmachine); AddFamilyError(ERR_FSAL, "FSAL related Errors", tab_errstatus_FSAL); AddFamilyError(ERR_CACHE_INODE, "FSAL related Errors", tab_errstatus_cache_inode); /* creating log */ LogTest( "Starting the test"); LogTest( "-----------------"); #if defined( _USE_GHOSTFS ) if(FSAL_IS_ERROR(status = FSAL_str2path(configfile, strlen(configfile) + 1, &(init_param.fs_specific_info. definition_file)))) { LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor); } #elif defined( _USE_HPSS ) FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, Flags); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, DebugValue); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, TransferType); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, NumRetries); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, BusyDelay); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, BusyRetries); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, TotalDelay); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, GKTotalDelay); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, LimitedRetries); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, MaxConnections); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, ReuseDataConnections); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, UsePortRange); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, RetryStageInp); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, DMAPWriteUpdates); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, ServerName); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, DescName); init_param.fs_specific_info.behaviors.PrincipalName = FSAL_INIT_FORCE_VALUE; strncpy(init_param.fs_specific_info.hpss_config.PrincipalName, HPSS_SSM, HPSS_MAX_PRINCIPAL_NAME); init_param.fs_specific_info.behaviors.KeytabPath = FSAL_INIT_FORCE_VALUE; strncpy(init_param.fs_specific_info.hpss_config.KeytabPath, HPSS_KEYTAB, HPSS_MAX_PATH_NAME); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, DebugPath); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, HostName); FSAL_SET_INIT_DEFAULT(init_param.fs_specific_info, RegistrySiteName); #endif /* 2-common info (default) */ FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxfilesize); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxlink); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxnamelen); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxpathlen); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, no_trunc); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, chown_restricted); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, case_insensitive); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, case_preserving); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, fh_expire_type); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, link_support); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, symlink_support); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, named_attr); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, unique_handles); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, lease_time); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, acl_support); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, cansettime); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, homogenous); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxread); FSAL_SET_INIT_DEFAULT(init_param.fs_common_info, maxwrite); /* Init */ if(FSAL_IS_ERROR(status = FSAL_Init(&init_param))) { LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor); } /* getting creds */ uid = getuid(); if(FSAL_IS_ERROR(status = FSAL_GetUserCred(uid, NULL, &cred))) { LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor); } /* Init of the cache inode module */ cache_param.hparam.index_size = 31; cache_param.hparam.alphabet_length = 10; /* Buffer seen as a decimal polynom */ cache_param.hparam.nb_node_prealloc = 100; cache_param.hparam.hash_func_key = cache_inode_fsal_hash_func; cache_param.hparam.hash_func_rbt = cache_inode_fsal_rbt_func; cache_param.hparam.hash_func_both = NULL ; /* BUGAZOMEU */ cache_param.hparam.compare_key = cache_inode_compare_key_fsal; cache_param.hparam.key_to_str = display_key; cache_param.hparam.val_to_str = display_value; if((ht = cache_inode_init(cache_param, &cache_status)) == NULL) { LogTest( "Error %d while init hash ", cache_status); } else LogTest( "Hash Table address = %p", ht); /* We need a cache_client to acces the cache */ cache_client_param.attrmask = FSAL_ATTRS_MANDATORY | FSAL_ATTR_MTIME | FSAL_ATTR_CTIME | FSAL_ATTR_ATIME; cache_client_param.nb_prealloc_entry = 1000; cache_client_param.nb_pre_dir_data = 200; cache_client_param.nb_pre_parent = 1200; cache_client_param.nb_pre_state_v4 = 100; cache_client_param.lru_param.nb_entry_prealloc = 1000; cache_client_param.lru_param.entry_to_str = lru_entry_to_str; cache_client_param.lru_param.clean_entry = lru_clean_entry; cache_client_param.grace_period_attr = 0; cache_client_param.grace_period_link = 0; cache_client_param.grace_period_dirent = 0; cache_client_param.expire_type_attr = CACHE_INODE_EXPIRE_NEVER; cache_client_param.expire_type_link = CACHE_INODE_EXPIRE_NEVER; cache_client_param.expire_type_dirent = CACHE_INODE_EXPIRE_NEVER; /* Init the cache_inode client */ if(cache_inode_client_init(&client, &cache_client_param, 0, NULL) != 0) exit(1); /* Init the gc */ gcpol.file_expiration_delay = 3; gcpol.directory_expiration_delay = 4; gcpol.hwmark_nb_entries = 6; gcpol.lwmark_nb_entries = 3; gcpol.run_interval = 4; cache_inode_set_gc_policy(gcpol); /* Getting the root of the FS */ if((FSAL_IS_ERROR(status = FSAL_str2path("/", 2, &pathroot)))) { LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor); exit(1); } if((FSAL_IS_ERROR(status = FSAL_lookupPath(&pathroot, &cred, &root_handle, &attribs)))) { LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor); exit(1); } fsdata.cookie = 0; fsdata.handle = root_handle; /* Cache the root of the FS */ if((cache_entry_root = cache_inode_make_root(&fsdata, 1, ht, &client, &cred, &cache_status)) == NULL) { LogTest( "Error: can't init fs's root"); exit(1); } /* A lookup in the root fsal */ if((FSAL_IS_ERROR(status = FSAL_str2name("cea", 10, &name)))) { LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor); exit(1); } if((cache_entry_lookup = cache_inode_lookup(cache_entry_root, &name, &attrlookup, ht, &client, &cred, &cache_status)) == NULL) { LogTest( "Error: can't lookup"); exit(1); } /* Lookup a second time (entry should now be cached) */ if((cache_entry_lookup2 = cache_inode_lookup(cache_entry_root, &name, &attrlookup, ht, &client, &cred, &cache_status)) == NULL) { LogTest( "Error: can't lookup"); exit(1); } if(cache_entry_lookup2 != cache_entry_lookup) { LogTest("Error: lookup results should be the same"); exit(1); } /* A lookup in the root fsal */ if((FSAL_IS_ERROR(status = FSAL_str2name("log", 10, &name)))) { LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor); exit(1); } if((cache_entry_lookup3 = cache_inode_lookup(cache_entry_root, &name, &attrlookup, ht, &client, &cred, &cache_status)) == NULL) { LogTest( "Error: can't lookup"); exit(1); } if((cache_entry_lookup4 = cache_inode_lookup(cache_entry_root, &name, &attrlookup, ht, &client, &cred, &cache_status)) == NULL) { LogTest( "Error: can't lookup"); exit(1); } if(cache_entry_lookup3 != cache_entry_lookup4) { LogTest("Error: lookup results should be the same"); exit(1); } /* A lookup in the root fsal */ if((FSAL_IS_ERROR(status = FSAL_str2name("SunOS_5", 10, &name)))) { LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor); exit(1); } cache_inode_print_dir(cache_entry_root); /* Test readdir */ if(cache_inode_readdir(cache_entry_root, 0, 100, &nbfound, &eod_met, dirent_array, ht, &client, &cred, &cache_status) != CACHE_INODE_SUCCESS) { LogTest( "Error: cache_inode_readdir failed"); exit(1); } LogTest( "Readdir nbfound=%d, eod_met=%d", nbfound, eod_met); for(i = 0; i < nbfound; i++) LogTest( "dirent_array[%d] ==> %s | %p", i, dirent_array[i].name.name, dirent_array[i].pentry); cache_inode_print_dir(cache_entry_root); /* looping on readir */ LogTest( "Loop directory in several pass"); eod_met = TO_BE_CONTINUED; begin_cookie = 0; do { if(cache_inode_readdir(cache_entry_root, begin_cookie, 2, &nbfound, &eod_met, dirent_array_loop, ht, &client, &cred, &cache_status) != CACHE_INODE_SUCCESS) { LogTest("Error: cache_inode_readdir failed: %d", cache_status); exit(1); } for(i = 0; i < nbfound; i++) LogTest( " ==> %s | %p", dirent_array_loop[i].name.name, dirent_array_loop[i].pentry); begin_cookie += nbfound; } while(eod_met == TO_BE_CONTINUED); LogTest( "---------------------------------"); /* A lookup in the root fsal */ if((FSAL_IS_ERROR(status = FSAL_str2name("cea", 10, &name)))) { LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor); exit(1); } if((cache_entry_lookup = cache_inode_lookup(cache_entry_root, &name, &attrlookup, ht, &client, &cred, &cache_status)) == NULL) { LogTest( "Error: can't lookup"); exit(1); } /* A lookup in the root fsal */ if((FSAL_IS_ERROR(status = FSAL_str2name("log", 10, &name)))) { LogError(COMPONENT_STDOUT,ERR_FSAL, status.major, status.minor); exit(1); } if((cache_entry_lookup = cache_inode_lookup(cache_entry_root, &name, &attrlookup, ht, &client, &cred, &cache_status)) == NULL) { LogTest( "Error: can't lookup"); exit(1); } /* Print the Hash Table */ HashTable_Log(COMPONENT_STDOUT, ht); LogTest( "Readdir nbfound=%d, eod_met=%d", nbfound, eod_met); for(i = 0; i < nbfound; i++) LogTest( "dirent_array[%d] ==> %s | %p ", i, dirent_array[i].name.name, dirent_array[i].pentry); /* Call the GC */ LogTest( "Sleeping %d second before gc (for gc invalidation)", gcpol.file_expiration_delay + 2); sleep(gcpol.file_expiration_delay + 2); if(cache_inode_gc(ht, &client, &cache_status) != CACHE_INODE_SUCCESS) { LogTest( "Error: cache_inode_gc failed"); exit(1); } LogTest( "GC performed successfully"); /* Print the Hash Table */ HashTable_Log(COMPONENT_STDOUT, ht); /* Another readdir, after gc is made */ eod_met = TO_BE_CONTINUED; begin_cookie = 0; LogTest( "ANOTHER READDIR AFTER GC"); do { if(cache_inode_readdir(cache_entry_root, begin_cookie, 2, &nbfound, &eod_met, dirent_array_loop, ht, &client, &cred, &cache_status) != CACHE_INODE_SUCCESS) { LogTest("Error: cache_inode_readdir failed: %d", cache_status); exit(1); } for(i = 0; i < nbfound; i++) LogTest( " ==> %s | %p", dirent_array_loop[i].name.name, dirent_array_loop[i].pentry); begin_cookie += nbfound; } while(eod_met == TO_BE_CONTINUED); LogTest( "---------------------------------"); /* Print the Hash Table */ HashTable_Log(COMPONENT_STDOUT, ht); LogTest( "---------------------------------"); /* The end of all the tests */ LogTest( "All tests exited successfully"); exit(0); } /* main */
/** @return false and set error code and description string on failure */ bool ArSocket::connect(const char *host, int port, Type type, const char *openOnIP) { char localhost[maxHostNameLen()]; myError=NoErr; myErrorStr.clear(); if (!host) { if (gethostname(localhost, sizeof(localhost)) == 1) { myError=ConBadHost; myErrorStr="Failure to locate host '"; myErrorStr+=localhost; myErrorStr+="'"; ArLog::logErrorFromOS(ArLog::Normal, "ArSocket::connect: gethostname failed"); return(false); } host=localhost; } bzero(&mySin, sizeof(mySin)); // MPL taking out this next code line from the if since it makes // everything we can't resolve try to connect to localhost // && !hostAddr("localhost", mySin.sin_addr)) char useHost[1024]; int usePort; separateHost(host, port, useHost, sizeof(useHost), &usePort); if (!hostAddr(useHost, mySin.sin_addr)) return(false); setRawIPString(); mySin.sin_family=AF_INET; mySin.sin_port=hostToNetOrder(usePort); if ((type == TCP) && ((myFD=socket(AF_INET, SOCK_STREAM, 0)) < 0)) { myError=NetFail; myErrorStr="Failure to make TCP socket"; ArLog::logErrorFromOS(ArLog::Normal, "ArSocket::connect: could not make tcp socket"); return(false); } else if ((type == UDP) && ((myFD=socket(AF_INET, SOCK_DGRAM, 0)) < 0)) { myError=NetFail; myErrorStr="Failure to make UDP socket"; ArLog::logErrorFromOS(ArLog::Normal, "ArSocket::connect: could not make udp socket"); return(false); } ArUtil::setFileCloseOnExec(myFD); if (openOnIP != NULL) { struct sockaddr_in outSin; if (!hostAddr(openOnIP, outSin.sin_addr)) { myError = NameLookup; myErrorStr = "Name lookup failed"; ArLog::log(ArLog::Normal, "Couldn't find ip of %s to open on", openOnIP); return(false); } outSin.sin_family=AF_INET; outSin.sin_port=hostToNetOrder(0); if (bind(myFD, (struct sockaddr *)&outSin, sizeof(outSin)) < 0) { ArLog::logErrorFromOS(ArLog::Normal, "ArSocket::connect: Failure to bind socket to port %d", 0); return(false); } } myType=type; if (::connect(myFD, (struct sockaddr *)&mySin, sizeof(struct sockaddr_in)) < 0) { myErrorStr="Failure to connect socket"; switch (errno) { case ECONNREFUSED: myError=ConRefused; myErrorStr+="; Connection refused"; break; case ENETUNREACH: myError=ConNoRoute; myErrorStr+="; No route to host"; break; default: myError=NetFail; break; } ArLog::logErrorFromOS(ArLog::Verbose, "ArSocket::connect: could not connect"); ::close(myFD); myFD = -1; return(false); } return(true); }
int main(int argc, char* argv[]) { int sts = 0; int c; char buf[MAXHOSTNAMELEN]; pmProgname = basename(argv[0]); while ((c = getopt(argc, argv, "D:?")) != EOF) { switch (c) { case 'D': sts = __pmParseDebug(optarg); if (sts < 0) { pmprintf("%s: unrecognized debug flag specification (%s)\n", pmProgname, optarg); sts = 1; } else { pmDebug |= sts; sts = 0; } break; case '?': default: sts = 1; break; } } if (sts) { pmprintf("Usage: %s\n", pmProgname); pmflush(); exit(1); /*NOTREACHED*/ } (void)gethostname(buf, MAXHOSTNAMELEN); buf[MAXHOSTNAMELEN-1] = '\0'; mesg("Create two fetch groups"); QmcGroup group1; pmflush(); QmcGroup group2; pmflush(); mesg("Add number of instances to both groups"); QmcMetric* numinsts1 = group1.addMetric("dynamic.numinsts"); pmflush(); if (numinsts1->status() < 0) exit(1); else numinsts1->dump(cout); QmcMetric* numinsts2 = group2.addMetric("dynamic.numinsts"); pmflush(); if (numinsts2->status() < 0) exit(1); else numinsts2->dump(cout); mesg("Fetch both groups"); group1.fetch(); numinsts1->dump(cout); group2.fetch(); numinsts2->dump(cout); mesg("Add dynamic metrics to both groups"); QmcMetric* discrete1 = group1.addMetric("dynamic.discrete", 0.0, true); pmflush(); if (discrete1->status() < 0) exit(1); else discrete1->dump(cout); QmcMetric* instant1 = group1.addMetric("dynamic.instant", 0.0, true); pmflush(); if (instant1->status() < 0) exit(1); else instant1->dump(cout); QmcMetric* counter1 = group1.addMetric("dynamic.counter", 0.0, true); pmflush(); if (counter1->status() < 0) exit(1); else counter1->dump(cout); QmcMetric* discrete2 = group2.addMetric("dynamic.discrete"); pmflush(); if (discrete2->status() < 0) exit(1); else discrete2->dump(cout); QmcMetric* instant2 = group2.addMetric("dynamic.instant"); pmflush(); if (instant2->status() < 0) exit(1); else instant2->dump(cout); QmcMetric* counter2 = group2.addMetric("dynamic.counter"); pmflush(); if (counter2->status() < 0) exit(1); else counter2->dump(cout); mesg("Fetch both groups"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); group2.fetch(); dump(numinsts2, discrete2, instant2, counter2); mesg("Add an instance"); store(ADD_INST, "1"); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Update indom for first group"); update(discrete1, instant1, counter1); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Add another instance"); store(ADD_INST, "5"); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Update indom for first group"); update(discrete1, instant1, counter1); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Delete first instance"); store(DEL_INST, "1"); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Update indom for first group"); update(discrete1, instant1, counter1); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Fetch second group"); group2.fetch(); dump(numinsts2, discrete2, instant2, counter2); mesg("Update indom for second group"); update(discrete2, instant2, counter2); mesg("Fetch second group"); group2.fetch(); dump(numinsts2, discrete2, instant2, counter2); mesg("Fetch second group"); group2.fetch(); dump(numinsts2, discrete2, instant2, counter2); mesg("Delete second instance, add new instance"); store(DEL_INST, "5"); store(ADD_INST, "3"); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Update indom for first group"); update(discrete1, instant1, counter1); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Fetch second group"); group2.fetch(); dump(numinsts2, discrete2, instant2, counter2); mesg("Update indom for second group"); update(discrete2, instant2, counter2); mesg("Fetch second group"); group2.fetch(); dump(numinsts2, discrete2, instant2, counter2); mesg("Fetch second group"); group2.fetch(); dump(numinsts2, discrete2, instant2, counter2); mesg("Delete third instance"); store(DEL_INST, "3"); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Update indom for first group"); update(discrete1, instant1, counter1); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Fetch second group"); group2.fetch(); dump(numinsts2, discrete2, instant2, counter2); mesg("Update indom for second group"); update(discrete2, instant2, counter2); mesg("Fetch second group"); group2.fetch(); dump(numinsts2, discrete2, instant2, counter2); mesg("Add second instance again"); store(ADD_INST, "5"); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Update indom for first group"); update(discrete1, instant1, counter1); mesg("Fetch first group"); group1.fetch(); dump(numinsts1, discrete1, instant1, counter1); mesg("Fetch second group"); group2.fetch(); dump(numinsts2, discrete2, instant2, counter2); mesg("Update indom for second group"); update(discrete2, instant2, counter2); mesg("Fetch second group"); group2.fetch(); dump(numinsts2, discrete2, instant2, counter2); return 0; }
Router::Router(char *fn) //Constructor { WSADATA wsadata; HOSTENT* hp; char peer_name1[MAXHOSTNAMELEN], peer_name2[MAXHOSTNAMELEN]; SOCKADDR_IN sa_in; FileBuf.empty=true; try { if (WSAStartup(0x0202,&wsadata)!=0) throw "Error in starting WSAStartup()\n"; } //Display any needed error response. catch (char *str) { cerr<<str<<":"<<dec<<WSAGetLastError()<<endl; return;} //Get Host name gethostname(localhost,MAXHOSTNAMELEN); cout<<"Router starting on host:"<<localhost<<endl<<flush; //Open the log file fout.open(fn); try { //Create the Udp Sock1 if((Sock1 = socket(AF_INET,SOCK_DGRAM,0))==INVALID_SOCKET) throw "Create UDP Socket1 failed\n"; //Fill-in UDP Port and Address info. sa_in.sin_family = AF_INET; sa_in.sin_port = htons(ROUTER_PORT1); sa_in.sin_addr.s_addr = htonl(INADDR_ANY); //Bind the UDP port1 if (bind(Sock1,(LPSOCKADDR)&sa_in,sizeof(sa_in)) == SOCKET_ERROR) throw "can't bind the socket1"; //Create the Udp Sock2 if((Sock2 = socket(AF_INET,SOCK_DGRAM,0))==INVALID_SOCKET) throw "Create UDP Socket2 failed\n"; //Fill-in UDP Port and Address info. sa_in.sin_family = AF_INET; sa_in.sin_port = htons(ROUTER_PORT2); sa_in.sin_addr.s_addr = htonl(INADDR_ANY); //Bind the UDP port2 if (bind(Sock2,(LPSOCKADDR)&sa_in,sizeof(sa_in)) == SOCKET_ERROR) throw "can't bind the socket2"; cout<<"\nPlease enter the first peer host name:"<<flush; //enter the dropping rate. cin>>peer_name1; cout<<"\nPlease enter the second peer host name:"<<flush; //enter the dropping rate. cin>>peer_name2; cout<<"\nPlease enter the drop rate:"<<flush; //enter the dropping rate. cin>>damage_rate; cout<<"\nPlease enter the delay rate:"<<flush; //enter the dropping rate. cin>>delay_rate; //creat peer host1 if((hp=gethostbyname(peer_name1)) == NULL) throw "get server name failed\n"; memset(&sa_in_peer1,0,sizeof(sa_in_peer1)); memcpy(&sa_in_peer1.sin_addr,hp->h_addr,hp->h_length); sa_in_peer1.sin_family = hp->h_addrtype; sa_in_peer1.sin_port = htons(PEER_PORT1); //creat peer host2 if((hp=gethostbyname(peer_name2)) == NULL) throw "get client name failed\n"; memset(&sa_in_peer2,0,sizeof(sa_in_peer2)); memcpy(&sa_in_peer2.sin_addr,hp->h_addr,hp->h_length); sa_in_peer2.sin_family = hp->h_addrtype; sa_in_peer2.sin_port = htons(PEER_PORT2); if (TRACE) { fout<<"Peer host 1: "<<peer_name1<<endl; fout<<"Peer host 2: "<<peer_name2<<endl; fout<<"Damage Rate: "<<damage_rate<<endl; } } catch (char *str) {cerr<<str<<":"<<dec<<WSAGetLastError()<<endl; exit(1);} srand( (unsigned)time( NULL ) ); }
extern int syslogd_main(int argc, char **argv) { int opt; int doFork = TRUE; char *p; /* do normal option parsing */ while ((opt = getopt(argc, argv, "m:nO:s:Sb:R:LC::")) > 0) { switch (opt) { case 'm': MarkInterval = atoi(optarg) * 60; break; case 'n': doFork = FALSE; break; case 'O': logFilePath = optarg; break; #ifdef CONFIG_FEATURE_ROTATE_LOGFILE case 's': logFileSize = atoi(optarg) * 1024; break; case 'b': logFileRotate = atoi(optarg); if( logFileRotate > 99 ) logFileRotate = 99; break; #endif #ifdef CONFIG_FEATURE_REMOTE_LOG case 'R': RemoteHost = bb_xstrdup(optarg); if ((p = strchr(RemoteHost, ':'))) { RemotePort = atoi(p + 1); *p = '\0'; } doRemoteLog = TRUE; break; case 'L': local_logging = TRUE; break; #endif #ifdef CONFIG_FEATURE_IPC_SYSLOG case 'C': if (optarg) { int buf_size = atoi(optarg); if (buf_size >= 4) { shm_size = buf_size * 1024; } } circular_logging = TRUE; break; #endif case 'S': small = true; break; default: bb_show_usage(); } } #ifdef CONFIG_FEATURE_REMOTE_LOG /* If they have not specified remote logging, then log locally */ if (doRemoteLog == FALSE) local_logging = TRUE; #endif /* Store away localhost's name before the fork */ gethostname(LocalHostName, sizeof(LocalHostName)); if ((p = strchr(LocalHostName, '.'))) { *p = '\0'; } umask(0); if (doFork == TRUE) { #if defined(__uClinux__) vfork_daemon_rexec(0, 1, argc, argv, "-n"); #else /* __uClinux__ */ if(daemon(0, 1) < 0) bb_perror_msg_and_die("daemon"); #endif /* __uClinux__ */ } doSyslogd(); return EXIT_SUCCESS; }
int main(int argc, char **argv) { afs_int32 code; afs_uint32 myHost; struct hostent *th; char hostname[64]; struct rx_service *tservice; struct rx_securityClass **securityClasses; afs_int32 numClasses; int lwps = 3; char clones[MAXHOSTSPERCELL]; afs_uint32 host = htonl(INADDR_ANY); struct cmd_syndesc *opts; struct cmd_item *list; char *pr_dbaseName; char *configDir; char *logFile; char *whoami = "ptserver"; char *auditFileName = NULL; char *interface = NULL; #ifdef AFS_AIX32_ENV /* * The following signal action for AIX is necessary so that in case of a * crash (i.e. core is generated) we can include the user's data section * in the core dump. Unfortunately, by default, only a partial core is * generated which, in many cases, isn't too useful. */ struct sigaction nsa; sigemptyset(&nsa.sa_mask); nsa.sa_handler = SIG_DFL; nsa.sa_flags = SA_FULLDUMP; sigaction(SIGABRT, &nsa, NULL); sigaction(SIGSEGV, &nsa, NULL); #endif osi_audit_init(); osi_audit(PTS_StartEvent, 0, AUD_END); /* Initialize dirpaths */ if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) { #ifdef AFS_NT40_ENV ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0); #endif fprintf(stderr, "%s: Unable to obtain AFS server directory.\n", argv[0]); exit(2); } pr_dbaseName = strdup(AFSDIR_SERVER_PRDB_FILEPATH); configDir = strdup(AFSDIR_SERVER_ETC_DIRPATH); logFile = strdup(AFSDIR_SERVER_PTLOG_FILEPATH); #if defined(SUPERGROUPS) /* make sure the structures for database records are the same size */ if ((sizeof(struct prentry) != ENTRYSIZE) || (sizeof(struct prentryg) != ENTRYSIZE)) { fprintf(stderr, "The structures for the database records are different" " sizes\n" "struct prentry = %" AFS_SIZET_FMT "\n" "struct prentryg = %" AFS_SIZET_FMT "\n" "ENTRYSIZE = %d\n", sizeof(struct prentry), sizeof(struct prentryg), ENTRYSIZE); PT_EXIT(1); } #endif cmd_DisableAbbreviations(); cmd_DisablePositionalCommands(); opts = cmd_CreateSyntax(NULL, NULL, NULL, NULL); /* ptserver specific options */ cmd_AddParmAtOffset(opts, OPT_database, "-database", CMD_SINGLE, CMD_OPTIONAL, "database file"); cmd_AddParmAlias(opts, OPT_database, "-db"); cmd_AddParmAtOffset(opts, OPT_access, "-default_access", CMD_SINGLE, CMD_OPTIONAL, "default access flags for new entries"); #if defined(SUPERGROUPS) cmd_AddParmAtOffset(opts, OPT_groupdepth, "-groupdepth", CMD_SINGLE, CMD_OPTIONAL, "max search depth for supergroups"); cmd_AddParmAlias(opts, OPT_groupdepth, "-depth"); #endif cmd_AddParmAtOffset(opts, OPT_restricted, "-restricted", CMD_FLAG, CMD_OPTIONAL, "enable restricted mode"); /* general server options */ cmd_AddParmAtOffset(opts, OPT_auditlog, "-auditlog", CMD_SINGLE, CMD_OPTIONAL, "location of audit log"); cmd_AddParmAtOffset(opts, OPT_auditiface, "-audit-interface", CMD_SINGLE, CMD_OPTIONAL, "interface to use for audit logging"); cmd_AddParmAtOffset(opts, OPT_config, "-config", CMD_SINGLE, CMD_OPTIONAL, "configuration location"); cmd_AddParmAtOffset(opts, OPT_debug, "-d", CMD_SINGLE, CMD_OPTIONAL, "debug level"); cmd_AddParmAtOffset(opts, OPT_logfile, "-logfile", CMD_SINGLE, CMD_OPTIONAL, "location of logfile"); cmd_AddParmAtOffset(opts, OPT_threads, "-p", CMD_SINGLE, CMD_OPTIONAL, "number of threads"); #if !defined(AFS_NT40_ENV) cmd_AddParmAtOffset(opts, OPT_syslog, "-syslog", CMD_SINGLE_OR_FLAG, CMD_OPTIONAL, "log to syslog"); #endif /* rx options */ cmd_AddParmAtOffset(opts, OPT_peer, "-enable_peer_stats", CMD_FLAG, CMD_OPTIONAL, "enable RX transport statistics"); cmd_AddParmAtOffset(opts, OPT_process, "-enable_process_stats", CMD_FLAG, CMD_OPTIONAL, "enable RX RPC statistics"); cmd_AddParmAtOffset(opts, OPT_rxbind, "-rxbind", CMD_FLAG, CMD_OPTIONAL, "bind only to the primary interface"); cmd_AddParmAtOffset(opts, OPT_rxmaxmtu, "-rxmaxmtu", CMD_SINGLE, CMD_OPTIONAL, "maximum MTU for RX"); /* rxkad options */ cmd_AddParmAtOffset(opts, OPT_dotted, "-allow-dotted-principals", CMD_FLAG, CMD_OPTIONAL, "permit Kerberos 5 principals with dots"); code = cmd_Parse(argc, argv, &opts); if (code == CMD_HELP) { PT_EXIT(0); } if (code) PT_EXIT(1); cmd_OptionAsString(opts, OPT_config, &configDir); cmd_OpenConfigFile(AFSDIR_SERVER_CONFIG_FILE_FILEPATH); cmd_SetCommandName("ptserver"); if (cmd_OptionAsList(opts, OPT_access, &list) == 0) { prp_user_default = prp_access_mask(list->data); if (list->next == NULL || list->next->data == NULL) { fprintf(stderr, "Missing second argument for -default_access\n"); PT_EXIT(1); } prp_group_default = prp_access_mask(list->next->data); } #if defined(SUPERGROUPS) cmd_OptionAsInt(opts, OPT_groupdepth, &depthsg); #endif cmd_OptionAsFlag(opts, OPT_restricted, &restricted); /* general server options */ cmd_OptionAsString(opts, OPT_auditlog, &auditFileName); if (cmd_OptionAsString(opts, OPT_auditiface, &interface) == 0) { if (osi_audit_interface(interface)) { printf("Invalid audit interface '%s'\n", interface); PT_EXIT(1); } free(interface); } cmd_OptionAsInt(opts, OPT_debug, &LogLevel); cmd_OptionAsString(opts, OPT_database, &pr_dbaseName); cmd_OptionAsString(opts, OPT_logfile, &logFile); if (cmd_OptionAsInt(opts, OPT_threads, &lwps) == 0) { if (lwps > 64) { /* maximum of 64 */ printf("Warning: '-p %d' is too big; using %d instead\n", lwps, 64); lwps = 64; } else if (lwps < 3) { /* minimum of 3 */ printf("Warning: '-p %d' is too small; using %d instead\n", lwps, 3); lwps = 3; } } #ifndef AFS_NT40_ENV if (cmd_OptionPresent(opts, OPT_syslog)) { serverLogSyslog = 1; cmd_OptionAsInt(opts, OPT_syslog, &serverLogSyslogFacility); } #endif /* rx options */ if (cmd_OptionPresent(opts, OPT_peer)) rx_enablePeerRPCStats(); if (cmd_OptionPresent(opts, OPT_process)) rx_enableProcessRPCStats(); cmd_OptionAsFlag(opts, OPT_rxbind, &rxBind); cmd_OptionAsInt(opts, OPT_rxmaxmtu, &rxMaxMTU); /* rxkad options */ cmd_OptionAsFlag(opts, OPT_dotted, &rxkadDisableDotCheck); cmd_FreeOptions(&opts); if (auditFileName) { osi_audit_file(auditFileName); osi_audit(PTS_StartEvent, 0, AUD_END); } #ifndef AFS_NT40_ENV serverLogSyslogTag = "ptserver"; #endif OpenLog(logFile); /* set up logging */ SetupLogSignals(); prdir = afsconf_Open(configDir); if (!prdir) { fprintf(stderr, "ptserver: can't open configuration directory.\n"); PT_EXIT(1); } if (afsconf_GetNoAuthFlag(prdir)) printf("ptserver: running unauthenticated\n"); #ifdef AFS_NT40_ENV /* initialize winsock */ if (afs_winsockInit() < 0) { ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0); fprintf(stderr, "ptserver: couldn't initialize winsock. \n"); PT_EXIT(1); } #endif /* get this host */ gethostname(hostname, sizeof(hostname)); th = gethostbyname(hostname); if (!th) { fprintf(stderr, "ptserver: couldn't get address of this host.\n"); PT_EXIT(1); } memcpy(&myHost, th->h_addr, sizeof(afs_uint32)); /* get list of servers */ code = afsconf_GetExtendedCellInfo(prdir, NULL, "afsprot", &info, clones); if (code) { afs_com_err(whoami, code, "Couldn't get server list"); PT_EXIT(2); } /* initialize audit user check */ osi_audit_set_user_check(prdir, pr_IsLocalRealmMatch); /* initialize ubik */ ubik_SetClientSecurityProcs(afsconf_ClientAuth, afsconf_UpToDate, prdir); ubik_SetServerSecurityProcs(afsconf_BuildServerSecurityObjects, afsconf_CheckAuth, prdir); /* The max needed is when deleting an entry. A full CoEntry deletion * required removal from 39 entries. Each of which may refers to the entry * being deleted in one of its CoEntries. If a CoEntry is freed its * predecessor CoEntry will be modified as well. Any freed blocks also * modifies the database header. Counting the entry being deleted and its * CoEntry this adds up to as much as 1+1+39*3 = 119. If all these entries * and the header are in separate Ubik buffers then 120 buffers may be * required. */ ubik_nBuffers = 120 + /*fudge */ 40; if (rxBind) { afs_int32 ccode; if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || AFSDIR_SERVER_NETINFO_FILEPATH) { char reason[1024]; ccode = afsconf_ParseNetFiles(SHostAddrs, NULL, NULL, ADDRSPERSITE, reason, AFSDIR_SERVER_NETINFO_FILEPATH, AFSDIR_SERVER_NETRESTRICT_FILEPATH); } else { ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE); } if (ccode == 1) { host = SHostAddrs[0]; /* the following call is idempotent so if/when it gets called * again by the ubik init stuff, it doesn't really matter * -- klm */ rx_InitHost(host, htons(AFSCONF_PROTPORT)); } } /* Disable jumbograms */ rx_SetNoJumbo(); if (rxMaxMTU != -1) { if (rx_SetMaxMTU(rxMaxMTU) != 0) { printf("rxMaxMTU %d is invalid\n", rxMaxMTU); PT_EXIT(1); } } code = ubik_ServerInitByInfo(myHost, htons(AFSCONF_PROTPORT), &info, clones, pr_dbaseName, &dbase); if (code) { afs_com_err(whoami, code, "Ubik init failed"); PT_EXIT(2); } #if defined(SUPERGROUPS) pt_hook_write(); #endif afsconf_BuildServerSecurityObjects(prdir, &securityClasses, &numClasses); tservice = rx_NewServiceHost(host, 0, PRSRV, "Protection Server", securityClasses, numClasses, PR_ExecuteRequest); if (tservice == (struct rx_service *)0) { fprintf(stderr, "ptserver: Could not create new rx service.\n"); PT_EXIT(3); } rx_SetMinProcs(tservice, 2); rx_SetMaxProcs(tservice, lwps); if (rxkadDisableDotCheck) { rx_SetSecurityConfiguration(tservice, RXS_CONFIG_FLAGS, (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK); } tservice = rx_NewServiceHost(host, 0, RX_STATS_SERVICE_ID, "rpcstats", securityClasses, numClasses, RXSTATS_ExecuteRequest); if (tservice == (struct rx_service *)0) { fprintf(stderr, "ptserver: Could not create new rx service.\n"); PT_EXIT(3); } rx_SetMinProcs(tservice, 2); rx_SetMaxProcs(tservice, 4); /* allow super users to manage RX statistics */ rx_SetRxStatUserOk(pr_rxstat_userok); LogCommandLine(argc, argv, "ptserver", #if defined(SUPERGROUPS) "1.1", #else "1.0", #endif "Starting AFS", FSLog); if (afsconf_GetLatestKey(prdir, NULL, NULL) == 0) { LogDesWarning(); } rx_StartServer(1); osi_audit(PTS_FinishEvent, -1, AUD_END); exit(0); }
int GetHostName(char *szName, int nSize) { return gethostname(szName, nSize); }
int main(int argc, char **argv) { struct hostent * host = NULL; int net_preopen_result; #ifdef ENABLE_IPV6 struct addrinfo hints, *res; int error; struct hostent trhost; char * alptr[2]; struct sockaddr_in * sa4; struct sockaddr_in6 * sa6; #endif /* Get the raw sockets first thing, so we can drop to user euid immediately */ if ( ( net_preopen_result = net_preopen () ) ) { fprintf( stderr, "mtr: unable to get raw sockets.\n" ); exit( EXIT_FAILURE ); } /* Now drop to user permissions */ if (setgid(getgid()) || setuid(getuid())) { fprintf (stderr, "mtr: Unable to drop permissions.\n"); exit(1); } /* Double check, just in case */ if ((geteuid() != getuid()) || (getegid() != getgid())) { fprintf (stderr, "mtr: Unable to drop permissions.\n"); exit(1); } /* reset the random seed */ srand (getpid()); display_detect(&argc, &argv); display_mode = 0; /* The field options are now in a static array all together, but that requires a run-time initialization. */ init_fld_options (); parse_mtr_options (getenv ("MTR_OPTIONS")); parse_arg (argc, argv); while (optind < argc) { char* name = argv[optind++]; append_to_names(argv[0], name); } /* Now that we know mtrtype we can select which socket to use */ if (net_selectsocket() != 0) { fprintf( stderr, "mtr: Couldn't determine raw socket type.\n" ); exit( EXIT_FAILURE ); } if (PrintVersion) { printf ("mtr " MTR_VERSION "\n"); exit(0); } if (PrintHelp) { printf("usage: %s [--help] [--version] [-4|-6] [-F FILENAME]\n" "\t\t[--report] [--report-wide] [--displaymode MODE]\n" "\t\t[--xml] [--gtk] [--curses] [--raw] [--csv] [--split]\n" "\t\t[--no-dns] [--show-ips] [-o FIELDS] [-y IPINFO] [--aslookup]\n" "\t\t[-i INTERVAL] [-c COUNT] [-s PACKETSIZE] [-B BITPATTERN]\n" "\t\t[-Q TOS] [--mpls]\n" "\t\t[-a ADDRESS] [-f FIRST-TTL] [-m MAX-TTL] [-U MAX_UNKNOWN]\n" "\t\t[--udp] [--tcp] [--sctp] [-P PORT] [-L LOCALPORT] [-Z TIMEOUT]\n" "\t\t[-G GRACEPERIOD] [-M MARK] HOSTNAME\n", argv[0]); printf("See the man page for details.\n"); exit(0); } time_t now = time(NULL); if (!names) append_to_names (argv[0], "localhost"); // default: localhost. names_t* head = names; while (names != NULL) { Hostname = names->name; // if (Hostname == NULL) Hostname = "localhost"; // no longer necessary. if (gethostname(LocalHostname, sizeof(LocalHostname))) { strcpy(LocalHostname, "UNKNOWNHOST"); } if (net_preopen_result != 0) { fprintf(stderr, "mtr: Unable to get raw socket. (Executable not suid?)\n"); if ( DisplayMode != DisplayCSV ) exit(EXIT_FAILURE); else { names = names->next; continue; } } #ifdef ENABLE_IPV6 /* gethostbyname2() is deprecated so we'll use getaddrinfo() instead. */ bzero( &hints, sizeof hints ); hints.ai_family = af; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo( Hostname, NULL, &hints, &res ); if ( error ) { if (error == EAI_SYSTEM) perror ("Failed to resolve host"); else fprintf (stderr, "Failed to resolve host: %s\n", gai_strerror(error)); if ( DisplayMode != DisplayCSV ) exit(EXIT_FAILURE); else { names = names->next; continue; } } /* Convert the first addrinfo into a hostent. */ host = &trhost; bzero( host, sizeof trhost ); host->h_name = res->ai_canonname; host->h_aliases = NULL; host->h_addrtype = res->ai_family; af = res->ai_family; host->h_length = res->ai_addrlen; host->h_addr_list = alptr; switch ( af ) { case AF_INET: sa4 = (struct sockaddr_in *) res->ai_addr; alptr[0] = (void *) &(sa4->sin_addr); break; case AF_INET6: sa6 = (struct sockaddr_in6 *) res->ai_addr; alptr[0] = (void *) &(sa6->sin6_addr); break; default: fprintf( stderr, "mtr unknown address type\n" ); if ( DisplayMode != DisplayCSV ) exit(EXIT_FAILURE); else { names = names->next; continue; } } alptr[1] = NULL; #else host = gethostbyname(Hostname); if (host == NULL) { herror("mtr gethostbyname"); if ( DisplayMode != DisplayCSV ) exit(EXIT_FAILURE); else { names = names->next; continue; } } af = host->h_addrtype; #endif if (net_open(host) != 0) { fprintf(stderr, "mtr: Unable to start net module.\n"); if ( DisplayMode != DisplayCSV ) exit(EXIT_FAILURE); else { names = names->next; continue; } } if (net_set_interfaceaddress (InterfaceAddress) != 0) { fprintf( stderr, "mtr: Couldn't set interface address.\n" ); if ( DisplayMode != DisplayCSV ) exit(EXIT_FAILURE); else { names = names->next; continue; } } lock(argv[0], stdout); display_open(); dns_open(); display_loop(); net_end_transit(); display_close(now); unlock(argv[0], stdout); if ( DisplayMode != DisplayCSV ) break; else names = names->next; } net_close(); while (head != NULL) { names_t* item = head; free(item->name); item->name = NULL; head = head->next; free(item); item = NULL; } head=NULL; return 0; }
static int initWebs(int demo) { struct hostent *hp; struct in_addr intaddr; char_t wbuf[128]; char host[64]; char *cp; /* * Initialize the socket subsystem */ socketOpen(); /* * Initialize the User Management database */ #ifdef USER_MANAGEMENT_SUPPORT umOpen(); umRestore(T("umconfig.txt")); #endif /* * Define the local Ip address, host name, default home page and the * root web directory. */ if (gethostname(host, sizeof(host)) < 0) { error(E_L, E_LOG, T("Can't get hostname")); return -1; } if ((hp = gethostbyname(host)) == NULL) { error(E_L, E_LOG, T("Can't get host address")); return -1; } memcpy((void*) &intaddr, (void*) hp->h_addr_list[0], (size_t) hp->h_length); /* * Set /web as the root web. Modify this to suit your needs */ if (demo) { websSetDefaultDir(demoWeb); } else { websSetDefaultDir(rootWeb); } /* * Set the IP address and host name. */ cp = inet_ntoa(intaddr); ascToUni(wbuf, cp, min(strlen(cp) + 1, sizeof(wbuf))); websSetIpaddr(wbuf); ascToUni(wbuf, hp->h_name, min(strlen(hp->h_name) + 1, sizeof(wbuf))); websSetHost(wbuf); /* * Configure the web server options before opening the web server */ websSetDefaultPage(T("default.asp")); websSetPassword(password); /* * Open the web server on the given port. If that port is taken, try * the next sequential port for up to "retries" attempts. */ websOpenServer(port, retries); /* * First create the URL handlers. Note: handlers are called in sorted order * with the longest path handler examined first. Here we define the security * handler, forms handler and the default web page handler. */ websUrlHandlerDefine(T(""), NULL, 0, websSecurityHandler, WEBS_HANDLER_FIRST); websUrlHandlerDefine(T("/goform"), NULL, 0, websFormHandler, 0); websUrlHandlerDefine(T("/cgi-bin"), NULL, 0, websCgiHandler, 0); websUrlHandlerDefine(T(""), NULL, 0, websDefaultHandler, WEBS_HANDLER_LAST); /* * Now define two test procedures. Replace these with your application * relevant ASP script procedures and form functions. */ websAspDefine(T("aspTest"), aspTest); websFormDefine(T("formTest"), formTest); /* * Create the Form handlers for the User Management pages */ #ifdef USER_MANAGEMENT_SUPPORT formDefineUserMgmt(); #endif /* * Create a handler for the default home page */ websUrlHandlerDefine(T("/"), NULL, 0, websHomePageHandler, 0); return 0; }
int main( int argc, char **argv ) { int status; rodsEnv myEnv; rErrMsg_t errMsg; rcComm_t *conn; rodsArguments_t myRodsArgs; char *optStr, buffer[HUGE_NAME_LEN], hostname[LONG_NAME_LEN]; objType_t srcType; rodsPathInp_t rodsPathInp; optStr = "hr"; status = parseCmdLineOpt( argc, argv, optStr, 0, &myRodsArgs ); if ( status < 0 ) { printf( "Use -h for help\n" ); exit( 1 ); } if ( myRodsArgs.help == True ) { usage(); exit( 0 ); } status = getRodsEnv( &myEnv ); if ( status < 0 ) { rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " ); exit( 1 ); } if ( strcmp( argv[argc - 1], "i:" ) == 0 ) { srcType = UNKNOWN_OBJ_T; strcpy( argv[argc - 1], "." ); } else if ( strncmp( argv[argc - 1], "i:", 2 ) == 0 ) { srcType = UNKNOWN_OBJ_T; snprintf( buffer, sizeof( buffer ), "%s", argv[argc - 1] + 2 ); argv[argc - 1] = buffer; } else { srcType = UNKNOWN_FILE_T; } status = parseCmdLinePath( argc, argv, optind, &myEnv, srcType, NO_INPUT_T, 0, &rodsPathInp ); if ( status < 0 ) { rodsLogError( LOG_ERROR, status, "main: parseCmdLinePath error. " ); usage(); exit( 1 ); } // =-=-=-=-=-=-=- // initialize pluggable api table irods::pack_entry_table& pk_tbl = irods::get_pack_table(); irods::api_entry_table& api_tbl = irods::get_client_api_table(); init_api_table( api_tbl, pk_tbl ); conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName, myEnv.rodsZone, 0, &errMsg ); if ( conn == NULL ) { exit( 2 ); } if ( strcmp( myEnv.rodsUserName, PUBLIC_USER_NAME ) != 0 ) { status = clientLogin( conn ); if ( status != 0 ) { rcDisconnect( conn ); exit( 7 ); } } status = gethostname( hostname, LONG_NAME_LEN ); if ( status < 0 ) { printf( "cannot resolve server name, aborting!\n" ); exit( 4 ); } status = scanObj( conn, &myRodsArgs, &rodsPathInp, hostname ); printErrorStack( conn->rError ); rcDisconnect( conn ); exit( status ); }
/** Set the host name @param [in] Argc The number of arguments @param [in] Argv The argument value array @retval 0 The application exited normally. @retval Other An error occurred. **/ int main ( IN int Argc, IN char **Argv ) { int AppStatus; DEBUG (( DEBUG_INFO, "%a starting\r\n", Argv[0])); // // Determine if the host name is specified // AppStatus = 0; if ( 1 < Argc ) { // // Set the host name // AppStatus = sethostname ( Argv[1], strlen ( Argv[1])); if ( -1 == AppStatus ) { switch ( errno ) { default: Print ( L"ERROR - errno: %d\r\n", errno ); break; case ENODEV: Print ( L"WARNING - Plarform does not support permanent storage!\r\n" ); break; case ENOMEM: Print ( L"ERROR - Insufficient storage to save host name!\r\n" ); break; case ENOTSUP: Print ( L"ERROR - Platform does not support environment variable storage!\r\n" ); break; } } } else { // // Display the current host name // AppStatus = gethostname ( &mBuffer[0], sizeof ( mBuffer )); if ( -1 == AppStatus ) { Print ( L"ERROR - Unable to get host name, errno: %d\r\n", errno ); } else { if ( 0 == mBuffer[0]) { Print ( L"Host name is not set!\r\n" ); } else { Print ( L"Host name: %a", &mBuffer[0]); } } } // // All done // return errno; }
//初始化cycle ngx_cycle_t * ngx_init_cycle(ngx_cycle_t *old_cycle) { void *rv; char **senv, **env; ngx_uint_t i, n; ngx_log_t *log; ngx_time_t *tp; ngx_conf_t conf;//与nginx.conf配置文件相关的一个变量,配置文件的解析都是围绕这个变量进行 ngx_pool_t *pool; ngx_cycle_t *cycle, **old; ngx_shm_zone_t *shm_zone, *oshm_zone; ngx_list_part_t *part, *opart; ngx_open_file_t *file; ngx_listening_t *ls, *nls; ngx_core_conf_t *ccf, *old_ccf; ngx_core_module_t *module; char hostname[NGX_MAXHOSTNAMELEN]; ngx_timezone_update(); /* force localtime update with a new timezone */ tp = ngx_timeofday(); // 这个宏就是取出之前的ngx_cache_time tp->sec = 0; ngx_time_update(); //这里又进行了一次time更新 log = old_cycle->log; //创建内存池,并把日志和它关联 ,创建固定大小的内存池:16384 pool = ngx_create_pool(NGX_CYCLE_POOL_SIZE, log); if (pool == NULL) { return NULL; } pool->log = log; //分配内存,并把内存池、日志、旧信息以及路径进行了设置。这两段代码所的是创建一个内存池,然后在内存池上为cycle变量分配一个存储空间。 cycle = ngx_pcalloc(pool, sizeof(ngx_cycle_t)); if (cycle == NULL) { ngx_destroy_pool(pool); return NULL; } cycle->pool = pool; cycle->log = log; cycle->new_log.log_level = NGX_LOG_ERR; cycle->old_cycle = old_cycle; //配置路径的前缀 cycle->conf_prefix.len = old_cycle->conf_prefix.len; cycle->conf_prefix.data = ngx_pstrdup(pool, &old_cycle->conf_prefix); if (cycle->conf_prefix.data == NULL) { ngx_destroy_pool(pool); return NULL; } //系统路径的前缀 cycle->prefix.len = old_cycle->prefix.len; cycle->prefix.data = ngx_pstrdup(pool, &old_cycle->prefix); if (cycle->prefix.data == NULL) { ngx_destroy_pool(pool); return NULL; } //配置文件路径 cycle->conf_file.len = old_cycle->conf_file.len; cycle->conf_file.data = ngx_pnalloc(pool, old_cycle->conf_file.len + 1); if (cycle->conf_file.data == NULL) { ngx_destroy_pool(pool); return NULL; } ngx_cpystrn(cycle->conf_file.data, old_cycle->conf_file.data, old_cycle->conf_file.len + 1); //配置参数设定 cycle->conf_param.len = old_cycle->conf_param.len; cycle->conf_param.data = ngx_pstrdup(pool, &old_cycle->conf_param); if (cycle->conf_param.data == NULL) { ngx_destroy_pool(pool); return NULL; } //文件路径分配空间并初始化 ,如果old_cycle默认没有指定,则大小为10 n = old_cycle->pathes.nelts ? old_cycle->pathes.nelts : 10; cycle->pathes.elts = ngx_pcalloc(pool, n * sizeof(ngx_path_t *)); if (cycle->pathes.elts == NULL) { ngx_destroy_pool(pool); return NULL; } cycle->pathes.nelts = 0; cycle->pathes.size = sizeof(ngx_path_t *); cycle->pathes.nalloc = n; cycle->pathes.pool = pool; // 每个打开的文件都会放到cycle中的open_files中。每个共享内存段都会放到shared_memory链表中 //如果原来结构中有文件,那么直接统计原来打开的文件,否则默认20 if (old_cycle->open_files.part.nelts) { n = old_cycle->open_files.part.nelts; for (part = old_cycle->open_files.part.next; part; part = part->next) { n += part->nelts; } } else { n = 20; } //根据数量初始化,初始化open_files if (ngx_list_init(&cycle->open_files, pool, n, sizeof(ngx_open_file_t)) != NGX_OK) { ngx_destroy_pool(pool); return NULL; } //如果原来结构中共享内存,那么直接统计原来共享内存数,否则默认20 if (old_cycle->shared_memory.part.nelts) { n = old_cycle->shared_memory.part.nelts; for (part = old_cycle->shared_memory.part.next; part; part = part->next) { n += part->nelts; } } else { n = 1; } //根据数量初始化,初始化shared_memory if (ngx_list_init(&cycle->shared_memory, pool, n, sizeof(ngx_shm_zone_t)) != NGX_OK) { ngx_destroy_pool(pool); return NULL; } //创建监听者,并初始化 n = old_cycle->listening.nelts ? old_cycle->listening.nelts : 10; cycle->listening.elts = ngx_pcalloc(pool, n * sizeof(ngx_listening_t)); if (cycle->listening.elts == NULL) { ngx_destroy_pool(pool); return NULL; } cycle->listening.nelts = 0; cycle->listening.size = sizeof(ngx_listening_t); cycle->listening.nalloc = n; cycle->listening.pool = pool; ngx_queue_init(&cycle->reusable_connections_queue); //创建所有模块配置的指针, 这里的ngx_max_module在nginx.c中计算过了 cycle->conf_ctx = ngx_pcalloc(pool, ngx_max_module * sizeof(void *)); if (cycle->conf_ctx == NULL) { ngx_destroy_pool(pool); return NULL; } //获取主机名,设置 hostname,这个时候hostname就是机器名,比如“yejianfeng-D1” if (gethostname(hostname, NGX_MAXHOSTNAMELEN) == -1) { ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, "gethostname() failed"); ngx_destroy_pool(pool); return NULL; } /* on Linux gethostname() silently truncates name that does not fit */ hostname[NGX_MAXHOSTNAMELEN - 1] = '\0'; cycle->hostname.len = ngx_strlen(hostname); cycle->hostname.data = ngx_pnalloc(pool, cycle->hostname.len); if (cycle->hostname.data == NULL) { ngx_destroy_pool(pool); return NULL; } ngx_strlow(cycle->hostname.data, (u_char *) hostname, cycle->hostname.len); //将主机名变为消息,所以这里主机名是不分大小写的 //调用核心模块的配置创建函数, cycle->conf_ctx 中对应的指针指向创建的配置 //创建所有core module的configure.它通过调用每个core module的ngx_xxx_module_create_conf方法,来创建对应的conf, //然后将这个conf对象保存在全局的conf_ctx中 for (i = 0; ngx_modules[i]; i++) { if (ngx_modules[i]->type != NGX_CORE_MODULE) { //非核心模块直接跳过 continue; } //这里只对核心模块进行处理,核心模块就是ngx_core_module,ngx_errlog_module,ngx_events_module和ngx_http_module //实际上只有ngx_core_module_create_conf //得到core modules module = ngx_modules[i]->ctx; //如果create_conf存在,则直接创建config if (module->create_conf) { rv = module->create_conf(cycle); //对每个模块调用模块内部的钩子ngx_xxx_module_create_conf,当然第一个模块是core if (rv == NULL) { ngx_destroy_pool(pool); return NULL; } //保存config,这里看到conf_ctx里面就是放对应模块的main conf. cycle->conf_ctx[ngx_modules[i]->index] = rv; } } senv = environ; //对指令结构进行初始化:参数,内存池 ngx_memzero(&conf, sizeof(ngx_conf_t)); /* STUB: init array ? */ conf.args = ngx_array_create(pool, 10, sizeof(ngx_str_t)); if (conf.args == NULL) { ngx_destroy_pool(pool); return NULL; } conf.temp_pool = ngx_create_pool(NGX_CYCLE_POOL_SIZE, log); if (conf.temp_pool == NULL) { ngx_destroy_pool(pool); return NULL; } //指令结果赋值 conf.ctx = cycle->conf_ctx; conf.cycle = cycle; conf.pool = pool; conf.log = log; conf.module_type = NGX_CORE_MODULE;//注意,一开始命令的类型就是MAIN,并且模块类型是core。 conf.cmd_type = NGX_MAIN_CONF; #if 0 log->log_level = NGX_LOG_DEBUG_ALL; #endif if (ngx_conf_param(&conf) != NGX_CONF_OK) { environ = senv; ngx_destroy_cycle_pools(&conf); return NULL; } //开始解析配置文件了,解析配置文件它会一行行读取,然后如果遇到指令 //则会查找到对应的ngx_command_t对象,然后执行对应的回调set方法。这里所有动作都在ngx_conf_parse这个函数中进行. //这函数是立即模块的核心函数,对配置文件边解析边处理 if (ngx_conf_parse(&conf, &cycle->conf_file) != NGX_CONF_OK) { environ = senv; ngx_destroy_cycle_pools(&conf); return NULL; } if (ngx_test_config && !ngx_quiet_mode) { ngx_log_stderr(0, "the configuration file %s syntax is ok", cycle->conf_file.data); } //当配置文件解析完毕后,就初始化core module的config for (i = 0; ngx_modules[i]; i++) { if (ngx_modules[i]->type != NGX_CORE_MODULE) { continue; } module = ngx_modules[i]->ctx; //调用ngx_xxx_module_init_conf if (module->init_conf) { if (module->init_conf(cycle, cycle->conf_ctx[ngx_modules[i]->index]) == NGX_CONF_ERROR) { environ = senv; ngx_destroy_cycle_pools(&conf); return NULL; } } } if (ngx_process == NGX_PROCESS_SIGNALLER) { return cycle; } ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module); if (ngx_test_config) { if (ngx_create_pidfile(&ccf->pid, log) != NGX_OK) { goto failed; } } else if (!ngx_is_init_cycle(old_cycle)) { /* * we do not create the pid file in the first ngx_init_cycle() call * because we need to write the demonized process pid */ old_ccf = (ngx_core_conf_t *) ngx_get_conf(old_cycle->conf_ctx, ngx_core_module); if (ccf->pid.len != old_ccf->pid.len || ngx_strcmp(ccf->pid.data, old_ccf->pid.data) != 0) { /* new pid file name */ if (ngx_create_pidfile(&ccf->pid, log) != NGX_OK) { goto failed; } ngx_delete_pidfile(old_cycle); } } if (ngx_test_lockfile(cycle->lock_file.data, log) != NGX_OK) { goto failed; } // 创建client_body_temp,proxy_temp,fastcgi_temp,uwsgi_temp,scgi_temp这几个目录 if (ngx_create_pathes(cycle, ccf->user) != NGX_OK) { goto failed; } if (cycle->new_log.file == NULL) { cycle->new_log.file = ngx_conf_open_file(cycle, &error_log); if (cycle->new_log.file == NULL) { goto failed; } } /* open the new files */ part = &cycle->open_files.part; file = part->elts; // 打开所有文件,这时候file里面不仅有存文件路径,而且存储了文件描述符等信息。 for (i = 0; /* void */ ; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; file = part->elts; i = 0; } if (file[i].name.len == 0) { continue; } file[i].fd = ngx_open_file(file[i].name.data, NGX_FILE_APPEND, NGX_FILE_CREATE_OR_OPEN, NGX_FILE_DEFAULT_ACCESS); ngx_log_debug3(NGX_LOG_DEBUG_CORE, log, 0, "log: %p %d \"%s\"", &file[i], file[i].fd, file[i].name.data); if (file[i].fd == NGX_INVALID_FILE) { ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, ngx_open_file_n " \"%s\" failed", file[i].name.data); goto failed; } #if !(NGX_WIN32) if (fcntl(file[i].fd, F_SETFD, FD_CLOEXEC) == -1) { ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, "fcntl(FD_CLOEXEC) \"%s\" failed", file[i].name.data); goto failed; } #endif } cycle->log = &cycle->new_log; pool->log = &cycle->new_log; /* create shared memory */ part = &cycle->shared_memory.part; shm_zone = part->elts; for (i = 0; /* void */ ; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; shm_zone = part->elts; i = 0; } if (shm_zone[i].shm.size == 0) { ngx_log_error(NGX_LOG_EMERG, log, 0, "zero size shared memory zone \"%V\"", &shm_zone[i].shm.name); goto failed; } shm_zone[i].shm.log = cycle->log; opart = &old_cycle->shared_memory.part; oshm_zone = opart->elts; for (n = 0; /* void */ ; n++) { if (n >= opart->nelts) { if (opart->next == NULL) { break; } opart = opart->next; oshm_zone = opart->elts; n = 0; } if (shm_zone[i].shm.name.len != oshm_zone[n].shm.name.len) { continue; } if (ngx_strncmp(shm_zone[i].shm.name.data, oshm_zone[n].shm.name.data, shm_zone[i].shm.name.len) != 0) { continue; } if (shm_zone[i].shm.size == oshm_zone[n].shm.size) { shm_zone[i].shm.addr = oshm_zone[n].shm.addr; if (shm_zone[i].init(&shm_zone[i], oshm_zone[n].data) != NGX_OK) { goto failed; } goto shm_zone_found; } ngx_shm_free(&oshm_zone[n].shm); break; } //初始化所有创建的共享内存 if (ngx_shm_alloc(&shm_zone[i].shm) != NGX_OK) { goto failed; } if (ngx_init_zone_pool(cycle, &shm_zone[i]) != NGX_OK) { goto failed; } if (shm_zone[i].init(&shm_zone[i], NULL) != NGX_OK) { goto failed; } shm_zone_found: continue; } /* handle the listening sockets */ if (old_cycle->listening.nelts) { ls = old_cycle->listening.elts; for (i = 0; i < old_cycle->listening.nelts; i++) { ls[i].remain = 0; } nls = cycle->listening.elts; for (n = 0; n < cycle->listening.nelts; n++) { for (i = 0; i < old_cycle->listening.nelts; i++) { if (ls[i].ignore) { continue; } if (ngx_cmp_sockaddr(nls[n].sockaddr, ls[i].sockaddr) == NGX_OK) { nls[n].fd = ls[i].fd; nls[n].previous = &ls[i]; ls[i].remain = 1; if (ls[n].backlog != nls[i].backlog) { nls[n].listen = 1; } #if (NGX_HAVE_DEFERRED_ACCEPT && defined SO_ACCEPTFILTER) /* * FreeBSD, except the most recent versions, * could not remove accept filter */ nls[n].deferred_accept = ls[i].deferred_accept; if (ls[i].accept_filter && nls[n].accept_filter) { if (ngx_strcmp(ls[i].accept_filter, nls[n].accept_filter) != 0) { nls[n].delete_deferred = 1; nls[n].add_deferred = 1; } } else if (ls[i].accept_filter) { nls[n].delete_deferred = 1; } else if (nls[n].accept_filter) { nls[n].add_deferred = 1; } #endif #if (NGX_HAVE_DEFERRED_ACCEPT && defined TCP_DEFER_ACCEPT) if (ls[n].deferred_accept && !nls[n].deferred_accept) { nls[n].delete_deferred = 1; } else if (ls[i].deferred_accept != nls[n].deferred_accept) { nls[n].add_deferred = 1; } #endif break; } } if (nls[n].fd == -1) { nls[n].open = 1; } } } else { ls = cycle->listening.elts; for (i = 0; i < cycle->listening.nelts; i++) { ls[i].open = 1; #if (NGX_HAVE_DEFERRED_ACCEPT && defined SO_ACCEPTFILTER) if (ls[i].accept_filter) { ls[i].add_deferred = 1; } #endif #if (NGX_HAVE_DEFERRED_ACCEPT && defined TCP_DEFER_ACCEPT) if (ls[i].deferred_accept) { ls[i].add_deferred = 1; } #endif } } //listen socket的初始化,创建并bind等操作, 打开所有的监听套接口(依次进行socket,bind,listen) if (ngx_open_listening_sockets(cycle) != NGX_OK) { goto failed; } if (!ngx_test_config) { ngx_configure_listening_sockets(cycle); } /* commit the new cycle configuration */ if (!ngx_use_stderr && cycle->log->file->fd != ngx_stderr) { if (ngx_set_stderr(cycle->log->file->fd) == NGX_FILE_ERROR) { ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, ngx_set_stderr_n " failed"); } } pool->log = cycle->log; //调用init_module对所有的模块进行初始化,调用所有模块的ngx_XXX_module_init钩子,比如ngx_event_module_init for (i = 0; ngx_modules[i]; i++) { if (ngx_modules[i]->init_module) { if (ngx_modules[i]->init_module(cycle) != NGX_OK) { /* fatal */ exit(1); } } } /* close and delete stuff that lefts from an old cycle */ // 关闭或删除残留在old_cycle中的资源 /* free the unnecessary shared memory */ opart = &old_cycle->shared_memory.part; oshm_zone = opart->elts; for (i = 0; /* void */ ; i++) { if (i >= opart->nelts) { if (opart->next == NULL) { goto old_shm_zone_done; } opart = opart->next; oshm_zone = opart->elts; i = 0; } part = &cycle->shared_memory.part; shm_zone = part->elts; for (n = 0; /* void */ ; n++) { if (n >= part->nelts) { if (part->next == NULL) { break; } part = part->next; shm_zone = part->elts; n = 0; } if (oshm_zone[i].shm.name.len == shm_zone[n].shm.name.len && ngx_strncmp(oshm_zone[i].shm.name.data, shm_zone[n].shm.name.data, oshm_zone[i].shm.name.len) == 0) { goto live_shm_zone; } } ngx_shm_free(&oshm_zone[i].shm); live_shm_zone: continue; } old_shm_zone_done: /* close the unnecessary listening sockets */ ls = old_cycle->listening.elts; for (i = 0; i < old_cycle->listening.nelts; i++) { if (ls[i].remain || ls[i].fd == -1) { continue; } if (ngx_close_socket(ls[i].fd) == -1) { ngx_log_error(NGX_LOG_EMERG, log, ngx_socket_errno, ngx_close_socket_n " listening socket on %V failed", &ls[i].addr_text); } #if (NGX_HAVE_UNIX_DOMAIN) if (ls[i].sockaddr->sa_family == AF_UNIX) { u_char *name; name = ls[i].addr_text.data + sizeof("unix:") - 1; ngx_log_error(NGX_LOG_WARN, cycle->log, 0, "deleting socket %s", name); if (ngx_delete_file(name) == -1) { ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_socket_errno, ngx_delete_file_n " %s failed", name); } } #endif } /* close the unnecessary open files */ part = &old_cycle->open_files.part; file = part->elts; for (i = 0; /* void */ ; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; file = part->elts; i = 0; } if (file[i].fd == NGX_INVALID_FILE || file[i].fd == ngx_stderr) { continue; } if (ngx_close_file(file[i].fd) == NGX_FILE_ERROR) { ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, ngx_close_file_n " \"%s\" failed", file[i].name.data); } } ngx_destroy_pool(conf.temp_pool); if (ngx_process == NGX_PROCESS_MASTER || ngx_is_init_cycle(old_cycle)) { /* * perl_destruct() frees environ, if it is not the same as it was at * perl_construct() time, therefore we save the previous cycle * environment before ngx_conf_parse() where it will be changed. */ env = environ; environ = senv; ngx_destroy_pool(old_cycle->pool); cycle->old_cycle = NULL; environ = env; return cycle; } if (ngx_temp_pool == NULL) { ngx_temp_pool = ngx_create_pool(128, cycle->log); if (ngx_temp_pool == NULL) { ngx_log_error(NGX_LOG_EMERG, cycle->log, 0, "could not create ngx_temp_pool"); exit(1); } n = 10; ngx_old_cycles.elts = ngx_pcalloc(ngx_temp_pool, n * sizeof(ngx_cycle_t *)); if (ngx_old_cycles.elts == NULL) { exit(1); } ngx_old_cycles.nelts = 0; ngx_old_cycles.size = sizeof(ngx_cycle_t *); ngx_old_cycles.nalloc = n; ngx_old_cycles.pool = ngx_temp_pool; ngx_cleaner_event.handler = ngx_clean_old_cycles; ngx_cleaner_event.log = cycle->log; ngx_cleaner_event.data = &dumb; dumb.fd = (ngx_socket_t) -1; } ngx_temp_pool->log = cycle->log; old = ngx_array_push(&ngx_old_cycles); if (old == NULL) { exit(1); } *old = old_cycle; if (!ngx_cleaner_event.timer_set) { ngx_add_timer(&ngx_cleaner_event, 30000); ngx_cleaner_event.timer_set = 1; } return cycle; failed: if (!ngx_is_init_cycle(old_cycle)) { old_ccf = (ngx_core_conf_t *) ngx_get_conf(old_cycle->conf_ctx, ngx_core_module); if (old_ccf->environment) { environ = old_ccf->environment; } } /* rollback the new cycle configuration */ part = &cycle->open_files.part; file = part->elts; for (i = 0; /* void */ ; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; file = part->elts; i = 0; } if (file[i].fd == NGX_INVALID_FILE || file[i].fd == ngx_stderr) { continue; } if (ngx_close_file(file[i].fd) == NGX_FILE_ERROR) { ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, ngx_close_file_n " \"%s\" failed", file[i].name.data); } } if (ngx_test_config) { ngx_destroy_cycle_pools(&conf); return NULL; } ls = cycle->listening.elts; for (i = 0; i < cycle->listening.nelts; i++) { if (ls[i].fd == -1 || !ls[i].open) { continue; } if (ngx_close_socket(ls[i].fd) == -1) { ngx_log_error(NGX_LOG_EMERG, log, ngx_socket_errno, ngx_close_socket_n " %V failed", &ls[i].addr_text); } } ngx_destroy_cycle_pools(&conf); return NULL; }
CMPIStatus IndCIMXMLHandlerCreateInstance(CMPIInstanceMI * mi, const CMPIContext *ctx, const CMPIResult *rslt, const CMPIObjectPath * cop, const CMPIInstance *ci) { CMPIStatus st = { CMPI_RC_OK, NULL }; CMPIArgs *in, *out = NULL; CMPIObjectPath *op; unsigned short persistenceType; _SFCB_ENTER(TRACE_INDPROVIDER, "IndCIMXMLHandlerCreateInstance"); if (interOpNameSpace(cop, &st) == 0) _SFCB_RETURN(st); CMPIInstance *ciLocal = CMClone(ci, NULL); memLinkInstance(ciLocal); CMPIObjectPath* copLocal = CMClone(cop, NULL); memLinkObjectPath(copLocal); setCCN(copLocal,ciLocal,"CIM_ComputerSystem"); internalProviderGetInstance(copLocal, &st); if (st.rc == CMPI_RC_ERR_FAILED) _SFCB_RETURN(st); if (st.rc == CMPI_RC_OK) { setStatus(&st, CMPI_RC_ERR_ALREADY_EXISTS, NULL); _SFCB_RETURN(st); } CMPIString *sysname=ciLocal->ft->getProperty(ciLocal,"SystemName",&st).value.string; if (sysname == NULL || sysname->hdl == NULL) { char hostName[512]; hostName[0]=0; gethostname(hostName,511); /* should be the same as SystemName of IndicationService */ CMAddKey(copLocal, "SystemName", hostName, CMPI_chars); CMSetProperty(ciLocal,"SystemName",hostName,CMPI_chars); } CMPIString *dest = CMGetProperty(ciLocal, "destination", &st).value.string; if (dest == NULL || CMGetCharPtr(dest) == NULL) { setStatus(&st, CMPI_RC_ERR_FAILED, "Destination property not found; is required"); CMRelease(ciLocal); _SFCB_RETURN(st); } else { /* if no scheme is given, assume http (as * req. for param by mof) */ char *ds = CMGetCharPtr(dest); if (strstr(ds, "://") == NULL) { char *prefix = "http://"; int n = strlen(ds) + strlen(prefix) + 1; char *newdest = malloc(n * sizeof(*newdest)); strcpy(newdest, prefix); strcat(newdest, ds); CMSetProperty(ciLocal, "destination", newdest, CMPI_chars); free(newdest); } } CMPIData persistence = CMGetProperty(ciLocal, "persistencetype", &st); if (persistence.state == CMPI_nullValue || persistence.state == CMPI_notFound) { persistenceType = 2; /* default is 2 = permanent */ } else if (persistence.value.uint16 < 1 || persistence.value.uint16 > 3) { setStatus(&st, CMPI_RC_ERR_FAILED, "PersistenceType property must be 1, 2, or 3"); CMRelease(ciLocal); _SFCB_RETURN(st); } else { persistenceType = persistence.value.uint16; } CMSetProperty(ciLocal, "persistencetype", &persistenceType, CMPI_uint16); if (CMClassPathIsA(_broker, copLocal, "cim_listenerdestination", NULL)) { //get the creation timestamp struct timeval tv; struct timezone tz; char context[100]; gettimeofday(&tv, &tz); struct tm cttm; char * gtime = malloc(15 * sizeof(*gtime)); memset(gtime, 0, 15 * sizeof(char)); if (gmtime_r(&tv.tv_sec, &cttm) != NULL) { strftime(gtime, 15, "%Y%m%d%H%M%S", &cttm); } // Even though reliable indications may be disabled, we need to do this // in case it ever gets enabled. // Get the IndicationService name CMPIObjectPath * isop = CMNewObjectPath(_broker, "root/interop", "CIM_IndicationService", NULL); CMPIEnumeration * isenm = _broker->bft->enumerateInstances(_broker, ctx, isop, NULL, NULL); CMPIData isinst = CMGetNext(isenm, NULL); CMPIData mc = CMGetProperty(isinst.value.inst, "Name", NULL); // build the context string sprintf (context,"%s#%s#",mc.value.string->ft->getCharPtr(mc.value.string,NULL),gtime); CMPIValue scontext; scontext.string = sfcb_native_new_CMPIString(context, NULL, 0); free(gtime); // set the properties CMSetProperty(ciLocal, "SequenceContext", &scontext, CMPI_string); CMPIValue zarro = {.sint64 = -1 }; CMSetProperty(ciLocal, "LastSequenceNumber", &zarro, CMPI_sint64); } _SFCB_TRACE_VAR(CMPIString *str = CDToString(_broker, copLocal, NULL)); _SFCB_TRACE_VAR(CMPIString *ns = CMGetNameSpace(copLocal, NULL)); _SFCB_TRACE(1,("--- handler %s %s", (char *) ns->hdl, (char *) str->hdl)); in = CMNewArgs(_broker, NULL); CMAddArg(in, "handler", &ciLocal, CMPI_instance); CMAddArg(in, "key", &copLocal, CMPI_ref); op = CMNewObjectPath(_broker, "root/interop", "cim_indicationsubscription", &st); CBInvokeMethod(_broker, ctx, op, "_addHandler", in, out, &st); if (st.rc == CMPI_RC_OK) { st = InternalProviderCreateInstance(NULL, ctx, rslt, copLocal, ciLocal); } else { CBInvokeMethod(_broker,ctx,op,"_removeHandler",in,out,NULL); } _SFCB_RETURN(st); } /* * ModifyInstance only for ListenerDestination.Destination */ CMPIStatus IndCIMXMLHandlerModifyInstance(CMPIInstanceMI * mi, const CMPIContext *ctx, const CMPIResult *rslt, const CMPIObjectPath * cop, const CMPIInstance *ci, const char **properties) { CMPIStatus st = { CMPI_RC_OK, NULL }; CMPIString *cn = CMGetClassName(cop, NULL); const char *cns = cn->ft->getCharPtr(cn,NULL); CMPIArgs *in; _SFCB_ENTER(TRACE_INDPROVIDER, "IndCIMXMLHandlerModifyInstance"); if(isa("root/interop", cns, "cim_listenerdestination")) { _SFCB_TRACE(1,("--- modify %s", cns)); CMPIData newDest = CMGetProperty(ci, "Destination", &st); fprintf(stderr, "new dest is %s\n", CMGetCharPtr(newDest.value.string)); if(newDest.state != CMPI_goodValue) { st.rc = CMPI_RC_ERR_FAILED; return st; } in=CMNewArgs(_broker,NULL); CMAddArg(in,"handler",&ci,CMPI_instance); CMAddArg(in,"key",&cop,CMPI_ref); /* cn needs to be IndicationSub to route the IM call to interopProv */ CMPIObjectPath* sop=CMNewObjectPath(_broker,"root/interop","cim_indicationsubscription",&st); CBInvokeMethod(_broker,ctx,sop,"_updateHandler",in,NULL,&st); if (st.rc==CMPI_RC_OK) { st=InternalProviderModifyInstance(NULL,ctx,rslt,cop,ci,properties); } else { CBInvokeMethod(_broker,ctx,sop,"_removeHandler",in,NULL,NULL); } } _SFCB_RETURN(st); }
int main(int argc, char** argv) { initOpts(&Opts::opts); parseOpts(argc, argv, &Opts::opts); // Begin by setting up our usage environment: TaskScheduler* scheduler = BasicTaskScheduler::createNew(); env = BasicUsageEnvironment::createNew(*scheduler); // Create 'groupsocks' for RTP and RTCP: struct in_addr destinationAddress; destinationAddress.s_addr = chooseRandomIPv4SSMAddress(*env); // Note: This is a multicast address. If you wish instead to stream // using unicast, then you should use the "testOnDemandRTSPServer" // test program - not this test program - as a model. const unsigned short rtpPortNum = 18888; const unsigned short rtcpPortNum = rtpPortNum+1; const unsigned char ttl = 255; char socks[1000] = { 0 }; sprintf(socks, "GroupSocket: %d.%d.%d.%d:%d", (destinationAddress.s_addr >> 24) & 0xff, (destinationAddress.s_addr >> 16) & 0xff, (destinationAddress.s_addr >> 8) & 0xff, destinationAddress.s_addr & 0xff, rtpPortNum); *env << socks << "\n"; const Port rtpPort(rtpPortNum); const Port rtcpPort(rtcpPortNum); Groupsock rtpGroupsock(*env, destinationAddress, rtpPort, ttl); rtpGroupsock.multicastSendOnly(); // we're a SSM source Groupsock rtcpGroupsock(*env, destinationAddress, rtcpPort, ttl); rtcpGroupsock.multicastSendOnly(); // we're a SSM source // Create a 'H264 Video RTP' sink from the RTP 'groupsock': OutPacketBuffer::maxSize = 200000; videoSink = H264VideoRTPSink::createNew(*env, &rtpGroupsock, 96); // Create (and start) a 'RTCP instance' for this RTP sink: const unsigned estimatedSessionBandwidth = 500; // in kbps; for RTCP b/w share const unsigned maxCNAMElen = 100; unsigned char CNAME[maxCNAMElen+1]; gethostname((char*)CNAME, maxCNAMElen); CNAME[maxCNAMElen] = '\0'; // just in case RTCPInstance* rtcp = RTCPInstance::createNew(*env, &rtcpGroupsock, estimatedSessionBandwidth, CNAME, videoSink, NULL /* we're a server */, True /* we're a SSM source */); // Note: This starts RTCP running automatically RTSPServer* rtspServer = RTSPServer::createNew(*env, 8554); if (rtspServer == NULL) { *env << "Failed to create RTSP server: " << env->getResultMsg() << "\n"; exit(1); } ServerMediaSession* sms = ServerMediaSession::createNew(*env, "source", inputFileName, "Session streamed by \"testH264VideoStreamer\"", True /*SSM*/); sms->addSubsession(PassiveServerMediaSubsession::createNew(*videoSink, rtcp)); rtspServer->addServerMediaSession(sms); char* url = rtspServer->rtspURL(sms); *env << "Play this stream using the URL \"" << url << "\"\n"; delete[] url; // Start the streaming: *env << "Beginning streaming...\n"; play(); env->taskScheduler().doEventLoop(); // does not return return 0; // only to prevent compiler warning }
char * TRANS(GetPeerNetworkId) (XtransConnInfo ciptr) { int family = ciptr->family; char *hostname; char addrbuf[256]; char *addr = NULL; switch (family) { case AF_UNSPEC: #if defined(UNIXCONN) || defined(STREAMSCONN) || defined(LOCALCONN) || defined(OS2PIPECONN) case AF_UNIX: { if (gethostname (addrbuf, sizeof (addrbuf)) == 0) { addrbuf[sizeof(addrbuf)-1] = '\0'; addr = addrbuf; } break; } #endif /* defined(UNIXCONN) || defined(STREAMSCONN) || defined(LOCALCONN) || defined(OS2PIPECONN) */ #if defined(TCPCONN) || defined(STREAMSCONN) || defined(MNX_TCPCONN) case AF_INET: { char *peer_addr = ciptr->peeraddr; struct sockaddr_in *saddr = (struct sockaddr_in *) peer_addr; struct hostent * hostp = NULL; #if defined(SIGALRM) && !defined(_WIN32) /* * gethostbyaddr can take a LONG time if the host does not exist. * Assume that if it does not respond in NAMESERVER_TIMEOUT seconds * that something is wrong and do not make the user wait. * gethostbyaddr will continue after a signal, so we have to * jump out of it. */ nameserver_timedout = 0; signal (SIGALRM, nameserver_lost); alarm (4); if (setjmp(env) == 0) { #endif hostp = gethostbyaddr ((char *) &saddr->sin_addr, sizeof (saddr->sin_addr), AF_INET); #if defined(SIGALRM) && !defined(_WIN32) } alarm (0); #endif if (hostp != NULL) addr = hostp->h_name; else addr = inet_ntoa (saddr->sin_addr); break; } #endif /* defined(TCPCONN) || defined(STREAMSCONN) || MNX_TCPCONN */ #if defined(DNETCONN) case AF_DECnet: { char *peer_addr = ciptr->peeraddr; struct sockaddr_dn *saddr = (struct sockaddr_dn *) peer_addr; struct nodeent *np; if (np = getnodebyaddr(saddr->sdn_add.a_addr, saddr->sdn_add.a_len, AF_DECnet)) { snprintf(addrbuf, sizeof(addrbuf), "%s:", np->n_name); } else { snprintf(addrbuf, sizeof(addrbuf), "%s:", dnet_htoa(&saddr->sdn_add)); } addr = addrbuf; break; } #endif /* defined(DNETCONN) */ #if defined(AMRPCCONN) case AF_AMOEBA: { addr = "Amoeba"; /* not really used */ break; } #endif #if defined(AMTCPCONN) && !(defined(TCPCONN) || defined(STREAMSCONN)) case AF_INET: { if (gethostname (addrbuf, sizeof (addrbuf)) == 0) { addrbuf[sizeof(addrbuf)-1] = '\0'; addr = addrbuf; } else { addr = ""; } break; } #endif default: return (NULL); } hostname = (char *) xalloc ( strlen (ciptr->transptr->TransName) + strlen (addr) + 2); strcpy (hostname, ciptr->transptr->TransName); strcat (hostname, "/"); if (addr) strcat (hostname, addr); return (hostname); }
ngx_cycle_t * ngx_init_cycle(ngx_cycle_t *old_cycle) { void *rv; char **senv, **env; ngx_uint_t i, n; ngx_log_t *log; ngx_time_t *tp; ngx_conf_t conf; ngx_pool_t *pool; ngx_cycle_t *cycle, **old; ngx_shm_zone_t *shm_zone, *oshm_zone; ngx_list_part_t *part, *opart; ngx_open_file_t *file; ngx_listening_t *ls, *nls; ngx_core_conf_t *ccf, *old_ccf; ngx_core_module_t *module; char hostname[NGX_MAXHOSTNAMELEN]; ngx_timezone_update(); /* force localtime update with a new timezone */ tp = ngx_timeofday(); tp->sec = 0; ngx_time_update(); log = old_cycle->log; pool = ngx_create_pool(NGX_CYCLE_POOL_SIZE, log); if (pool == NULL) { return NULL; } pool->log = log; cycle = ngx_pcalloc(pool, sizeof(ngx_cycle_t)); if (cycle == NULL) { ngx_destroy_pool(pool); return NULL; } cycle->pool = pool; cycle->log = log; cycle->new_log.log_level = NGX_LOG_ERR; cycle->old_cycle = old_cycle; cycle->conf_prefix.len = old_cycle->conf_prefix.len; cycle->conf_prefix.data = ngx_pstrdup(pool, &old_cycle->conf_prefix); if (cycle->conf_prefix.data == NULL) { ngx_destroy_pool(pool); return NULL; } cycle->prefix.len = old_cycle->prefix.len; cycle->prefix.data = ngx_pstrdup(pool, &old_cycle->prefix); if (cycle->prefix.data == NULL) { ngx_destroy_pool(pool); return NULL; } cycle->conf_file.len = old_cycle->conf_file.len; cycle->conf_file.data = ngx_pnalloc(pool, old_cycle->conf_file.len + 1); if (cycle->conf_file.data == NULL) { ngx_destroy_pool(pool); return NULL; } ngx_cpystrn(cycle->conf_file.data, old_cycle->conf_file.data, old_cycle->conf_file.len + 1); cycle->conf_param.len = old_cycle->conf_param.len; cycle->conf_param.data = ngx_pstrdup(pool, &old_cycle->conf_param); if (cycle->conf_param.data == NULL) { ngx_destroy_pool(pool); return NULL; } n = old_cycle->pathes.nelts ? old_cycle->pathes.nelts : 10; cycle->pathes.elts = ngx_pcalloc(pool, n * sizeof(ngx_path_t *)); if (cycle->pathes.elts == NULL) { ngx_destroy_pool(pool); return NULL; } cycle->pathes.nelts = 0; cycle->pathes.size = sizeof(ngx_path_t *); cycle->pathes.nalloc = n; cycle->pathes.pool = pool; if (old_cycle->open_files.part.nelts) { n = old_cycle->open_files.part.nelts; for (part = old_cycle->open_files.part.next; part; part = part->next) { n += part->nelts; } } else { n = 20; } if (ngx_list_init(&cycle->open_files, pool, n, sizeof(ngx_open_file_t)) != NGX_OK) { ngx_destroy_pool(pool); return NULL; } if (old_cycle->shared_memory.part.nelts) { n = old_cycle->shared_memory.part.nelts; for (part = old_cycle->shared_memory.part.next; part; part = part->next) { n += part->nelts; } } else { n = 1; } if (ngx_list_init(&cycle->shared_memory, pool, n, sizeof(ngx_shm_zone_t)) != NGX_OK) { ngx_destroy_pool(pool); return NULL; } n = old_cycle->listening.nelts ? old_cycle->listening.nelts : 10; cycle->listening.elts = ngx_pcalloc(pool, n * sizeof(ngx_listening_t)); if (cycle->listening.elts == NULL) { ngx_destroy_pool(pool); return NULL; } cycle->listening.nelts = 0; cycle->listening.size = sizeof(ngx_listening_t); cycle->listening.nalloc = n; cycle->listening.pool = pool; cycle->conf_ctx = ngx_pcalloc(pool, ngx_max_module * sizeof(void *)); if (cycle->conf_ctx == NULL) { ngx_destroy_pool(pool); return NULL; } if (gethostname(hostname, NGX_MAXHOSTNAMELEN) == -1) { ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, "gethostname() failed"); ngx_destroy_pool(pool); return NULL; } /* on Linux gethostname() silently truncates name that does not fit */ hostname[NGX_MAXHOSTNAMELEN - 1] = '\0'; cycle->hostname.len = ngx_strlen(hostname); cycle->hostname.data = ngx_pnalloc(pool, cycle->hostname.len); if (cycle->hostname.data == NULL) { ngx_destroy_pool(pool); return NULL; } ngx_memcpy(cycle->hostname.data, hostname, cycle->hostname.len); for (i = 0; ngx_modules[i]; i++) { if (ngx_modules[i]->type != NGX_CORE_MODULE) { continue; } module = ngx_modules[i]->ctx; if (module->create_conf) { rv = module->create_conf(cycle); if (rv == NULL) { ngx_destroy_pool(pool); return NULL; } cycle->conf_ctx[ngx_modules[i]->index] = rv; } } senv = environ; ngx_memzero(&conf, sizeof(ngx_conf_t)); /* STUB: init array ? */ conf.args = ngx_array_create(pool, 10, sizeof(ngx_str_t)); if (conf.args == NULL) { ngx_destroy_pool(pool); return NULL; } conf.temp_pool = ngx_create_pool(NGX_CYCLE_POOL_SIZE, log); if (conf.temp_pool == NULL) { ngx_destroy_pool(pool); return NULL; } conf.ctx = cycle->conf_ctx; conf.cycle = cycle; conf.pool = pool; conf.log = log; conf.module_type = NGX_CORE_MODULE; conf.cmd_type = NGX_MAIN_CONF; #if 0 log->log_level = NGX_LOG_DEBUG_ALL; #endif if (ngx_conf_param(&conf) != NGX_CONF_OK) { environ = senv; ngx_destroy_cycle_pools(&conf); return NULL; } if (ngx_conf_parse(&conf, &cycle->conf_file) != NGX_CONF_OK) { environ = senv; ngx_destroy_cycle_pools(&conf); return NULL; } if (ngx_test_config) { ngx_log_stderr(0, "the configuration file %s syntax is ok", cycle->conf_file.data); } for (i = 0; ngx_modules[i]; i++) { if (ngx_modules[i]->type != NGX_CORE_MODULE) { continue; } module = ngx_modules[i]->ctx; if (module->init_conf) { if (module->init_conf(cycle, cycle->conf_ctx[ngx_modules[i]->index]) == NGX_CONF_ERROR) { environ = senv; ngx_destroy_cycle_pools(&conf); return NULL; } } } if (ngx_process == NGX_PROCESS_SIGNALLER) { return cycle; } ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module); if (ngx_test_config) { if (ngx_create_pidfile(&ccf->pid, log) != NGX_OK) { goto failed; } } else if (!ngx_is_init_cycle(old_cycle)) { /* * we do not create the pid file in the first ngx_init_cycle() call * because we need to write the demonized process pid */ old_ccf = (ngx_core_conf_t *) ngx_get_conf(old_cycle->conf_ctx, ngx_core_module); if (ccf->pid.len != old_ccf->pid.len || ngx_strcmp(ccf->pid.data, old_ccf->pid.data) != 0) { /* new pid file name */ if (ngx_create_pidfile(&ccf->pid, log) != NGX_OK) { goto failed; } ngx_delete_pidfile(old_cycle); } } if (ngx_test_lockfile(cycle->lock_file.data, log) != NGX_OK) { goto failed; } if (ngx_create_pathes(cycle, ccf->user) != NGX_OK) { goto failed; } if (cycle->new_log.file == NULL) { cycle->new_log.file = ngx_conf_open_file(cycle, &error_log); if (cycle->new_log.file == NULL) { goto failed; } } /* open the new files */ part = &cycle->open_files.part; file = part->elts; for (i = 0; /* void */ ; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; file = part->elts; i = 0; } if (file[i].name.len == 0) { continue; } file[i].fd = ngx_open_file(file[i].name.data, NGX_FILE_APPEND, NGX_FILE_CREATE_OR_OPEN, NGX_FILE_DEFAULT_ACCESS); ngx_log_debug3(NGX_LOG_DEBUG_CORE, log, 0, "log: %p %d \"%s\"", &file[i], file[i].fd, file[i].name.data); if (file[i].fd == NGX_INVALID_FILE) { ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, ngx_open_file_n " \"%s\" failed", file[i].name.data); goto failed; } #if !(NGX_WIN32) if (fcntl(file[i].fd, F_SETFD, FD_CLOEXEC) == -1) { ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, "fcntl(FD_CLOEXEC) \"%s\" failed", file[i].name.data); goto failed; } #endif } cycle->log = &cycle->new_log; pool->log = &cycle->new_log; /* create shared memory */ part = &cycle->shared_memory.part; shm_zone = part->elts; for (i = 0; /* void */ ; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; shm_zone = part->elts; i = 0; } if (shm_zone[i].shm.size == 0) { ngx_log_error(NGX_LOG_EMERG, log, 0, "zero size shared memory zone \"%V\"", &shm_zone[i].shm.name); goto failed; } if (shm_zone[i].init == NULL) { /* unused shared zone */ continue; } shm_zone[i].shm.log = cycle->log; opart = &old_cycle->shared_memory.part; oshm_zone = opart->elts; for (n = 0; /* void */ ; n++) { if (n >= opart->nelts) { if (opart->next == NULL) { break; } opart = opart->next; oshm_zone = opart->elts; n = 0; } if (shm_zone[i].shm.name.len != oshm_zone[n].shm.name.len) { continue; } if (ngx_strncmp(shm_zone[i].shm.name.data, oshm_zone[n].shm.name.data, shm_zone[i].shm.name.len) != 0) { continue; } if (shm_zone[i].shm.size == oshm_zone[n].shm.size) { shm_zone[i].shm.addr = oshm_zone[n].shm.addr; if (shm_zone[i].init(&shm_zone[i], oshm_zone[n].data) != NGX_OK) { goto failed; } goto shm_zone_found; } ngx_shm_free(&oshm_zone[n].shm); break; } if (ngx_shm_alloc(&shm_zone[i].shm) != NGX_OK) { goto failed; } if (ngx_init_zone_pool(cycle, &shm_zone[i]) != NGX_OK) { goto failed; } if (shm_zone[i].init(&shm_zone[i], NULL) != NGX_OK) { goto failed; } shm_zone_found: continue; } /* handle the listening sockets */ if (old_cycle->listening.nelts) { ls = old_cycle->listening.elts; for (i = 0; i < old_cycle->listening.nelts; i++) { ls[i].remain = 0; } nls = cycle->listening.elts; for (n = 0; n < cycle->listening.nelts; n++) { for (i = 0; i < old_cycle->listening.nelts; i++) { if (ls[i].ignore) { continue; } if (ngx_cmp_sockaddr(nls[n].sockaddr, ls[i].sockaddr) == NGX_OK) { nls[n].fd = ls[i].fd; nls[n].previous = &ls[i]; ls[i].remain = 1; if (ls[n].backlog != nls[i].backlog) { nls[n].listen = 1; } #if (NGX_HAVE_DEFERRED_ACCEPT && defined SO_ACCEPTFILTER) /* * FreeBSD, except the most recent versions, * could not remove accept filter */ nls[n].deferred_accept = ls[i].deferred_accept; if (ls[i].accept_filter && nls[n].accept_filter) { if (ngx_strcmp(ls[i].accept_filter, nls[n].accept_filter) != 0) { nls[n].delete_deferred = 1; nls[n].add_deferred = 1; } } else if (ls[i].accept_filter) { nls[n].delete_deferred = 1; } else if (nls[n].accept_filter) { nls[n].add_deferred = 1; } #endif #if (NGX_HAVE_DEFERRED_ACCEPT && defined TCP_DEFER_ACCEPT) if (ls[n].deferred_accept && !nls[n].deferred_accept) { nls[n].delete_deferred = 1; } else if (ls[i].deferred_accept != nls[n].deferred_accept) { nls[n].add_deferred = 1; } #endif break; } } if (nls[n].fd == -1) { nls[n].open = 1; } } } else { ls = cycle->listening.elts; for (i = 0; i < cycle->listening.nelts; i++) { ls[i].open = 1; #if (NGX_HAVE_DEFERRED_ACCEPT && defined SO_ACCEPTFILTER) if (ls[i].accept_filter) { ls[i].add_deferred = 1; } #endif #if (NGX_HAVE_DEFERRED_ACCEPT && defined TCP_DEFER_ACCEPT) if (ls[i].deferred_accept) { ls[i].add_deferred = 1; } #endif } } if (ngx_open_listening_sockets(cycle) != NGX_OK) { goto failed; } if (!ngx_test_config) { ngx_configure_listening_sockets(cycle); } /* commit the new cycle configuration */ if (!ngx_use_stderr && cycle->log->file->fd != ngx_stderr) { if (ngx_set_stderr(cycle->log->file->fd) == NGX_FILE_ERROR) { ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, ngx_set_stderr_n " failed"); } } pool->log = cycle->log; for (i = 0; ngx_modules[i]; i++) { if (ngx_modules[i]->init_module) { if (ngx_modules[i]->init_module(cycle) != NGX_OK) { /* fatal */ exit(1); } } } /* close and delete stuff that lefts from an old cycle */ /* free the unnecessary shared memory */ opart = &old_cycle->shared_memory.part; oshm_zone = opart->elts; for (i = 0; /* void */ ; i++) { if (i >= opart->nelts) { if (opart->next == NULL) { goto old_shm_zone_done; } opart = opart->next; oshm_zone = opart->elts; i = 0; } part = &cycle->shared_memory.part; shm_zone = part->elts; for (n = 0; /* void */ ; n++) { if (n >= part->nelts) { if (part->next == NULL) { break; } part = part->next; shm_zone = part->elts; n = 0; } if (oshm_zone[i].shm.name.len == shm_zone[n].shm.name.len && ngx_strncmp(oshm_zone[i].shm.name.data, shm_zone[n].shm.name.data, oshm_zone[i].shm.name.len) == 0) { goto live_shm_zone; } } ngx_shm_free(&oshm_zone[i].shm); live_shm_zone: continue; } old_shm_zone_done: /* close the unnecessary listening sockets */ ls = old_cycle->listening.elts; for (i = 0; i < old_cycle->listening.nelts; i++) { if (ls[i].remain || ls[i].fd == -1) { continue; } if (ngx_close_socket(ls[i].fd) == -1) { ngx_log_error(NGX_LOG_EMERG, log, ngx_socket_errno, ngx_close_socket_n " listening socket on %V failed", &ls[i].addr_text); } } /* close the unnecessary open files */ part = &old_cycle->open_files.part; file = part->elts; for (i = 0; /* void */ ; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; file = part->elts; i = 0; } if (file[i].fd == NGX_INVALID_FILE || file[i].fd == ngx_stderr) { continue; } if (ngx_close_file(file[i].fd) == NGX_FILE_ERROR) { ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, ngx_close_file_n " \"%s\" failed", file[i].name.data); } } ngx_destroy_pool(conf.temp_pool); if (ngx_process == NGX_PROCESS_MASTER || ngx_is_init_cycle(old_cycle)) { /* * perl_destruct() frees environ, if it is not the same as it was at * perl_construct() time, therefore we save the previous cycle * environment before ngx_conf_parse() where it will be changed. */ env = environ; environ = senv; ngx_destroy_pool(old_cycle->pool); cycle->old_cycle = NULL; environ = env; return cycle; } if (ngx_temp_pool == NULL) { ngx_temp_pool = ngx_create_pool(128, cycle->log); if (ngx_temp_pool == NULL) { ngx_log_error(NGX_LOG_EMERG, cycle->log, 0, "can not create ngx_temp_pool"); exit(1); } n = 10; ngx_old_cycles.elts = ngx_pcalloc(ngx_temp_pool, n * sizeof(ngx_cycle_t *)); if (ngx_old_cycles.elts == NULL) { exit(1); } ngx_old_cycles.nelts = 0; ngx_old_cycles.size = sizeof(ngx_cycle_t *); ngx_old_cycles.nalloc = n; ngx_old_cycles.pool = ngx_temp_pool; ngx_cleaner_event.handler = ngx_clean_old_cycles; ngx_cleaner_event.log = cycle->log; ngx_cleaner_event.data = &dumb; dumb.fd = (ngx_socket_t) -1; } ngx_temp_pool->log = cycle->log; old = ngx_array_push(&ngx_old_cycles); if (old == NULL) { exit(1); } *old = old_cycle; if (!ngx_cleaner_event.timer_set) { ngx_add_timer(&ngx_cleaner_event, 30000); ngx_cleaner_event.timer_set = 1; } return cycle; failed: if (!ngx_is_init_cycle(old_cycle)) { old_ccf = (ngx_core_conf_t *) ngx_get_conf(old_cycle->conf_ctx, ngx_core_module); if (old_ccf->environment) { environ = old_ccf->environment; } } /* rollback the new cycle configuration */ part = &cycle->open_files.part; file = part->elts; for (i = 0; /* void */ ; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; file = part->elts; i = 0; } if (file[i].fd == NGX_INVALID_FILE || file[i].fd == ngx_stderr) { continue; } if (ngx_close_file(file[i].fd) == NGX_FILE_ERROR) { ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, ngx_close_file_n " \"%s\" failed", file[i].name.data); } } if (ngx_test_config) { ngx_destroy_cycle_pools(&conf); return NULL; } ls = cycle->listening.elts; for (i = 0; i < cycle->listening.nelts; i++) { if (ls[i].fd == -1 || !ls[i].open) { continue; } if (ngx_close_socket(ls[i].fd) == -1) { ngx_log_error(NGX_LOG_EMERG, log, ngx_socket_errno, ngx_close_socket_n " %V failed", &ls[i].addr_text); } } ngx_destroy_cycle_pools(&conf); return NULL; }
void RNG_SystemInfoForRNG(void) { FILE *fp; char buf[BUFSIZ]; size_t bytes; const char * const *cp; char *randfile; #ifdef DARWIN #if TARGET_OS_IPHONE /* iOS does not expose a way to access environ. */ char **environ = NULL; #else char **environ = *_NSGetEnviron(); #endif #else extern char **environ; #endif #ifdef BEOS static const char * const files[] = { "/boot/var/swap", "/boot/var/log/syslog", "/boot/var/tmp", "/boot/home/config/settings", "/boot/home", 0 }; #else static const char * const files[] = { "/etc/passwd", "/etc/utmp", "/tmp", "/var/tmp", "/usr/tmp", 0 }; #endif #if defined(BSDI) static char netstat_ni_cmd[] = "netstat -nis"; #else static char netstat_ni_cmd[] = "netstat -ni"; #endif GiveSystemInfo(); bytes = RNG_GetNoise(buf, sizeof(buf)); RNG_RandomUpdate(buf, bytes); /* * Pass the C environment and the addresses of the pointers to the * hash function. This makes the random number function depend on the * execution environment of the user and on the platform the program * is running on. */ if (environ != NULL) { cp = (const char * const *) environ; while (*cp) { RNG_RandomUpdate(*cp, strlen(*cp)); cp++; } RNG_RandomUpdate(environ, (char*)cp - (char*)environ); } /* Give in system information */ if (gethostname(buf, sizeof(buf)) == 0) { RNG_RandomUpdate(buf, strlen(buf)); } GiveSystemInfo(); /* grab some data from system's PRNG before any other files. */ bytes = RNG_FileUpdate("/dev/urandom", SYSTEM_RNG_SEED_COUNT); /* If the user points us to a random file, pass it through the rng */ randfile = getenv("NSRANDFILE"); if ( ( randfile != NULL ) && ( randfile[0] != '\0') ) { char *randCountString = getenv("NSRANDCOUNT"); int randCount = randCountString ? atoi(randCountString) : 0; if (randCount != 0) { RNG_FileUpdate(randfile, randCount); } else { RNG_FileForRNG(randfile); } } /* pass other files through */ for (cp = files; *cp; cp++) RNG_FileForRNG(*cp); /* * Bug 100447: On BSD/OS 4.2 and 4.3, we have problem calling safe_popen * in a pthreads environment. Therefore, we call safe_popen last and on * BSD/OS we do not call safe_popen when we succeeded in getting data * from /dev/urandom. * * Bug 174993: On platforms providing /dev/urandom, don't fork netstat * either, if data has been gathered successfully. */ #if defined(BSDI) || defined(FREEBSD) || defined(NETBSD) \ || defined(OPENBSD) || defined(DARWIN) || defined(LINUX) \ || defined(HPUX) if (bytes) return; #endif #ifdef SOLARIS /* * On Solaris, NSS may be initialized automatically from libldap in * applications that are unaware of the use of NSS. safe_popen forks, and * sometimes creates issues with some applications' pthread_atfork handlers. * We always have /dev/urandom on Solaris 9 and above as an entropy source, * and for Solaris 8 we have the libkstat interface, so we don't need to * fork netstat. */ #undef DO_NETSTAT if (!bytes) { /* On Solaris 8, /dev/urandom isn't available, so we use libkstat. */ PRUint32 kstat_bytes = 0; if (SECSuccess != RNG_kstat(&kstat_bytes)) { PORT_Assert(0); } bytes += kstat_bytes; PORT_Assert(bytes); } #endif #ifdef DO_NETSTAT fp = safe_popen(netstat_ni_cmd); if (fp != NULL) { while ((bytes = fread(buf, 1, sizeof(buf), fp)) > 0) RNG_RandomUpdate(buf, bytes); safe_pclose(fp); } #endif }
/* - main - mostly argument parsing */ int main(int argc, char *argv[]) { int opt; int nbits = 0; int seedbits = DEFAULT_SEED_BITS; char *configdir = NULL; /* where the NSS databases reside */ char *password = NULL; /* password for token authentication */ while ((opt = getopt_long(argc, argv, "", opts, NULL)) != EOF) switch (opt) { case 'n': case 'p': fprintf(stderr, "%s: --noopt and --rounds options have been obsoleted - ignored\n", me); break; case 'v': /* verbose description */ verbose = 1; break; case 'r': fprintf(stderr, "%s: Warning: --random is obsoleted for --seeddev. It no longer specifies the random device used for obtaining random key material", me); /* FALLTHROUGH */ case 'S': /* nonstandard random device for seed */ device = optarg; break; case 'H': /* set hostname for output */ { size_t full_len = strlen(optarg); bool oflow = sizeof(outputhostname) - 1 < full_len; size_t copy_len = oflow ? sizeof(outputhostname) - 1 : full_len; memcpy(outputhostname, optarg, copy_len); outputhostname[copy_len] = '\0'; } break; case 'h': /* help */ printf("Usage:\t%s\n", usage); exit(0); break; case 'V': /* version */ printf("%s %s\n", me, ipsec_version_code()); exit(0); break; case 'c': /* nss configuration directory */ case 'd': /* -d is used for configdir with nss tools */ configdir = optarg; break; case 'P': /* token authentication password */ password = optarg; break; case 's': /* seed bits */ seedbits = atoi(optarg); if (PK11_IsFIPS()) { if (seedbits < DEFAULT_SEED_BITS) { fprintf(stderr, "%s: FIPS mode does not allow < %d seed bits\n", me, DEFAULT_SEED_BITS); exit(1); } } break; case '?': default: printf("Usage:\t%s\n", usage); exit(2); } if (outputhostname[0] == '\0') { if (gethostname(outputhostname, sizeof(outputhostname)) < 0) { fprintf(stderr, "%s: gethostname failed (%s)\n", me, strerror(errno)); exit(1); } } if (configdir == NULL) { configdir = NSSDIR; } if (argv[optind] == NULL) { /* default: spread bits between 3072 - 4096 in multiple's of 16 */ srand(time(NULL)); nbits = 3072 + 16 * (rand() % 64); } else { unsigned long u; err_t ugh = ttoulb(argv[optind], 0, 10, INT_MAX, &u); if (ugh != NULL) { fprintf(stderr, "%s: keysize specification is malformed: %s\n", me, ugh); exit(1); } nbits = u; } if (nbits < MIN_KEYBIT ) { fprintf(stderr, "%s: requested RSA key size of %d is too small - use %d or more\n", me, nbits, MIN_KEYBIT); exit(1); } else if (nbits > MAXBITS) { fprintf(stderr, "%s: overlarge bit count (max %d)\n", me, MAXBITS); exit(1); } else if (nbits % (BITS_PER_BYTE * 2) != 0) { fprintf(stderr, "%s: bit count (%d) not multiple of %d\n", me, nbits, (int)BITS_PER_BYTE * 2); exit(1); } rsasigkey(nbits, seedbits, configdir, password); exit(0); }
/* - main - mostly argument parsing */ int main(int argc, char *argv[]) { int opt; extern int optind; extern char *optarg; int errflg = 0; int i; int nbits; char *oldkeyfile = NULL; while ((opt = getopt_long(argc, argv, "", opts, NULL)) != EOF) switch (opt) { case 'v': /* verbose description */ verbose = 1; break; case 'r': /* nonstandard /dev/random */ device = optarg; break; case 'p': /* number of prime-check rounds */ nrounds = atoi(optarg); if (nrounds <= 0) { fprintf(stderr, "%s: rounds must be > 0\n", me); exit(2); } break; case 'o': /* reformat old key */ oldkeyfile = optarg; break; case 'H': /* set hostname for output */ strcpy(outputhostname, optarg); break; case 'n': /* don't optimize the private key */ do_lcm = 0; break; case 'h': /* help */ printf("Usage:\t%s\n", usage); printf("\tor\n"); printf("\t%s\n", usage2); exit(0); break; case 'V': /* version */ printf("%s ported from openswan 2.4.12\n", me); exit(0); break; case '?': default: errflg = 1; break; } if (errflg || optind != ((oldkeyfile != NULL) ? argc : argc-1)) { printf("Usage:\t%s\n", usage); printf("\tor\n"); printf("\t%s\n", usage2); exit(2); } if (outputhostname[0] == '\0') { i = gethostname(outputhostname, sizeof(outputhostname)); if (i < 0) { fprintf(stderr, "%s: gethostname failed (%s)\n", me, strerror(errno)); exit(1); } } if (oldkeyfile == NULL) { assert(argv[optind] != NULL); nbits = atoi(argv[optind]); } else nbits = getoldkey(oldkeyfile); if (nbits <= 0) { fprintf(stderr, "%s: invalid bit count (%d)\n", me, nbits); exit(1); } else if (nbits > MAXBITS) { fprintf(stderr, "%s: overlarge bit count (max %d)\n", me, MAXBITS); exit(1); } else if (nbits % (CHAR_BIT*2) != 0) { /* *2 for nbits/2-bit primes */ fprintf(stderr, "%s: bit count (%d) not multiple of %d\n", me, nbits, (int)CHAR_BIT*2); exit(1); } rsasigkey(nbits, (oldkeyfile == NULL) ? 0 : 1); exit(0); }
/* SETUP ROUTINES */ static int initial_set(void) { int prompt,status,i,tmporder; Real current_naik_epsilon; /* On node zero, read lattice size, seed, and send to others */ if(mynode()==0){ /* print banner */ printf("SU3 with improved KS action\n"); printf("Microcanonical simulation with refreshing\n"); printf("Rational function hybrid Monte Carlo algorithm\n"); printf("MIMD version %s\n",MILC_CODE_VERSION); printf("Machine = %s, with %d nodes\n",machine_type(),numnodes()); gethostname(hostname, 128); printf("Host(0) = %s\n",hostname); printf("Username = %s\n", getenv("USER")); time_stamp("start"); /* Print list of options selected */ node0_printf("Options selected...\n"); show_generic_opts(); show_generic_ks_opts(); show_generic_ks_md_opts(); #ifdef INT_ALG node0_printf("INT_ALG=%s\n",ks_int_alg_opt_chr()); #endif #if FERM_ACTION == HISQ show_su3_mat_opts(); show_hisq_links_opts(); show_hisq_force_opts(); #endif status=get_prompt(stdin, &prompt); IF_OK status += get_i(stdin, prompt,"nx", &par_buf.nx ); IF_OK status += get_i(stdin, prompt,"ny", &par_buf.ny ); IF_OK status += get_i(stdin, prompt,"nz", &par_buf.nz ); IF_OK status += get_i(stdin, prompt,"nt", &par_buf.nt ); #ifdef FIX_NODE_GEOM IF_OK status += get_vi(stdin, prompt, "node_geometry", par_buf.node_geometry, 4); #ifdef FIX_IONODE_GEOM IF_OK status += get_vi(stdin, prompt, "ionode_geometry", par_buf.ionode_geometry, 4); #endif #endif IF_OK status += get_i(stdin, prompt,"iseed", &par_buf.iseed ); /* Number of pseudofermions */ IF_OK status += get_i(stdin, prompt,"n_pseudo", &par_buf.n_pseudo ); if(par_buf.n_pseudo > MAX_N_PSEUDO){ printf("Error: Too many pseudofermion fields. Recompile. Current max is %d\n" ,MAX_N_PSEUDO); terminate(1); } /* get name of file containing rational function parameters */ IF_OK status += get_s(stdin, prompt, "load_rhmc_params", par_buf.rparamfile); /* beta, quark masses */ IF_OK status += get_f(stdin, prompt,"beta", &par_buf.beta ); IF_OK status += get_i(stdin, prompt,"n_dyn_masses", &par_buf.n_dyn_masses ); IF_OK status += get_vf(stdin, prompt, "dyn_mass", par_buf.dyn_mass, par_buf.n_dyn_masses); IF_OK status += get_vi(stdin, prompt, "dyn_flavors", par_buf.dyn_flavors, par_buf.n_dyn_masses); IF_OK status += get_f(stdin, prompt,"u0", &par_buf.u0 ); if(status>0) par_buf.stopflag=1; else par_buf.stopflag=0; } /* end if(mynode()==0) */ /* Node 0 broadcasts parameter buffer to all other nodes */ broadcast_bytes((char *)&par_buf,sizeof(par_buf)); if( par_buf.stopflag != 0 ) normal_exit(0); nx = par_buf.nx; ny = par_buf.ny; nz = par_buf.nz; nt = par_buf.nt; #ifdef FIX_NODE_GEOM for(i = 0; i < 4; i++) node_geometry[i] = par_buf.node_geometry[i]; #ifdef FIX_IONODE_GEOM for(i = 0; i < 4; i++) ionode_geometry[i] = par_buf.ionode_geometry[i]; #endif #endif iseed = par_buf.iseed; n_pseudo = par_buf.n_pseudo; strcpy(rparamfile,par_buf.rparamfile); this_node = mynode(); number_of_nodes = numnodes(); volume=nx*ny*nz*nt; total_iters=0; #ifdef HISQ_SVD_COUNTER hisq_svd_counter = 0; #endif #ifdef HISQ_FORCE_FILTER_COUNTER hisq_force_filter_counter = 0; #endif /* Load rational function parameters */ rparam = load_rhmc_params(rparamfile, n_pseudo); if(rparam == NULL)terminate(1); /* Determine the maximum rational fcn order */ max_rat_order = 0; for(i = 0; i < n_pseudo; i++){ if(rparam[i].MD.order > max_rat_order)max_rat_order = rparam[i].MD.order; if(rparam[i].GR.order > max_rat_order)max_rat_order = rparam[i].GR.order; if(rparam[i].FA.order > max_rat_order)max_rat_order = rparam[i].FA.order; } node0_printf("Maximum rational func order is %d\n",max_rat_order); /* Determine the number of different Naik masses and fill in n_orders_naik and n_pseudo_naik */ current_naik_epsilon = rparam[0].naik_term_epsilon; tmporder = 0; n_naiks = 0; n_order_naik_total = 0; for( i=0; i<n_pseudo; i++ ) { if( rparam[i].naik_term_epsilon != current_naik_epsilon ) { if( tmporder > 0 ) { n_orders_naik[n_naiks] = tmporder; eps_naik[n_naiks] = current_naik_epsilon; current_naik_epsilon = rparam[i].naik_term_epsilon; n_naiks++; n_order_naik_total += tmporder; tmporder = 0; } } tmporder += rparam[i].MD.order; n_pseudo_naik[n_naiks]++; } if( tmporder > 0 ) { n_orders_naik[n_naiks] = tmporder; eps_naik[n_naiks] = current_naik_epsilon; n_order_naik_total += tmporder; n_naiks++; } #if FERM_ACTION == HISQ // calculate epsilon corrections for different Naik terms if( 0 != eps_naik[0] ) { node0_printf("IN HISQ ACTION FIRST SET OF PSEUDO FERMION FIELDS SHOULD HAVE EPSILON CORRECTION TO NAIK TERM ZERO.\n"); terminate(1); } #endif node0_printf("Naik term correction structure of multi_x:\n"); node0_printf("n_naiks %d\n",n_naiks); for( i=0; i<n_naiks; i++ ) { node0_printf("n_pseudo_naik[%d]=%d\n", i, n_pseudo_naik[i]); node0_printf("n_orders_naik[%d]=%d\n", i, n_orders_naik[i]); #if FERM_ACTION == HISQ node0_printf("eps_naik[%d]=%f\n", i, eps_naik[i]); #endif } node0_printf("n_order_naik_total %d\n",n_order_naik_total); #if FERM_ACTION == HISQ if( n_naiks+1 > MAX_NAIK ) { node0_printf("MAX_NAIK=%d < n_naiks+1=%d\n", MAX_NAIK, n_naiks+1 ); node0_printf("Increase MAX_NAIK\n"); terminate(1); } #else /* HISQ */ if( n_naiks>1 ) { node0_printf("FOR ACTIONS OTHER THAN HISQ EPSILON CORRECTION IS NOT USED.\n"); node0_printf("ONLY ONE SET OF X LINKS IS USED.\n"); node0_printf("SET ALL naik_mass TO 0 IN RATIONAL FUNCTION FILE.\n"); terminate(1); } #endif /* HISQ */ beta = par_buf.beta; n_dyn_masses = par_buf.n_dyn_masses; for(i = 0; i < n_dyn_masses; i++){ dyn_mass[i] = par_buf.dyn_mass[i]; dyn_flavors[i] = par_buf.dyn_flavors[i]; } u0 = par_buf.u0; return(prompt); }
int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr,"usage %s <filename>\n", argv[0]); exit(0); } #ifdef GBN printf("Running Receiver based on GBN semantics\n"); #endif #ifdef SR printf("Running Receiver based on SR semantics\n"); #endif int sockfd; struct sockaddr_in serv_addr; socklen_t srvlen = sizeof(serv_addr); sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sockfd < 0)exception("ERROR opening socket"); bzero(&serv_addr, sizeof(serv_addr)); char* filename = argv[1]; serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(0); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)exception("ERROR on binding"); // record the address info char hostname[513]; hostname[512] = 0; if (gethostname(hostname, 512) != 0)exception("ERROR obtaining hostname"); if (getsockname(sockfd, (struct sockaddr *) &serv_addr, &srvlen) != 0)exception("ERROR obtaining sockname"); unsigned short portnumber = ntohs(serv_addr.sin_port); printf("Listening on %s:%u with protocol % d\n", hostname, portnumber, IPPROTO_UDP); { FILE* fp; fp=fopen(CONNECTION_INFO,"w"); if(fp==NULL)exception("file not found\n"); fprintf(fp, "%s %d", hostname, portnumber); fclose(fp); } // start receiving transmission char buffer[PACKET_SIZE_MAX+1]; Stack stack = createStack(STACK_SIZE_MULTIPLIER); stack.window_high = stack.size; stack = iteration(sockfd, buffer, stack); close(sockfd); { FILE* fp; fp=fopen(filename,"wb"); if(fp==NULL)exception("file not found\n"); unsigned int sn = 0; while (1) { Packet* p_ptr = stack.packets + sn; if (p_ptr->pt == EOT)break; fwrite(p_ptr->payload, p_ptr->pl - PACKET_SIZE_MIN, 1, fp); if(ferror(fp))exception("file IO failure\n"); sn++; } fclose(fp); } return 0; }
bool UdpComm::joinMulticast(const char* addrStr) { sockaddr_in group; if(!resolve(addrStr, 0, &group)) return false; //join multicast group for every interface if(IN_MULTICAST(ntohl(group.sin_addr.s_addr))) { #ifndef WINDOWS ip_mreq mreq; ifconf ifc; ifreq* item; char buf[1024]; ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; if(ioctl(sock, SIOCGIFCONF, &ifc) < 0) { std::cerr << "cannot get interface list" << std::endl; return false; } else { bool could_join(false); for(unsigned int i = 0; i < ifc.ifc_len / sizeof(ifreq); i++) { item = &ifc.ifc_req[i]; mreq.imr_multiaddr = group.sin_addr; mreq.imr_interface = ((sockaddr_in*)&item->ifr_addr)->sin_addr; if(0 == setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void*)&mreq, sizeof(mreq))) could_join = true; } if(!could_join) { std::cerr << "join multicast group failed for interface" << std::endl; return false; } } #else char host[128]; hostent* pHost; if(gethostname(host, sizeof(host)) < 0 || !(pHost = (hostent*)gethostbyname(host))) { std::cerr << "cannot get interface list" << std::endl; return false; } ip_mreq mreq; bool couldJoin(false); for(int i = 0; pHost->h_addr_list[i]; i++) { mreq.imr_multiaddr = group.sin_addr; mreq.imr_interface = *((in_addr*)pHost->h_addr_list[i]); if(setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mreq, sizeof(mreq)) == 0) couldJoin = true; } if(!couldJoin) { std::cerr << "join multicast group failed for interface" << std::endl; return false; } #endif return true; } else std::cerr << "not a multicast address" << std::endl; return false; }