当前位置: 首页>>代码示例>>C++>>正文


C++ send_error函数代码示例

本文整理汇总了C++中send_error函数的典型用法代码示例。如果您正苦于以下问题:C++ send_error函数的具体用法?C++ send_error怎么用?C++ send_error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了send_error函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: translate

static void translate(char *filename) {
  int count = 0;
  
  char *text = get_file_text(filename);
  char *start = text;
  if (text == NULL) {
    fprintf(stderr,"file %s not found\n",filename);
    return;
  }
  printf("translating %s:",filename);
  String result(1000,1000);
  while (*text) {
    if (isalpha(*text)) {
      String name;
      int len = get_name(text,name);
      if (len <= 0) {
	send_error(filename, start,text,"invalid identifier found",false);
	exit(-1);
      }
      text += len;
      suif_hash_map<String,String>::iterator iter = renames.find(name);
      if (iter != renames.end()) {
	count ++;
	result += (*iter).second;
      }
      else
	result += name;
    }
    else {
      result.push(*text);
      text ++;
    }
  }
  write_text(filename,(const char *)result);
  printf("%d substitutions made\n",count);
}// end translate
开发者ID:JehandadKhan,项目名称:roccc-2.0,代码行数:36,代码来源:rename.cpp

示例2: reply_with_perror_errno

void
reply_with_perror_errno (int err, const char *fs, ...)
{
  CLEANUP_FREE char *buf1 = NULL;
  CLEANUP_FREE char *buf2 = NULL;
  va_list args;
  int r;

  va_start (args, fs);
  r = vasprintf (&buf1, fs, args);
  va_end (args);

  if (r == -1) {
  error:
    perror ("vasprintf");
    exit (EXIT_FAILURE);
  }

  r = asprintf (&buf2, "%s: %s", buf1, strerror (err));
  if (r == -1)
    goto error;

  send_error (err, buf2);
}
开发者ID:rwmjones,项目名称:libguestfs,代码行数:24,代码来源:proto.c

示例3: cmd_resps

static bool cmd_resps(int srv, struct message *response)
{
  switch(current_request) {
  case(CMD_QUIT):
  case(CMD_END):
  case(CMD_PUSH):
  case(CMD_CLEAN):
  case(CMD_RESPS):
  case(CMD_RESPI):
  case(CMD_SIZE):
  case(CMD_NBCLI):
  case(CMD_NBSRV):
  case(CMD_NBRCV):
  case(CMD_NBSND):
  case(CMD_NBERR):
  case(CMD_MAXNSEC):
  case(CMD_MINNSEC):
  case(CMD_SUMNSEC):
    warnx("unexpected string from server");
    send_error(srv, E_INVAL);
    break;
  case(CMD_POP):
  case(CMD_POPF):
  case(CMD_GET):
  case(CMD_GETF):
    printf("%s\n", response->p_string);
    break;
  case(CMD_GETALL):
    printf("%d - %s\n", getall_counter++, response->p_string);
    break;
  default:
    break;
  }

  return true;
}
开发者ID:gawen947,项目名称:sunix,代码行数:36,代码来源:gpushd-client.c

示例4: client_thread

void* client_thread(void * client_queue) {

    int confd;
    status res;
    char* message = NULL;

    queue *cq = (queue *)client_queue;

    for(;;) {

        confd = dequeue(cq);
        printf("Connection %d\n acquired by thread %lu\n", confd, pthread_self());
        /*  Serve client until they close connection, or
         *  there is an error when attempting to read/write to/from them */
        do {
            /*  Obtain the request message as a string ending in '\r\n\r\n */
            if ((res = obtain_request(&message, confd)) != OK) {
                printf("Failed to obtain HTTP request from connection %d\n",confd);
                if (res != CONNECTION_ERROR) {
                   res = send_error(res, confd);
                }
            } else { /* If request message recieved successfully */
                res = respond_to(message, confd); 
            }
            
           
        } while (res != CONNECTION_ERROR);
        printf("Closing connection %d for thread %lu\n",confd, pthread_self());
        close(confd);       
    }
    /*  Should never get here, but if it does
     *  might as well attempt to avoid any memory leaks */
    free(message);
    return NULL;
        
}
开发者ID:RossMeikleham,项目名称:Webserver-C,代码行数:36,代码来源:web_server.c

示例5: kill_clients

void kill_clients(int pipe, const char* msg)
{
	struct client* p;                       /* Used to traverse clients linked list */
	int socket_buff[1];                     /* Send socket fd to main thread to remove from
	                                                           master fd list */

	// LOCK : Make sure clients is not altered while removing all client connections
	pthread_mutex_lock(&clients_lock);
	if (clients->count > 0) {
		p = clients->head;
		while (p != NULL) {
			// Send the socket fd to the main thread to remove
			// it from the master fd list
			socket_buff[0] = p->socket;
			write(pipe, socket_buff, 1);

			// Make sure that the socket is removed from
			// the master list before preceding any farther
			// (Removes a race condition which would cause
			// select() to break)
			pthread_mutex_lock(&slock);
			while (done == 0)
				pthread_cond_wait(&sready, &slock);
			done = 0;
			pthread_mutex_unlock(&slock);

			send_error(p->socket, msg);
			close(p->socket);
			remove_client_ref(p->socket);

			p = clients->head;
		}
	}
	// UNLOCK
	pthread_mutex_unlock(&clients_lock);
}
开发者ID:cmoresid,项目名称:dirapp,代码行数:36,代码来源:server.c

示例6: handle_init

void handle_init(MSICall *call, const MSIMessage *msg)
{
    assert(call);
    LOGGER_DEBUG(call->session->messenger->log,
                 "Session: %p Handling 'init' friend: %d", call->session, call->friend_number);

    if (!msg->capabilities.exists) {
        LOGGER_WARNING(call->session->messenger->log, "Session: %p Invalid capabilities on 'init'");
        call->error = msi_EInvalidMessage;
        goto FAILURE;
    }

    switch (call->state) {
        case msi_CallInactive: {
            /* Call requested */
            call->peer_capabilities = msg->capabilities.value;
            call->state = msi_CallRequested;

            if (invoke_callback(call, msi_OnInvite) == -1) {
                goto FAILURE;
            }
        }
        break;

        case msi_CallActive: {
            /* If peer sent init while the call is already
             * active it's probable that he is trying to
             * re-call us while the call is not terminated
             * on our side. We can assume that in this case
             * we can automatically answer the re-call.
             */

            LOGGER_INFO(call->session->messenger->log, "Friend is recalling us");

            MSIMessage out_msg;
            msg_init(&out_msg, requ_push);

            out_msg.capabilities.exists = true;
            out_msg.capabilities.value = call->self_capabilities;

            send_message(call->session->messenger, call->friend_number, &out_msg);

            /* If peer changed capabilities during re-call they will
             * be handled accordingly during the next step
             */
        }
        break;

        case msi_CallRequested: // fall-through
        case msi_CallRequesting: {
            LOGGER_WARNING(call->session->messenger->log, "Session: %p Invalid state on 'init'");
            call->error = msi_EInvalidState;
            goto FAILURE;
        }
    }

    return;
FAILURE:
    send_error(call->session->messenger, call->friend_number, call->error);
    kill_call(call);
}
开发者ID:GrayHatter,项目名称:toxcore,代码行数:61,代码来源:msi.c

示例7: ident

/*
	<% ident(arg, "arg", 'arg'); %>

	Syntax checking is very relaxed and all arguments are considered a
	string. Example, the following are the same:

		<% ident(foo); %>
		<% ident('foo'); %>

*/
int parse_asp(const char *path)
{
	char *buffer;
	char *cp;
	char *a, *b, *c;
	char x;
	int argc;
	char *argv[32];
	char *ident;
	const aspapi_t *api;

	if (f_read_alloc_string(path, &buffer, 128 * 1024) < 0) {
		free(buffer);
		if (!header_sent) send_error(500, NULL, "Read error");
		return 0;
	}

	if (!header_sent) send_header(200, NULL, mime_html, 0);

	// <% id(arg, arg); %>
	cp = buffer;
	while (*cp) {
		if ((b = strstr(cp, "%>")) == NULL) {
			web_puts(cp);
			break;
		}
		*b = 0;

		//xx <% <% %>
		//xx %>

		a = cp;
		while ((c = strstr(a, "<%")) != NULL) {
			a = c + 2;
		}

		if (a == cp) {
			*b = '%';
			b += 2;
			web_write(cp, b - cp);
			cp = b;
			continue;
		}

		web_write(cp, (a - cp) - 2);

		cp = b + 2;

		while (*a == ' ') ++a;
		ident = a;
		while (((*a >= 'a') && (*a <= 'z')) || ((*a >= 'A') && (*a <= 'Z')) || ((*a >= '0') && (*a <= '9')) || (*a == '_')) {
			++a;
		}
		if (ident == a) {
#ifdef DEBUG
			syslog(LOG_WARNING, "Identifier not found in %s @%u", path, a - buffer);
#endif
			continue;
		}
		b = a;
		while (*a == ' ') ++a;
		if (*a++ != '(') {
#ifdef DEBUG
			syslog(LOG_WARNING, "Expecting ( in %s @%u", path, a - buffer);
#endif
			continue;
		}
		*b = 0;

		// <% foo(123, "arg"); %>
		// a -----^            ^--- null

//		printf("\n[[['%s'\n", ident);

		argc = 0;
		while (*a) {
			while (*a == ' ') ++a;
			if (*a == ')') {
FINAL:
				++a;
				while ((*a == ' ') || (*a == ';')) ++a;
				if (*a != 0) break;

				for (api = aspapi; api->name; ++api) {
					if (strcmp(api->name, ident) == 0) {
						api->exec(argc, argv);
						break;
					}
				}

//.........这里部分代码省略.........
开发者ID:NieHao,项目名称:Tomato-RAF,代码行数:101,代码来源:parser.c

示例8: main

int main(int argc, char *argv[])
{
	int sock;
	struct sockaddr_in server_address;
	struct sockaddr_in client_address;
	int client_address_size;
	unsigned short server_port;
    int loss_percentage;

	if (argc < 3 || argc > 4){
		fprintf(stderr, "Usage:  %s <Server Port> <Loss Percentage> [-d]\n", argv[0]);
		exit(1);
	}

	server_port = atoi(argv[1]);
    loss_percentage = atoi(argv[2]);

    if (argc == 4 && strcmp(argv[3], "-d") == 0) {
        printf("Debug mode on.\n");
        debug = 1;
    }

    // Set up ARQ with loss_percentage and max packet size
    if (arq_init(loss_percentage, 0) < 0) {
        fprintf(stderr, "Unable to set up ARQ\n");
        fprintf(stderr, "Invalid loss percentage - Must be between 0 and 100.\n");
        exit(2);
    }
	// Create socket for incoming connections
	if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		fprintf(stderr, "Could not create socket.");
		exit(2);
	}

	memset(&server_address, 0, sizeof(server_address));
	server_address.sin_family = AF_INET;
	server_address.sin_addr.s_addr = htonl(INADDR_ANY);
	server_address.sin_port = htons(server_port);

	// Bind to the server address
	if (bind(sock, (struct sockaddr *) &server_address, sizeof(server_address)) < 0) {
		fprintf(stderr, "Could not bind to server address.");
		exit(2);
	}

	printf("Server started...\n");

	while(1) {
		client_address_size = sizeof(client_address);

        char *buffer = calloc(1, sizeof(char) * arq_get_max_packet_size());

        if (arq_recvfrom(sock, buffer, arq_get_max_packet_size(), 0, (struct sockaddr *) &client_address, &client_address_size) < 0) {
            continue;
        }

        char *client = inet_ntoa(client_address.sin_addr);

        int split_size = 0;
        char **split_buffer = split(buffer, " ", &split_size);

        free(buffer);

        if (split_size > 0) {
            // Handle REQUEST
            if (strcmp(split_buffer[0], "REQUEST") == 0) {
                if (split_size >= 2) {
                    // Got a request with a file name
                    char *file = split_buffer[1];

                    printf("%s - Received request for %s\n", client, file);

                    FILE *fp = fopen(file, "r");

                    if (!fp) {
                        // Oh no the file error
                        printf("%s - Could not open file %s\n", client, file);

                        if (send_error(sock, (struct sockaddr *) &client_address, client_address_size) < 0) {
                            fprintf(stderr, "%s - Unable to contact client.\n", client);
                        }
                    } else {
                        // File was opened successfully
                        printf("%s - Starting transfer\n", client);

                        // 5 b/c number of bytes for "SEND "
                        const int command_size = 5;
                        int chunk_size = arq_get_max_data_size() - command_size;

                        int read_chunk_size = 0;

                        do {
                            void *chunk = calloc((size_t) chunk_size, sizeof(char));
                            read_chunk_size = fread(chunk, 1, chunk_size, fp);

                            if (read_chunk_size > 0) {
                                buffer = calloc(arq_get_max_packet_size(), sizeof(char));

                                sprintf(buffer, "SEND %s", (char *) chunk);

//.........这里部分代码省略.........
开发者ID:Tanner,项目名称:File-Transfer,代码行数:101,代码来源:server.c

示例9: while

void *worker(void *data)
{
  int hSocket;
  char pBuffer[BUFFER_SIZE];
  char method[BUFFER_SIZE];
  char path[BUFFER_SIZE];
  while(1)
    {
      pthread_mutex_lock(&lock);
      while(num == 0)
	pthread_cond_wait(&empty, &lock);
      hSocket = queue[rem];
      rem = (rem + 1) % Q_SIZE;
      num--;
      pthread_mutex_unlock(&lock);
      pthread_cond_signal(&full);
      
      /* Process information */ 
      read(hSocket, pBuffer, BUFFER_SIZE);
      
      if(sscanf(pBuffer, "%[^ ] %[^ ]", method, path) < 2)
      {
	send_error(hSocket, BAD_REQUEST, "Not the accepted protocol");
	continue;
      }
      
      if(strcasecmp(method, "get") != 0)
      {
	send_error(hSocket, NOT_IMPLEMENTED, "Only implemented GET");
	continue;
      }

      char *path_ptr = path;
      if(path[0] == '/')
	path_ptr = &(path[1]);
      
      int len = strlen(path_ptr);
      if(*path_ptr == '/' || strcmp(path_ptr, "..") == 0 || strncmp(path_ptr, "../", 3) == 0 || strstr(path_ptr, "/../") != NULL || strcmp(&(path_ptr[len-3]), "/..") == 0)
      {
	send_error(hSocket, BAD_REQUEST, "Tried to access a private file");
	continue;
      }
      
      FILE *f = fopen(path_ptr, "r");
      if(f)
      {
	fgets(pBuffer, BUFFER_SIZE, f);
	write(hSocket, pBuffer, strlen(pBuffer));
      }
      else
      {
	send_error(hSocket, NOT_FOUND, "Unable to locate file");
	continue;
      } 
     
      fclose(f);
      if(close(hSocket) == SOCKET_ERROR)
      {
	printf("Could not close socket\n");
	continue;
      }
    }
  return NULL;
}
开发者ID:mscott64,项目名称:8803_project1,代码行数:64,代码来源:server.c

示例10: handle_request

int handle_request(int connfd) {
    char *buf = (char *) malloc(MAXLINE);
    char *method, *uri, *version;
    char *fullpath;
    int nread;
    struct stat fs;
    int is_dir;
    int error_code = 0, ret = 0;
    rio_t rio;

    rio_initb(&rio, connfd);

    nread = rio_readlineb(&rio, buf, MAXLINE - 1);
    if (nread == 0) {
        error_code = 400;
        goto fail;
    } else if (buf[nread - 1] != '\n') {
        error_code = 414;
        goto fail;
    } else {
        buf[nread - 1] = 0;
        if (nread >= 2 && buf[nread - 2] == '\r') {
            buf[nread - 2] = 0;
        }
    }
    method = buf;
    for (uri = method; *uri != 0; ++uri) {
        if (*uri == ' ') {
            *uri = 0;
            ++uri;
            break;
        }
    }
    for (version = uri; *version != 0; ++version) {
        if (*version == ' ') {
            *version = 0;
            ++version;
            break;
        }
    }
    if (*method == 0 || *uri == 0 || *version == 0) {
        /* missing some fields in http request header */
        error_code = 400;
        goto fail;
    }
    if (strcmp(method, "GET") != 0) {
        /* only allow GET method */
        error_code = 405;
        goto fail;
    }

    goto next;

fail:
    free(buf);
    if (error_code > 0) {
        send_error(connfd, error_code);
        return 0;
    }

next:
    /* translate path and dispatch HTTP request according to path */
    uri = translate_path(uri);
    fullpath = (char *) malloc(strlen(uri) + 2);
    fullpath[0] = '.';
    strcpy(fullpath + 1, uri);

    if (stat(fullpath, &fs) != 0) {
        send_error(connfd, 404);
    } else {
        is_dir = S_ISDIR(fs.st_mode);
        if (is_dir) {
            if (fullpath[(int) strlen(fullpath) - 1] != '/') {
                send_response(connfd, 301, NULL);
                send_header(connfd, "Location", "%s/", fullpath);
                end_headers(connfd);
            } else {
                ret = list_directory(connfd, fullpath);
            }
        } else {
            ret = fetch_file(connfd, fullpath);
        }
    }
    free(fullpath);
    free(buf);

    return ret;
}
开发者ID:foreverbell,项目名称:playground,代码行数:88,代码来源:http-server.c

示例11: main

int main(int argc, char **argv) 
{
  ETERM *tuplep;
  ETERM *fnp, *argp;
  byte buf[1024];

  sqlite3 *db;
  char *zErrMsg = 0;
  int rc;

  log = fopen("/tmp/sqlite_port.log", "a+");
  fprintf(log, "******start log (%s)******\n", argv[1]);
  fflush(log);

  rc = sqlite3_open(argv[1], &db);
  if (rc) {
    sqlite3_close(db);
    exit(1);
  }

  erl_init(NULL, 0);

  while (read_cmd(buf) > 0) {
    tuplep = erl_decode(buf);
    fnp = erl_element(1, tuplep);
    argp = erl_element(2, tuplep);
    
    if (strncmp((const char *)ERL_ATOM_PTR(fnp), "close", 5) == 0) {
      fprintf(log, "closing sqlite3_close\n");
      fflush(log);

      sqlite3_close(db);
      break;
    }
    else if (strncmp((const char *)ERL_ATOM_PTR(fnp), "list_tables", 11) == 0) {
      fprintf(log, "calling list_tables\n");

      result = 0;

      rc = sqlite3_exec(db, MASTER_QUERY, list_tables, 0, &zErrMsg);
      if (rc != SQLITE_OK) {
	send_error(zErrMsg);
	sqlite3_free(zErrMsg);
      }
      else if (result != 0)  {
	send_result();
      }
      else {
	// not an error and no results. still need to return something
	send_ok();
      } 

      fflush(log);

    }
    else if (strncmp((const char *)ERL_ATOM_PTR(fnp), "sql_exec", 8) == 0) {
      fprintf(log, "calling sqlite3_exec %s\n", erl_iolist_to_string(argp));

      result = 0;

      rc = sqlite3_exec(db, erl_iolist_to_string(argp), callback, 0, &zErrMsg);
      if (rc != SQLITE_OK) {
	send_error(zErrMsg);
	sqlite3_free(zErrMsg);
      }
      else if (result != 0)  {
	send_result();
      }
      else {
	// not an error and no results. still need to return something
	send_ok();
      } 

      fflush(log);
    }

    erl_free_compound(tuplep);
    erl_free_term(fnp);
    erl_free_term(argp);
  }

  fprintf(log, "******end log******\n");
  fclose(log);
  return 0;
}
开发者ID:avtobiff,项目名称:sqlite-erlang,代码行数:85,代码来源:sqlite_port.c

示例12: monotonic_clock


//.........这里部分代码省略.........
							ERR_CS << "Unrecognized admin reload argument: " << ctl[1] << '\n';
						}
					} else {
						LOG_CS << "Reloading all configuration...\n";
						need_reload = 1;
						// Avoid flush timer ellapsing
						continue;
					}
				} else if(ctl == "setpass") {
					if(ctl.args_count() != 2) {
						ERR_CS << "Incorrect number of arguments for 'setpass'\n";
					} else {
						const std::string& addon_id = ctl[1];
						const std::string& newpass = ctl[2];
						config& campaign = get_campaign(addon_id);

						if(!campaign) {
							ERR_CS << "Add-on '" << addon_id << "' not found, cannot set passphrase\n";
						} else if(newpass.empty()) {
							// Shouldn't happen!
							ERR_CS << "Add-on passphrases may not be empty!\n";
						} else {
							campaign["passphrase"] = newpass;
							write_config();

							LOG_CS << "New passphrase set for '" << addon_id << "'\n";
						}
					}
				} else {
					ERR_CS << "Unrecognized admin command: " << ctl.full() << '\n';
				}
			}

			const time_t cur_ts = monotonic_clock();
			// Write config to disk every ten minutes.
			if(force_flush || labs(cur_ts - last_ts) >= 10*60) {
				write_config();
				last_ts = cur_ts;
			}

			network::process_send_queue();

			sock = network::accept_connection();
			if(sock) {
				LOG_CS << "received connection from " << network::ip_address(sock) << "\n";
			}

			config data;

			while((sock = network::receive_data(data, 0)) != network::null_connection)
			{
				config::all_children_iterator i = data.ordered_begin();

				if(i != data.ordered_end()) {
					// We only handle the first child.
					const config::any_child& c = *i;

					request_handlers_table::const_iterator j
							= handlers_.find(c.key);

					if(j != handlers_.end()) {
						// Call the handler.
						j->second(this, request(c.key, c.cfg, sock));
					} else {
						send_error("Unrecognized [" + c.key + "] request.",
								   sock);
					}
				}
			}
		} catch(network::error& e) {
			if(!e.socket) {
				ERR_CS << "fatal network error: " << e.message << "\n";
				throw;
			} else {
				LOG_CS << "client disconnect: " << e.message << " " << network::ip_address(e.socket) << "\n";
				e.disconnect();
			}
		} catch(const config::error& e) {
			network::connection err_sock = 0;
			network::connection const * err_connection = boost::get_error_info<network::connection_info>(e);

			if(err_connection != NULL) {
				err_sock = *err_connection;
			}

			if(err_sock == 0 && sock > 0) {
				err_sock = sock;
			}

			if(err_sock) {
				ERR_CS << "client disconnect due to exception: " << e.what() << " " << network::ip_address(err_sock) << "\n";
				network::disconnect(err_sock);
			} else {
				throw;
			}
		}

		SDL_Delay(20);
	}
}
开发者ID:numo16,项目名称:wesnoth,代码行数:101,代码来源:campaign_server.cpp

示例13: process

int process(FILE *f)
{
  char buf[4096];
  char *method;
  char *path;
  char *protocol;
  struct stat statbuf;
  char pathbuf[4096];
  int len;

  if (!fgets(buf, sizeof(buf), f)) return -1;
  printf("URL: %s", buf);

  method = strtok(buf, " ");
  path = strtok(NULL, " ");
  protocol = strtok(NULL, "\r");
  if (!method || !path || !protocol) return -1;

  fseek(f, 0, SEEK_CUR); // Force change of stream direction

  if (strcasecmp(method, "GET") != 0)
    send_error(f, 501, "Not supported", NULL, "Method is not supported.");
  else if (stat(path, &statbuf) < 0)
    send_error(f, 404, "Not Found", NULL, "File not found.");
  else if (S_ISDIR(statbuf.st_mode))
  {
    len = strlen(path);
    if (len == 0 || path[len - 1] != '/')
    {
      snprintf(pathbuf, sizeof(pathbuf), "Location: %s/", path);
      send_error(f, 302, "Found", pathbuf, "Directories must end with a slash.");
    }
    else
    {
      snprintf(pathbuf, sizeof(pathbuf), "%sindex.html", path);
      if (stat(pathbuf, &statbuf) >= 0)
        send_file(f, pathbuf, &statbuf);
      else
      {
        DIR *dir;
        struct dirent *de;

        send_headers(f, 200, "OK", NULL, "text/html", -1, statbuf.st_mtime);
        fprintf(f, "<HTML><HEAD><TITLE>Index of %s</TITLE></HEAD>\r\n<BODY>", path);
        fprintf(f, "<H4>Index of %s</H4>\r\n<PRE>\n", path);
        fprintf(f, "Name                             Last Modified              Size\r\n");
        fprintf(f, "<HR>\r\n");
        if (len > 1) fprintf(f, "<A HREF=\"..\">..</A>\r\n");

        dir = opendir(path);
        while ((de = readdir(dir)) != NULL)
        {
          char timebuf[32];
          struct tm *tm;

          strcpy(pathbuf, path);
          strcat(pathbuf, de->d_name);

          stat(pathbuf, &statbuf);
          tm = gmtime(&statbuf.st_mtime);
          strftime(timebuf, sizeof(timebuf), "%d-%b-%Y %H:%M:%S", tm);

          fprintf(f, "<A HREF=\"%s%s\">", de->d_name, S_ISDIR(statbuf.st_mode) ? "/" : "");
          fprintf(f, "%s%s", de->d_name, S_ISDIR(statbuf.st_mode) ? "/</A>" : "</A> ");
          if (strlen(de->d_name) < 32) fprintf(f, "%*s", 32 - strlen(de->d_name), "");
          if (S_ISDIR(statbuf.st_mode))
            fprintf(f, "%s\r\n", timebuf);
          else
            fprintf(f, "%s %10d\r\n", timebuf, statbuf.st_size);
        }
        closedir(dir);

        fprintf(f, "</PRE>\r\n<HR>\r\n<ADDRESS>%s</ADDRESS>\r\n</BODY></HTML>\r\n", SERVER);
      }
    }
  }
  else
    send_file(f, path, &statbuf);

  return 0;
}
开发者ID:renjithrr,项目名称:htp,代码行数:81,代码来源:server.c

示例14: int

void *plmc_client_mgr(void *arguments)
{
	thread_entry *tentry;
	thread_data *tdata;
	char command[PLMC_CMD_NAME_MAX_LENGTH];
	char result[PLMC_MAX_TCP_DATA_LEN];
	char ee_id[PLMC_EE_ID_MAX_LENGTH];
	PLMC_cmd_idx cmd_enum;
	int sockfd, retval, bytes_received;
	struct timeval tv;
	int( *callback)(tcp_msg *);
	tentry = (thread_entry *) arguments;
	tdata = &(tentry->thread_d);
	command[0] ='\0';
	
	/* Adding 10 seconds to the plmc_cmd_timeout_secs in the 
	*  plmcd.conf file
	*/
	tv.tv_sec = config.plmc_cmd_timeout_secs + 10;
	tv.tv_usec = 0;
	tcp_msg tcpmsg;
	
	#ifdef PLMC_LIB_DEBUG
	fprintf(plmc_lib_debug, "plmc_client_mgr started up\n");
	fflush(plmc_lib_debug);
	#endif 
	
	/* Lock to get the socket */
	if (pthread_mutex_lock(&tdata->td_lock) != 0) {
		syslog(LOG_ERR, "plmc_lib: plmc_client_mgr encountered an "
				"error getting a lock for a client");
		send_error(PLMC_LIBERR_SYSTEM_RESOURCES,
				PLMC_LIBACT_EXIT_THREAD, NULL, PLMC_NOOP_CMD);
		pthread_exit((void *)NULL);
	}
	sockfd = tentry->thread_d.socketfd;
	strncpy(ee_id, tdata->ee_id, PLMC_EE_ID_MAX_LENGTH);
	ee_id[PLMC_EE_ID_MAX_LENGTH - 1] = '\0';
	
	/* 
	* There is a new command, copy it locally and return the 
	* lock 
	*/
	strncpy(command, tdata->command, PLMC_CMD_NAME_MAX_LENGTH);
	command[PLMC_CMD_NAME_MAX_LENGTH - 1] = '\0';
	cmd_enum = plmc_cmd_string_to_enum(tdata->command);
	/* Get the callback as well */
	callback = tdata->callback;
		
	/* Unlock */
	if (pthread_mutex_unlock(&tdata->td_lock) != 0) {
		syslog(LOG_ERR, "plmc_lib: encountered an "
			"error unlocking a client mutex");
		send_error(PLMC_LIBERR_SYSTEM_RESOURCES, 
				PLMC_LIBACT_UNDEFINED, ee_id, cmd_enum);
	}			
	
	#ifdef PLMC_LIB_DEBUG
	fprintf(plmc_lib_debug, "plmc_client_mgr got a new command %s for "
						"ee_id %s\n", command, ee_id);
	fflush(plmc_lib_debug);
	#endif 
	
	/* 
	* Change the socket option so that it waits for tv.tv_sec seconds 
	* for a respons 
	*/
	if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, 
							sizeof tv) < 0)  {
		syslog(LOG_ERR, "plmc_lib: encountered an error during "
				"a call to setsockopt() from client_mgr");
		syslog(LOG_ERR, "plmc_lib: errnor is %d", errno);
		syslog(LOG_ERR, "plmc_lib: Closing socket and exiting "
								"client_mgr");
		send_error(PLMC_LIBERR_SYSTEM_RESOURCES, 
				PLMC_LIBACT_EXIT_THREAD, ee_id, cmd_enum);
		if (close_socket(sockfd) !=0) {
			syslog(LOG_ERR, "plmc_lib: encountered an error "
					"during a call to close_socket");
		}
		pthread_exit((void *)NULL);
	}

	#ifdef PLMC_LIB_DEBUG
	fprintf(plmc_lib_debug, "plmc_client_mgr: Sending command to client\n");
	fflush(plmc_lib_debug);
	#endif 
	/* Send the command to PLMc */
	retval = send(sockfd, command, strlen(command), 0);
	if (retval <= 0) {
		syslog(LOG_ERR, "plmc_lib: Client Mgr encountered an error "
				"during a call to send(). Leaving cleanup for "
				"connection mgr");
		syslog(LOG_ERR, "plmc_lib: errnor is %d", errno);
		/* Connection MGR will send error to plmc_lib */
		pthread_exit((void *)NULL);
	}
		
	/* Get the response */
	bytes_received = recv(sockfd, result, PLMC_MAX_TCP_DATA_LEN, 0);
//.........这里部分代码省略.........
开发者ID:helioloureiro,项目名称:opensaf-fork,代码行数:101,代码来源:plmc_lib_internal.c

示例15: list_directory

int list_directory(int connfd, const char *dirname) {
    char *buf;
    DIR *d;
    struct dirent *dir;
    struct stat fs;
    const char *item_fmt;
    const char *filename;
    char *fullname;
    int len1, len2, nwritten = 0;
    int ret;

    d = opendir(dirname);
    if (d) {

        buf = (char *) malloc(MAXBUF);

        /* TODO: escape or quote dirname / filename */
        nwritten += snprintf(buf + nwritten, MAXBUF - nwritten,
                             "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n"
                             "<html>\n"
                             "<title>Directory listing for %s</title>\n"
                             "<body>\n"
                             "<h2>Directory listing for %s</h2>\n"
                             "<hr>\n"
                             "<ul>\n", dirname + 1, dirname + 1);

        while ((dir = readdir(d)) != NULL) {
            filename = dir->d_name;

            if (strcmp(filename, ".") == 0 || strcmp(filename, "..") == 0) {
                continue;
            } else {
                len1 = strlen(dirname);
                len2 = strlen(filename);
                fullname = (char *) malloc(len1 + len2 + 1);
                strcpy(fullname, dirname);
                strcpy(fullname + len1, filename);
                fullname[len1 + len2] = 0;

                if (strcasecmp(filename, "index.html") == 0 || strcasecmp(filename, "index.htm") == 0) {
                    ret = fetch_file(connfd, fullname);
                    free(fullname);
                    free(buf);
                    closedir(d);
                    return ret;
                } else {
                    stat(fullname, &fs);
                    if (S_ISDIR(fs.st_mode)) {
                        item_fmt = "<li><a href=\"%s/\">%s/</a>\n";
                    } else {
                        item_fmt = "<li><a href=\"%s\">%s</a>\n";
                    }
                    nwritten += snprintf(buf + nwritten, MAXBUF - nwritten,
                                         item_fmt, filename, filename);
                }

                free(fullname);
            }
        }
        closedir(d);

        nwritten += snprintf(buf + nwritten, MAXBUF - nwritten,
                             "</ul>\n"
                             "<hr>\n"
                             "</body>\n"
                             "</html>\n");

        send_response(connfd, 200, NULL);
        send_header(connfd, "Content-Type", "text/html");
        send_header(connfd, "Content-Length", "%d", nwritten);
        end_headers(connfd);
        rio_writen(connfd, buf, nwritten);

        free(buf);

        return 1;
    }

    send_error(connfd, 404);

    return 0;
}
开发者ID:foreverbell,项目名称:playground,代码行数:82,代码来源:http-server.c


注:本文中的send_error函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。